@markus-global/cli 0.9.6-rc.3 → 0.9.6
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/web-ui/assets/{CommentInput-M8fK80hQ.js → CommentInput-CBNbViJY.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-RSmGZz7B.js → ContentRenderer-DE3pZgeX.js} +2 -2
- package/dist/web-ui/assets/{Deliverables-20FdLf3j.js → Deliverables-Cx97uG2f.js} +1 -1
- package/dist/web-ui/assets/{Notifications-BuQgoq8N.js → Notifications-DnOdXHNc.js} +1 -1
- package/dist/web-ui/assets/{Search-C1J7hOxM.js → Search-BxFLlgcf.js} +1 -1
- package/dist/web-ui/assets/{Settings-CkWlYwww.js → Settings-D0i8Lnsk.js} +1 -1
- package/dist/web-ui/assets/{Store-CT21QIvl.js → Store-BELkjEqO.js} +1 -1
- package/dist/web-ui/assets/{Team-IGIT0ic-.js → Team-D_C3tvWh.js} +4 -4
- package/dist/web-ui/assets/{Work-8pPQZSGi.js → Work-DpRdSwD5.js} +1 -1
- package/dist/web-ui/assets/{arc-CXP8TJ4Z.js → arc-CyhYnNcy.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CnhgvvRo.js → architectureDiagram-3BPJPVTR-BYIYNrCP.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-DqRVjDFQ.js → blockDiagram-GPEHLZMM-Tj8Yz066.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DZSmS4Ru.js → c4Diagram-AAUBKEIU-Ifa4IAJa.js} +1 -1
- package/dist/web-ui/assets/channel-B33xJsNY.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-yFUiknTK.js → chunk-2J33WTMH-CNSbz4EK.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-Bnb6oBqb.js → chunk-4BX2VUAB-DhNtaIHh.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-Cs5hI6M_.js → chunk-55IACEB6-WUpOSLP9.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-CpbwsGyE.js → chunk-727SXJPM-BJV_Jz1H.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-C8FbSLr-.js → chunk-AQP2D5EJ-BHu_5o0Y.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-BE8b8Z18.js → chunk-FMBD7UC4-CfxugWTK.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BkCuxycB.js → chunk-ND2GUHAM-hIFBUDLZ.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-DNqwxqAc.js → chunk-QZHKN3VN-DF0OYrsG.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BePK-BYt.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BePK-BYt.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DngEBUuJ.js → cose-bilkent-S5V4N54A-C3LM31P0.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-D_y-XkrB.js → dagre-BM42HDAG-C_m79Kes.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-j-8mrd3C.js → diagram-2AECGRRQ-D8liSSSE.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-CTpQszOj.js → diagram-5GNKFQAL-DqtsU-bB.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-CQV4k1zW.js → diagram-KO2AKTUF-C6zkMDRo.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-DXHceUfT.js → diagram-LMA3HP47-Dx2JnYqj.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-C0e6dNqB.js → diagram-OG6HWLK6-ZI_lN3Ui.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-Ae0H11G8.js → erDiagram-TEJ5UH35-DQ5VepuZ.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DIi7PQOc.js → flowDiagram-I6XJVG4X-6GiDnWFL.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-SsfqU1vk.js → ganttDiagram-6RSMTGT7-D6HROKP8.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BVihrQh9.js → gitGraphDiagram-PVQCEYII-CXm0stFt.js} +1 -1
- package/dist/web-ui/assets/{index-DteFMYqJ.js → index-BMzsi3-i.js} +4 -4
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CkfGEgxq.js → infoDiagram-5YYISTIA-C1RxESvu.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-B1ZImZ5e.js → ishikawaDiagram-YF4QCWOH-K65PlAf9.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BQy-ncy5.js → journeyDiagram-JHISSGLW-_Rs_Vudv.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-CDVZZgmZ.js → kanban-definition-UN3LZRKU-Jf6WnoNW.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-C8KDDcZX.js → mermaid.core-C6jfI8lj.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DPxO_8hK.js → mindmap-definition-RKZ34NQL-CuVR_m6C.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-DHlWXx9i.js → pieDiagram-4H26LBE5-BiPJBXLU.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CZ6UHdQ6.js → quadrantDiagram-W4KKPZXB-C4hoAfNv.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CqqJ21Fa.js → requirementDiagram-4Y6WPE33-BmjjjPuK.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-rXKj-Lk5.js → sankeyDiagram-5OEKKPKP-ts7xFx2o.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-B6ByYG8_.js → sequenceDiagram-3UESZ5HK-C3je_x5z.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BF_GF2mS.js → stateDiagram-AJRCARHV-CREzVZ-3.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CZU51KZ-.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-DQezudig.js → timeline-definition-PNZ67QCA-CriALCTC.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-DIUsjJzR.js → vennDiagram-CIIHVFJN-Bc9NNe3M.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-DV3IEIDa.js → wardley-L42UT6IY-psF9We_q.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-brc2hegH.js → wardleyDiagram-YWT4CUSO-DNZ9Jdgm.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BWvdfON5.js → xychartDiagram-2RQKCTM6-COezi66E.js} +1 -1
- package/dist/web-ui/index.html +1 -1
- package/package.json +1 -1
- package/dist/web-ui/assets/channel-BM-bbV7_.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DvmFO1VX.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DvmFO1VX.js +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DnrCJfaD.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{r as C,k as fx,u as Pt,O as YS,j as h,y as ma,ac as US,a as Sf,b as _f,P as Ht,c as wf,l as J,w as gt,M as HS,A as _s,n as Or,V as Wa,i as px,ad as GS,ae as KS,af as JS,ag as ym,ah as Sl,d as mx,ai as gx,h as Ox,p as Oc,aj as e_,ak as t_,al as Sm,am as s_,a3 as i_,a5 as xx,a4 as vx,X as r_,an as n_,ao as o_,_ as bx,E as _m,ap as xn,aq as a_,ar as l_,as as ed,at as wm,au as c_,B as td,D as km,o as Cm,s as h_,m as d_,Q as Pm,q as Tm,t as u_,av as f_,v as p_,aw as Qm,x as m_,ax as g_,z as O_,ay as x_,az as v_,R as b_,aA as y_,F as S_,aB as Jl,aC as ec,C as __}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BMzsi3-i.js","assets/index-C9gwAZYM.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as C,k as fx,u as Pt,O as YS,j as h,y as ma,ac as US,a as Sf,b as _f,P as Ht,c as wf,l as J,w as gt,M as HS,A as _s,n as Or,V as Wa,i as px,ad as GS,ae as KS,af as JS,ag as ym,ah as Sl,d as mx,ai as gx,h as Ox,p as Oc,aj as e_,ak as t_,al as Sm,am as s_,a3 as i_,a5 as xx,a4 as vx,X as r_,an as n_,ao as o_,_ as bx,E as _m,ap as xn,aq as a_,ar as l_,as as ed,at as wm,au as c_,B as td,D as km,o as Cm,s as h_,m as d_,Q as Pm,q as Tm,t as u_,av as f_,v as p_,aw as Qm,x as m_,ax as g_,z as O_,ay as x_,az as v_,R as b_,aA as y_,F as S_,aB as Jl,aC as ec,C as __}from"./index-BMzsi3-i.js";import{r as $m,p as w_}from"./CommentInput-CBNbViJY.js";import{ContentRenderer as du,resolveFormat as k_}from"./ContentRenderer-DE3pZgeX.js";function Fn(s,e,t){let i=t.initialDeps??[],r,n=!0;function a(){var o,l,c;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==i.length||u.some((b,v)=>i[v]!==b)))return r;i=u;let g;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(g=Date.now()),r=e(...u),t.key&&((c=t.debug)!=null&&c.call(t))){const b=Math.round((Date.now()-d)*100)/100,v=Math.round((Date.now()-g)*100)/100,m=v/16,O=(p,x)=>{for(p=String(p);p.length<x;)p=" "+p;return p};console.info(`%c⏱ ${O(v,5)} /${O(b,5)} ms`,`
|
|
3
3
|
font-size: .6rem;
|
|
4
4
|
font-weight: bold;
|
|
5
5
|
color: hsl(${Math.max(0,Math.min(120-120*m,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(r),n=!1,r}return a.updateDeps=o=>{i=o},a}function jm(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const C_=(s,e)=>Math.abs(s-e)<1.01,P_=(s,e,t)=>{let i;return function(...r){s.clearTimeout(i),i=s.setTimeout(()=>e.apply(this,r),t)}},Em=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},T_=s=>s,Q_=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),i=[];for(let r=e;r<=t;r++)i.push(r);return i},$_=(s,e)=>{const t=s.scrollElement;if(!t)return;const i=s.targetWindow;if(!i)return;const r=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(r(Em(t)),!i.ResizeObserver)return()=>{};const n=new i.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const c=l.borderBoxSize[0];if(c){r({width:c.inlineSize,height:c.blockSize});return}}r(Em(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},Rm={passive:!0},Am=typeof window>"u"?!0:"onscrollend"in window,j_=(s,e)=>{const t=s.scrollElement;if(!t)return;const i=s.targetWindow;if(!i)return;let r=0;const n=s.options.useScrollendEvent&&Am?()=>{}:P_(i,()=>{e(r,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;r=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(r,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,Rm);const c=s.options.useScrollendEvent&&Am;return c&&t.addEventListener("scrollend",l,Rm),()=>{t.removeEventListener("scroll",o),c&&t.removeEventListener("scrollend",l)}},E_=(s,e,t)=>{if(e?.borderBoxSize){const i=e.borderBoxSize[0];if(i)return Math.round(i[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},R_=(s,{adjustments:e=0,behavior:t},i)=>{var r,n;const a=s+e;(n=(r=i.scrollElement)==null?void 0:r.scrollTo)==null||n.call(r,{[i.options.horizontal?"left":"top"]:a,behavior:t})};class A_{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,i,r;return((r=(i=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:i.now)==null?void 0:r.call(i))??Date.now()},this.observer=(()=>{let t=null;const i=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(r=>{r.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var r;(r=i())==null||r.disconnect(),t=null},observe:r=>{var n;return(n=i())==null?void 0:n.observe(r,{box:"border-box"})},unobserve:r=>{var n;return(n=i())==null?void 0:n.unobserve(r)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([i,r])=>{typeof r>"u"&&delete t[i]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:T_,rangeExtractor:Q_,onChange:()=>{},measureElement:E_,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var i,r;(r=(i=this.options).onChange)==null||r.call(i,this,t)},this.maybeNotify=Fn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const 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=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)}),this.unsubs.push(this.options.observeElementRect(this,r=>{this.scrollRect=r,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(r,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<r?"forward":"backward":null,this.scrollOffset=r,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,i)=>{const r=new Map,n=new Map;for(let a=i-1;a>=0;a--){const o=t[a];if(r.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&r.set(o.lane,!0),r.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=Fn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,i,r,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:i,scrollMargin:r,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=Fn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:i,scrollMargin:r,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},c)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const g of this.laneAssignments.keys())g>=t&&this.laneAssignments.delete(g);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(g=>{this.itemSizeCache.set(g.key,g.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let g=0;g<d;g++){const b=u[g];b&&(f[b.lane]=g)}for(let g=d;g<t;g++){const b=n(g),v=this.laneAssignments.get(g);let m,O;const p=l==="estimate"||c.has(b);if(v!==void 0&&this.options.lanes>1){m=v;const k=f[m],w=k!==void 0?u[k]:void 0;O=w?w.end+this.options.gap:i+r}else{const k=this.options.lanes===1?u[g-1]:this.getFurthestMeasurement(u,g);O=k?k.end+this.options.gap:i+r,m=k?k.lane:g%this.options.lanes,this.options.lanes>1&&p&&this.laneAssignments.set(g,m)}const x=c.get(b),y=typeof x=="number"?x:this.options.estimateSize(g),_=O+y;u[g]={index:g,start:O,size:y,end:_,key:b,lane:m},f[m]=g}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Fn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,i,r,n)=>this.range=t.length>0&&i>0?M_({measurements:t,outerSize:i,scrollOffset:r,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Fn(()=>{let t=null,i=null;const r=this.calculateRange();return r&&(t=r.startIndex,i=r.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,i]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,i]},(t,i,r,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:i,count:r}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const i=this.options.indexAttribute,r=t.getAttribute(i);return r?parseInt(r,10):(console.warn(`Missing attribute name '${i}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var i;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const r=this.scrollState.index??((i=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:i.index);if(r!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,r-n),o=Math.min(this.options.count-1,r+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const i=this.indexFromElement(t),r=this.options.getItemKey(i),n=this.elementsCache.get(r);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(r,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(i)&&this.resizeItem(i,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,i)=>{var r;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=i-a;o!==0&&(((r=this.scrollState)==null?void 0:r.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,i)),this.notify(!1))},this.getVirtualItems=Fn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,i)=>{const r=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=i[o];r.push(l)}return r},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const i=this.getMeasurements();if(i.length!==0)return jm(i[yx(0,i.length-1,r=>jm(i[r]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,i,r=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();i==="auto"&&(i=t>=a+n?"end":"start"),i==="center"?t+=(r-n)/2:i==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,i="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(i==="auto")if(a.end>=n+r-this.options.scrollPaddingEnd)i="end";else if(a.start<=n+this.options.scrollPaddingStart)i="start";else return[n,i];if(i==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),i];const o=i==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,i,a.size),i]},this.scrollToOffset=(t,{align:i="start",behavior:r="auto"}={})=>{const n=this.getOffsetForAlignment(t,i),a=this.now();this.scrollState={index:null,align:i,behavior:r,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:i="auto",behavior:r="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,i);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:r,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:i="auto"}={})=>{const r=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:i,startedAt:n,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const i=this.getMeasurements();let r;if(i.length===0)r=this.options.paddingStart;else if(this.options.lanes===1)r=((t=i[i.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=i.length-1;for(;a>=0&&n.some(o=>o===null);){const o=i[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}r=Math.max(...n.filter(o=>o!==null))}return Math.max(r-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:i,behavior:r})=>{this.options.scrollToFn(t,{behavior:r,adjustments:i},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const i=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,r=i?i[0]:this.scrollState.lastTargetOffset,n=1,a=r!==this.scrollState.lastTargetOffset;if(!a&&C_(r,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=r,this.scrollState.behavior="auto",this._scrollToOffset(r,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const yx=(s,e,t,i)=>{for(;s<=e;){const r=(s+e)/2|0,n=t(r);if(n<i)s=r+1;else if(n>i)e=r-1;else return r}return s>0?s-1:0};function M_({measurements:s,outerSize:e,scrollOffset:t,lanes:i}){const r=s.length-1,n=l=>s[l].start;if(s.length<=i)return{startIndex:0,endIndex:r};let a=yx(0,r,n,t),o=a;if(i===1)for(;o<r&&s[o].end<t+e;)o++;else if(i>1){const l=Array(i).fill(0);for(;o<r&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const c=Array(i).fill(t+e);for(;a>=0&&c.some(d=>d>=t);){const d=s[a];c[d.lane]=d.start,a--}a=Math.max(0,a-a%i),o=Math.min(r,o+(i-1-o%i))}return{startIndex:a,endIndex:o}}const Mm=typeof document<"u"?C.useLayoutEffect:C.useEffect;function L_({useFlushSync:s=!0,...e}){const t=C.useReducer(()=>({}),{})[1],i={...e,onChange:(n,a)=>{var o;s&&a?fx.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[r]=C.useState(()=>new A_(i));return r.setOptions(i),Mm(()=>r._didMount(),[]),Mm(()=>r._willUpdate()),r}function N_(s){return L_({observeElementRect:$_,observeElementOffset:j_,scrollToFn:R_,...s})}const Lm={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 D_({notification:s,agentName:e,acknowledging:t,onClose:i,onAcknowledge:r}){const{t:n}=Pt(["team","common"]);YS(!0);const a=s.priority||"normal",o=s.metadata??{},l=e||(typeof o.agentName=="string"?o.agentName:void 0);return fx.createPortal(h.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:c=>{c.target===c.currentTarget&&i()},children:h.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:[h.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[h.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),h.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),h.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[l&&h.jsx("p",{className:"text-xs text-fg-tertiary",children:l}),a!=="normal"&&h.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${Lm[a]??Lm.normal}`,children:a})]})]}),h.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:n("common:close"),children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 6L6 18"}),h.jsx("path",{d:"M6 6l12 12"})]})})]}),h.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:h.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:h.jsx(ma,{content:s.body||""})})}),h.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[h.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:n("common:close")}),h.jsx("button",{onClick:()=>{r()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?n("common:loading"):n("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"})})]})]})}),document.body)}function ga({children:s,onClose:e,title:t,width:i="w-[440px]"}){return h.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:h.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${i} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:r=>r.stopPropagation(),children:[h.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function to({label:s,children:e}){return h.jsxs("div",{children:[h.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function I_({onClose:s,onCreate:e}){const{t}=Pt(["team","common"]),[i,r]=C.useState(""),[n,a]=C.useState("");return h.jsx(ga,{onClose:s,title:t("team:modals.createTeam.title"),children:h.jsxs("div",{className:"space-y-4",children:[h.jsx(to,{label:t("team:modals.createTeam.teamName"),children:h.jsx("input",{value:i,onChange:o=>r(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&i.trim()&&e(i.trim(),n.trim()||void 0)}})}),h.jsx(to,{label:t("team:modals.createTeam.description"),children:h.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),h.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),h.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:h.jsx(US,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:h.jsx("span",{className:"text-brand-400 font-medium"}),1:h.jsx("span",{className:"text-brand-400"})}})}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:()=>i.trim()&&e(i.trim(),n.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:t("team:modals.createTeam.createTeam")})]})]})})}function B_({onClose:s,onAdd:e}){const{t}=Pt(["team","common"]),[i,r]=C.useState(""),[n,a]=C.useState("member"),[o,l]=C.useState(""),[c,d]=C.useState(""),[u,f]=C.useState(!1),[g,b]=C.useState(null),[v,m]=C.useState(!1),O=g?.inviteToken?`${window.location.origin}/#invite?token=${g.inviteToken}`:null,p=async()=>{if(d(""),!i.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(i.trim(),n,o.trim());b({...y,userName:i.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),m(!0),setTimeout(()=>m(!1),2e3))};return g?h.jsxs(ga,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[h.jsxs("div",{className:"text-center py-4",children:[h.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:h.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:h.jsx("polyline",{points:"20 6 9 17 4 12"})})}),h.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:g.userName})}),O?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),h.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),h.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),h.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${v?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(v?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):h.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),h.jsx("div",{className:"flex justify-end pt-3",children:h.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):h.jsx(ga,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:h.jsxs("div",{className:"space-y-4",children:[h.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:[h.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),h.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",h.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),h.jsx(to,{label:t("team:modals.addHuman.name"),children:h.jsx("input",{value:i,onChange:y=>r(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),h.jsx(to,{label:t("team:modals.addHuman.role"),children:h.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[h.jsx("option",{value:"owner",children:t("common:role.owner")}),h.jsx("option",{value:"admin",children:t("common:role.admin")}),h.jsx("option",{value:"member",children:t("common:role.member")}),h.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),h.jsx(to,{label:t("team:modals.addHuman.emailRequired"),children:h.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),h.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),c&&h.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:c}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:p,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function W_({teamId:s,ungrouped:e,onClose:t,onAdd:i}){const{t:r}=Pt(["team","common"]);return h.jsx(ga,{onClose:t,title:r("team:modals.addExisting.title"),children:h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:r("team:modals.addExisting.hint")}),e.length===0?h.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:r("team:modals.addExisting.allInTeam")}):h.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>h.jsxs("button",{onClick:()=>i(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[h.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),h.jsxs("div",{className:"flex-1",children:[h.jsx("div",{className:"font-medium text-sm",children:n.name}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?r("team:modals.addExisting.typeAgent"):r("team:modals.addExisting.typeHuman")]})]}),n.status&&h.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:r("common:close")})})]})})}function X_({onClose:s,onConnected:e}){const{t}=Pt(["team","common"]),[i,r]=C.useState(""),[n,a]=C.useState(""),[o,l]=C.useState(!1),[c,d]=C.useState(null),[u,f]=C.useState(null),g=async()=>{if(!i.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const v=i.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const m=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:v,agentName:i.trim(),orgId:"default",capabilities:["general"]})});if(!m.ok){const p=await m.json().catch(()=>({}));throw new Error(p.error??`HTTP ${m.status}`)}const O=await m.json();d({externalAgentId:v,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(m){a(String(m))}l(!1)},b=(v,m)=>{navigator.clipboard.writeText(v),f(m),setTimeout(()=>f(null),2e3)};return h.jsx(ga,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:c?(()=>{const v=c.gatewayUrl??`${window.location.origin}/api/gateway`,m=c.token?t("team:modals.openClaw.bearerTokenLine",{token:c.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:v,externalAgentId:c.externalAgentId,tokenSection:m});return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"text-center py-6",children:[h.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),h.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),h.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:h.jsx("strong",{children:i})})]}),h.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[h.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),h.jsx("button",{onClick:()=>b(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),h.jsx("div",{className:"flex justify-end pt-5",children:h.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),h.jsxs("div",{className:"space-y-4",children:[h.jsx(to,{label:t("team:modals.openClaw.agentName"),children:h.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:i,onChange:v=>r(v.target.value),autoFocus:!0})}),n&&h.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:g,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let _l=new Map;function q_({agents:s,humans:e,authUser:t,onClose:i,onCreate:r}){const{t:n}=Pt(["team","common"]),[a,o]=C.useState(""),[l,c]=C.useState(new Set),[d,u]=C.useState(""),[f,g]=C.useState(!1),b=C.useMemo(()=>{const p=[];for(const x of s)p.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&p.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return p},[s,e,t]),v=C.useMemo(()=>{if(!d)return b;const p=d.toLowerCase();return b.filter(x=>x.name.toLowerCase().includes(p)||x.subtitle.toLowerCase().includes(p))},[b,d]),m=p=>{c(x=>{const y=new Set(x);return y.has(p)?y.delete(p):y.add(p),y})},O=async()=>{if(!a.trim()||l.size===0)return;g(!0);const p=[...l],x={},y={};for(const _ of p){const k=b.find(w=>w.id===_);k&&(x[_]=k.type,y[_]=k.name)}await r(a.trim(),p,x,y),g(!1)};return h.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:i,children:h.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[h.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[h.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),h.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),h.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:h.jsx("input",{value:a,onChange:p=>o(p.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),h.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:h.jsx("input",{value:d,onChange:p=>u(p.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),h.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[v.length===0&&h.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),v.map(p=>h.jsxs("button",{onClick:()=>m(p.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(p.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[h.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(p.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(p.id)&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"20 6 9 17 4 12"})})}),h.jsx(_s,{name:p.name,size:20,bgClass:p.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate text-[11px] font-medium block",children:p.name}),h.jsx("span",{className:"text-[9px] text-fg-tertiary",children:p.subtitle})]}),h.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${p.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:p.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},p.id))]}),h.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),h.jsxs("div",{className:"flex gap-2",children:[h.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:n("common:cancel")}),h.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const z_=C.memo(function({authUser:e,agents:t,teams:i,humans:r,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:c,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:g,onSelectDm:b,onSelectTeam:v,selectedTeamId:m,onRefreshTeams:O,onRefreshAgents:p,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:_,onManageGroupMembers:k,unreadByAgent:w,unreadByChannel:S,width:Q,onResizeStart:I,hidden:D,onCollapse:$,initialLoading:j,previewMode:B,focused:F,l2Available:V}){const{t:Z}=Pt(["team","common"]),se=Sf(),T=_f(Ht.TEAM),A=wf(),N=e?.role==="owner"||e?.role==="admin",z=C.useMemo(()=>new Set(a.map(W=>W.markusAgentId).filter(Boolean)),[a]),[U,ne]=C.useState([]),[Se,Pe]=C.useState(new Set),[X,M]=C.useState(!1),[K,ie]=C.useState(!1),[oe,G]=C.useState(null),[$e,Ie]=C.useState(!1),[We,Y]=C.useState(!1),[ee,le]=C.useState(null),[ke,Ce]=C.useState(null),[dt,ht]=C.useState(null),[yt,ss]=C.useState(!1),[Lt,zs]=C.useState(""),[vs,bs]=C.useState(null),[si,Zs]=C.useState(null),[Ps,xt]=C.useState(null),[$i,ji]=C.useState(!1),Ga=C.useRef(null),[gh,Hr]=C.useState(null),Ji=C.useRef(null),Ka=C.useRef(null),[Po,To]=C.useState(null),Gr=(W,he="success")=>{To({message:W,type:he}),setTimeout(()=>To(null),3e3)},[ii,xi]=C.useState(null),[Ja,Qo]=C.useState(!1),An=C.useRef(!1);C.useEffect(()=>{if(B)return;J.governance.getSystemStatus().then(ue=>{An.current=!0,xi(ue.globalPaused)}).catch(()=>{An.current=!0,xi(!1)});const W=gt.on("system:pause-all",()=>{An.current&&xi(!0)}),he=gt.on("system:resume-all",()=>{An.current&&xi(!1)});return()=>{W(),he()}},[]),C.useEffect(()=>{if(!B)return;const W=setTimeout(()=>{const he=Ka.current,ue=Ji.current;he&&ue&&ue.scrollTo({top:he.offsetTop-ue.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(W)},[B]);const $o=C.useCallback(()=>{ii!==null&&Kr({title:Z(ii?"modals.resumeAll.title":"modals.pauseAll.title"),message:Z(ii?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:Z(ii?"chat.resume":"chat.pause"),onConfirm:async()=>{Qo(!0);try{ii?(await J.governance.resumeAll(),xi(!1)):(await J.governance.pauseAll(),xi(!0))}catch{}Qo(!1)}})},[ii]),[Ei,Kr]=C.useState(null),Mn=(W,he,ue,Re,Fe)=>{Kr({title:W,message:he,onConfirm:ue,confirmLabel:Re,checkboxes:Fe})},[ri,Tr]=C.useState(null),[Jr,jo]=C.useState(null),ni=C.useRef(null),Ts=C.useRef(null),[vi,Eo]=C.useState(!1),[ce,ut]=C.useState(null),[ge,is]=C.useState(""),lt=C.useCallback((W,he=176,ue=220)=>{const Re=window.innerWidth,Fe=window.innerHeight,tt=8;let vt=W.clientX,mt=W.clientY;return vt+he>Re-tt&&(vt=Math.max(tt,Re-he-tt)),mt+ue>Fe-tt&&(mt=Math.max(tt,Fe-ue-tt)),vt=Math.max(tt,Math.min(vt,Re-he-tt)),mt=Math.max(tt,Math.min(mt,Fe-ue-tt)),{x:vt,y:mt}},[]),[As,Nt]=C.useState(_l),en=C.useMemo(()=>t.map(W=>W.id).sort().join(","),[t]);C.useEffect(()=>{if(!t.length||!T)return;let W=!1;(async()=>{const mt=[];await Promise.allSettled(t.map(async Ye=>{if(!_l.has(Ye.id))try{const{sessions:Yt}=await J.sessions.listByAgent(Ye.id,1);if(!Yt.length)return;const{messages:Dt}=await J.sessions.getMessages(Yt[0].id,1);if(Dt.length){const Ut=Dt[0],Ls=Ut.metadata?.segments;let Zt=Ut.content;if(Ls&&Ls.length>0){const Ai=[...Ls].reverse().find(Nn=>Nn.type==="text");Ai&&Ai.type==="text"&&(Zt=Ai.content)}const us=Zt.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);us&&mt.push([Ye.id,us])}}catch{}})),!W&&mt.length&&Nt(Ye=>{const Yt=new Map(Ye);for(const[Dt,Ut]of mt)Yt.set(Dt,Ut);return _l=Yt,Yt})})();const ue=new Set(t.map(mt=>mt.id)),Re=mt=>mt.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Fe=(mt,Ye)=>{if(!mt||!Ye||!ue.has(mt))return;const Yt=Re(Ye);Yt&&Nt(Dt=>{const Ut=new Map(Dt);return Ut.set(mt,Yt),_l=Ut,Ut})},tt=gt.on("chat:proactive_message",mt=>{const Ye=mt.payload;Fe(Ye.agentId??"",Ye.message??"")}),vt=gt.on("chat:message",mt=>{const Ye=mt.payload,Yt=Ye.senderId??Ye.agentId??"",Dt=Ye.text??Ye.message??"";Fe(Yt,Dt)});return()=>{W=!0,tt(),vt()}},[en,T]);const Ms=C.useCallback(()=>{B||J.teams.list().then(W=>ne(W.ungrouped)).catch(()=>{})},[B]);C.useEffect(()=>{Ms()},[Ms]),C.useEffect(()=>{if(!T)return;const W=gt.on("team:update",Ms),he=gt.on("agent:removed",Ms);return()=>{W(),he()}},[Ms,T]),C.useEffect(()=>{if(!ke&&!dt&&!vs&&!$i&&!Ps)return;const W=()=>{Ce(null),ht(null),bs(null),xt(null),ji(!1)},he=setTimeout(()=>document.addEventListener("click",W),0);return()=>{clearTimeout(he),document.removeEventListener("click",W)}},[ke,dt,vs,$i,Ps]);const tn=(W,he)=>{Mn(`${Z("common:delete")} "${he}"?`,Z("modals.deleteTeam.message"),async ue=>{const Re=ue?.deleteMembers??!0,Fe=ue?.purgeFiles??!1;await J.teams.delete(W,Re,{purgeFiles:Fe}),O(),Ms(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},Z("contextMenu.deleteTeam"),[{id:"deleteMembers",label:Z("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:Z("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Ln=async(W,he)=>{try{const Re=await(he==="start"?J.teams.startAll:J.teams.stopAll)(W),Fe=Re.success?.length??0,tt=Re.failed?.length??0;tt>0?Gr(Z("batchAction.failed",{action:Z(`batchAction.operation.${he}`),ok:Fe,fail:tt}),"error"):Fe>0&&Gr(Z("batchAction.succeeded",{count:Fe,action:Z(`batchAction.past.${he}`)}),"success"),p()}catch(ue){Gr(Z("batchAction.failedToRun",{action:Z(`batchAction.operation.${he}`),error:ue instanceof Error?ue.message:String(ue)}),"error")}},Oh=async(W,he,ue)=>{await J.teams.update(W,{managerId:he,managerType:ue}),O()},el=async W=>{if(!ge.trim()){ut(null);return}await J.teams.update(W,{name:ge.trim()}),ut(null),O()},At=async(W,he)=>{he==="offline"?await J.agents.start(W):await J.agents.stop(W),p()},Qs=(W,he)=>{Mn(Z("modals.removeFromTeam.title"),Z("modals.removeFromTeam.message"),async()=>{await J.teams.removeMember(W,he),O(),Ms()},Z("common:remove"))},Vs=(W,he,ue)=>{Mn(`${Z("common:remove")} "${he}"?`,Z(ue==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Re=>{if(ue==="agent"){const Fe=Re?.purgeFiles??!1;await J.agents.remove(W,{purgeFiles:Fe})}else await J.users.remove(W);p(),O(),x?.(),Ms(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},Z("common:remove"),ue==="agent"?[{id:"purgeFiles",label:Z("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},rs=W=>{if(W.isOrgSecretary||W.protected)return!0;if(W.teamId)return!1;const he=(W.role??"").toLowerCase().trim(),ue=(W.name??"").trim();return ue==="Secretary"||ue==="秘书"||he==="secretary"||he.startsWith("secretary")},xh=(W,he,ue)=>{const Re=t.find(Fe=>Fe.id===he);Re&&rs(Re)||(Ts.current={x:W.clientX,y:W.clientY},ni.current=setTimeout(()=>{Tr({agentId:he,fromTeamId:ue}),Eo(!0)},200))},bi=W=>{if(!Ts.current||!ni.current)return;const he=Math.abs(W.clientX-Ts.current.x),ue=Math.abs(W.clientY-Ts.current.y);(he>5||ue>5)&&(vi||(clearTimeout(ni.current),ni.current=null))},hs=async()=>{if(ni.current&&(clearTimeout(ni.current),ni.current=null),Ts.current=null,vi&&ri&&Jr){const W=Jr==="_ungrouped"?void 0:Jr;try{if(ri.fromTeamId&&ri.fromTeamId!==W&&await J.teams.removeMember(ri.fromTeamId,ri.agentId),W&&W!==ri.fromTeamId){const he=t.find(ue=>ue.id===ri.agentId);await J.teams.addMember(W,ri.agentId,"agent")}O(),p(),Ms()}catch(he){Gr(Z("batchAction.moveFailed",{error:he instanceof Error?he.message:String(he)}),"error")}}Tr(null),jo(null),Eo(!1)},sn=C.useMemo(()=>new Map(i.map(W=>[W.id,W])),[i]),ds=C.useMemo(()=>{const W=new Map,he=[];for(const ue of t)if(ue.teamId&&sn.has(ue.teamId)){const Re=W.get(ue.teamId)??[];Re.push(ue),W.set(ue.teamId,Re)}else he.push(ue);return{byTeam:W,ungrouped:he}},[t,sn]),oi=(W,he)=>{const ue=l==="direct"&&c===W.id,Re=z.has(W.id),Fe=W.status==="offline",tt=W.status==="idle"?"bg-green-500":W.status==="working"?"bg-blue-500 animate-pulse":W.status==="error"?"bg-red-500":"bg-gray-600",mt=(void 0)?.managerId===W.id,Ye=W.role?.toLowerCase().replace(/[-_]/g," ").trim(),Yt=W.name.toLowerCase().trim(),Dt=Ye&&Ye!==Yt,Ut=As.get(W.id)||W.currentActivity?.label?.slice(0,60)||"",Ls=W.status==="idle"?Z("common:status.online"):W.status==="working"?Z("common:status.working"):W.status==="error"?Z("common:status.error"):Z("common:status.offline");return h.jsx("div",{className:`relative mb-0.5 ${vi&&ri?.agentId===W.id?"opacity-40":""}`,onPointerDown:Zt=>xh(Zt,W.id,he),onPointerMove:bi,onPointerUp:hs,children:h.jsxs("button",{"data-l1-nav-id":`agent:${W.id}`,onClick:()=>{vi||f(W.id)},onContextMenu:Zt=>{if(!N)return;Zt.preventDefault();const us=lt(Zt);ss(!1),zs(""),ht({agentId:W.id,teamId:he,...us})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${se?"":"touch-none"} ${Fe?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ri(ue)}`,children:[h.jsx(_s,{name:W.name,avatarUrl:W.avatarUrl,size:28,bgClass:Fe?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:W.name}),Dt&&h.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",W.role,")"]}),mt&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:h.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"})}),Re&&h.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"}),Fe&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:Z("common:status.offline")})]}),h.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Ut||" "})]}),h.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(w?.get(W.id)??0)>0&&h.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:w.get(W.id)}),W.mailboxDepth!=null&&W.mailboxDepth>0&&h.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:W.mailboxDepth}),h.jsx("span",{title:Ls,onClick:Zt=>{Zt.stopPropagation(),_(W.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${tt}`}),se&&N&&h.jsx("span",{role:"button",tabIndex:0,onClick:Zt=>{if(Zt.stopPropagation(),dt?.agentId===W.id)ht(null);else{const us=lt(Zt);ss(!1),zs(""),ht({agentId:W.id,teamId:he,...us})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:Z("chat.moreOptions"),children:h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"1"}),h.jsx("circle",{cx:"12",cy:"5",r:"1"}),h.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},W.id)},tl=(W,he,ue,Re)=>{const Fe=vi&&Jr===W&&ri?.fromTeamId!==W,tt=gh===W,vt=m===W,mt=w?(ds.byTeam.get(W)??[]).reduce((Rt,ns)=>Rt+(w.get(ns.id)??0),0):0,Ye=o.find(Rt=>Rt.type==="team"&&Rt.teamId===W),Yt=Ye&&S?S[Ye.channelKey]??0:0,Dt=mt+Yt,Ut=ds.byTeam.get(W)??[],Ls=Ut.filter(Rt=>Rt.status==="offline").length,Zt=Ut.length,us=Zt>0&&Ls===Zt,Ai=Ls>0&&!us,Nn=us?"bg-gray-500":Ai?"bg-amber-500":"bg-green-500";return h.jsxs("div",{"data-team-id":W,className:`mb-0.5 rounded-lg transition-all duration-500 ${Fe?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${tt?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{vi&&jo(W)},onPointerLeave:()=>{vi&&Jr===W&&jo(null)},children:[h.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[h.jsxs("button",{"data-l1-nav-id":`team:${W}`,onClick:()=>{v&&W!=="_ungrouped"&&v(W)},onContextMenu:Rt=>{if(!N||!he)return;Rt.preventDefault();const ns=lt(Rt);Ce({teamId:W,...ns})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${us?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ri(vt)}`,children:[h.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${us?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Zt>0&&h.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${Nn}`})]}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[ce===W?h.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:ge,onChange:Rt=>is(Rt.target.value),onBlur:()=>el(W),onKeyDown:Rt=>{Rt.key==="Enter"&&el(W),Rt.key==="Escape"&&ut(null)},onClick:Rt=>Rt.stopPropagation(),autoFocus:!0}):h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Re}),h.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[Z("chat.members_other",{count:ue}),us&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:Z("common:status.offline")}),Ai&&h.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Ls,"/",Zt]})]})]}),Dt>0&&h.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:Dt}),h.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:h.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"})})]}),N&&he&&h.jsx("button",{onClick:Rt=>{if(Rt.stopPropagation(),ke?.teamId===W)Ce(null);else{const ns=lt(Rt);Ce({teamId:W,...ns})}},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:Z("chat.moreOptions"),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"1"}),h.jsx("circle",{cx:"12",cy:"5",r:"1"}),h.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Fe&&vi&&h.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:Z("chat.dropHere")})]},W)},Ve=C.useMemo(()=>{const W=new Map,he=[],ue=[],Re=[];for(const Fe of o)if(Fe.channelKey.startsWith("dm:a2a:"))Re.push(Fe);else if(Fe.type==="custom")ue.push(Fe);else if(Fe.teamId){const tt=W.get(Fe.teamId)??[];tt.push(Fe),W.set(Fe.teamId,tt)}else{const tt=i.find(vt=>Fe.name.toLowerCase().includes(vt.name.toLowerCase())||vt.name.toLowerCase().includes(Fe.name.toLowerCase()));if(tt){const vt=W.get(tt.id)??[];vt.push(Fe),W.set(tt.id,vt)}else he.push(Fe)}return{byTeam:W,unmatched:he,custom:ue,dmChannels:Re}},[o,i]),[rt,er]=C.useState(!1),rn=l==="channel"&&Ve.dmChannels.some(W=>W.channelKey===d);C.useEffect(()=>{rn&&er(!0)},[rn]);const sl=C.useMemo(()=>{const W=[];e&&W.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const ue of r)ue.id!==e?.id&&W.push({kind:"dm",id:`dm:${ue.id}`,userId:ue.id});for(const ue of Ve.custom)W.push({kind:"channel",id:`channel:${ue.channelKey}`,channelKey:ue.channelKey});for(const ue of Ve.unmatched)W.push({kind:"channel",id:`channel:${ue.channelKey}`,channelKey:ue.channelKey});const he=ds.ungrouped.length>0?ds.ungrouped:i.length===0?t:[];for(const ue of he)W.push({kind:"agent",id:`agent:${ue.id}`,agentId:ue.id});for(const ue of i)W.push({kind:"team",id:`team:${ue.id}`,teamId:ue.id});if(rt)for(const ue of Ve.dmChannels)W.push({kind:"channel",id:`channel:${ue.channelKey}`,channelKey:ue.channelKey});return W},[e,r,Ve,ds,i,t,rt]),nn=C.useRef(sl);nn.current=sl;const ai=C.useCallback(W=>{W.kind==="dm"?b(W.userId):W.kind==="channel"?g(W.channelKey):W.kind==="agent"?f(W.agentId):W.kind==="team"&&v?.(W.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${W.id}"]`)?.scrollIntoView({block:"nearest"})})},[b,g,f,v]);C.useEffect(()=>{if(B||se||!T||D)return;const W=he=>{const ue=A?.keyboardPane??"content";if(ue==="l0"||ue==="l2"||he.metaKey||he.ctrlKey||he.altKey||px(he.target))return;const Re=he.key.length===1?he.key.toLowerCase():he.key;if(Re==="h"||Re==="ArrowLeft"){if(ue!=="l1")return;he.preventDefault(),he.stopPropagation(),A?.setL0FocusPageId(Ht.TEAM),A?.setLeftCollapsed(!1),A?.setKeyboardPane("l0");return}if(Re==="l"||Re==="ArrowRight"){if(ue!=="l1")return;he.preventDefault(),he.stopPropagation(),V&&A?.setKeyboardPane("l2");return}if(ue!=="l1"&&!(F&&(Re==="j"||Re==="k"||Re==="ArrowDown"||Re==="ArrowUp")))return;const Fe=Re==="j"||Re==="ArrowDown"?1:Re==="k"||Re==="ArrowUp"?-1:0;if(!Fe)return;he.preventDefault(),he.stopPropagation(),A?.setKeyboardPane("l1");const tt=nn.current;if(tt.length===0)return;let vt=-1;if(l==="dm"){const Ye=u||e?.id;Ye&&(vt=tt.findIndex(Yt=>Yt.kind==="dm"&&Yt.userId===Ye))}else l==="direct"?vt=tt.findIndex(Ye=>Ye.kind==="agent"&&Ye.agentId===c):l==="channel"&&(vt=tt.findIndex(Ye=>Ye.kind==="channel"&&Ye.channelKey===d),vt<0&&m&&(vt=tt.findIndex(Ye=>Ye.kind==="team"&&Ye.teamId===m)));vt<0&&(vt=Fe>0?-1:0);const mt=Math.max(0,Math.min(tt.length-1,vt+Fe));ai(tt[mt])};return document.addEventListener("keydown",W,!0),()=>document.removeEventListener("keydown",W,!0)},[B,se,T,D,A,F,V,l,u,e?.id,c,d,m,ai]);const Ri=W=>W?F?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return h.jsxs(h.Fragment,{children:[h.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${Q!=null?"shrink-0":"flex-1 min-w-0"} ${F?"ring-1 ring-inset ring-brand-500/30":""}`,style:D?{display:"none"}:Q!=null?{width:Q}:void 0,children:[h.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[se&&h.jsx(HS,{}),!se&&$&&h.jsx("button",{onClick:$,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:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),h.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),h.jsx("h2",{className:"text-lg font-semibold",children:Z("chat.title")}),N&&h.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ga,children:[h.jsxs("button",{onClick:()=>ji(!$i),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:[h.jsx("span",{className:"text-brand-500",children:"+"})," ",Z("chat.manage"),h.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${$i?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:h.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"})})]}),$i&&h.jsxs("div",{ref:W=>{if(!W)return;const he=W.getBoundingClientRect(),ue=window.innerWidth,Re=8;he.right>ue-Re&&(W.style.left="auto",W.style.right="0"),he.left<Re&&(W.style.left="0",W.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:[h.jsxs("button",{onClick:()=>{ji(!1),le("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),h.jsx("circle",{cx:"12",cy:"5",r:"2"}),h.jsx("path",{d:"M12 7v4"}),h.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),h.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),Z("chat.addAgent")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:Z("chat.addAgentDesc")})]}),h.jsxs("button",{onClick:()=>{ji(!1),le("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:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),h.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),Z("chat.newTeam")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:Z("chat.newTeamDesc")})]}),h.jsxs("button",{onClick:()=>{ji(!1),ie(!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:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M20 8v6"}),h.jsx("path",{d:"M23 11h-6"})]}),Z("chat.addHuman")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:Z("chat.addHumanDesc")})]}),h.jsxs("button",{onClick:()=>{ji(!1),Y(!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:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.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"}),h.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),Z("chat.newGroupChat")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:Z("chat.newGroupChatDesc")})]}),ii!==null&&h.jsxs("button",{onClick:()=>{ji(!1),$o()},disabled:Ja,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 ${ii?"text-green-600":"text-red-500"}`,children:[h.jsx("div",{className:"font-medium flex items-center gap-1.5",children:ii?h.jsxs(h.Fragment,{children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",Z("chat.resume")]}):h.jsxs(h.Fragment,{children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",Z("contextMenu.stopAll")]})}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:Z(ii?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),h.jsxs("div",{ref:Ji,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:Z("chat.people")}),e&&h.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>b(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ri(l==="dm"&&(u===e.id||!u))}`,children:[h.jsx(_s,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Z("chat.myNotes")})]}),h.jsx("span",{className:"text-fg-secondary shrink-0",children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),h.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),r.filter(W=>W.id!==e?.id).map(W=>{const he=e?.id?`dm:${[e.id,W.id].sort().join(":")}`:"",ue=he&&S?S[he]??0:0;return h.jsxs("button",{"data-l1-nav-id":`dm:${W.id}`,onClick:()=>b(W.id),onContextMenu:Re=>{if(!N||W.id===e?.id)return;Re.preventDefault();const Fe=lt(Re);bs({userId:W.id,...Fe})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${l==="dm"&&u===W.id?F?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[h.jsx(_s,{name:W.name,avatarUrl:W.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:W.name}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:W.email||W.role})]}),ue>0?h.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:ue}):h.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},W.id)})]}),Ve.custom.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:Z("chat.groups")}),Ve.custom.map(W=>{const he=l==="channel"&&d===W.channelKey;return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.channelKey),onContextMenu:ue=>{ue.preventDefault();const Re=lt(ue);xt({gcId:W.id,...Re})},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 ${Ri(he)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:W.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:Z("chat.members_other",{count:W.memberCount??0})})]})]},W.id)})]}),j?h.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((W,he)=>h.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[h.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),h.jsxs("div",{className:"flex-1 space-y-1.5",children:[h.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),h.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),h.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},he))}):t.length===0&&i.length===0?h.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:Z("chat.noAgentsYet")}):null,Ve.unmatched.map(W=>{const he=S?.[W.channelKey]??0;return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.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 ${Ri(l==="channel"&&d===W.channelKey)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:W.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:Z("chat.groupChat")})]}),he>0?h.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:he}):W.memberCount!==void 0&&W.memberCount>0?h.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:W.memberCount}):null]},W.id)}),ds.ungrouped.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:Z("chat.agents")}),ds.ungrouped.map(W=>oi(W))]}),i.length>0&&h.jsxs("div",{className:"mb-2",ref:Ka,children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:Z("chat.teams")}),i.map(W=>{const he=ds.byTeam.get(W.id)??[],ue=W.members?.length||he.length;return tl(W.id,W,ue,W.name)})]}),i.length===0&&ds.ungrouped.length===0&&t.length>0&&t.map(W=>oi(W)),Ve.dmChannels.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsxs("button",{onClick:()=>er(W=>!W),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:[h.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${rt?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:h.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"})}),Z("chat.agentDMs"),h.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Ve.dmChannels.length})]}),rt&&Ve.dmChannels.map(W=>{const he=l==="channel"&&d===W.channelKey,ue=S?.[W.channelKey]??0,Re=W.name.replace(/^DM:\s*/,"");return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.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 ${Ri(he)}`,children:[h.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:h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})})}),h.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:Re}),ue>0&&h.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:ue})]},W.id)})]})]})]}),I&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:I,children:h.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"})}),ke&&(()=>{const W=ds.byTeam.get(ke.teamId)??[],he=W.some(Re=>Re.status==="offline"),ue=W.some(Re=>Re.status!=="offline");return h.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:ke.x,top:ke.y},onClick:Re=>Re.stopPropagation(),children:[h.jsxs("button",{onClick:()=>{const Re=sn.get(ke.teamId);Re&&(ut(ke.teamId),is(Re.name)),Ce(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),h.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),Z("contextMenu.renameTeam")]}),he&&h.jsxs("button",{onClick:()=>{Ln(ke.teamId,"start"),Ce(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),Z("contextMenu.startAll")]}),ue&&h.jsxs("button",{onClick:()=>{Ln(ke.teamId,"stop"),Ce(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),Z("contextMenu.stopAll")]}),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{Ce(null),Or.navigate(Ht.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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),Z("chat.addAgent")]}),U.length>0&&h.jsxs("button",{onClick:()=>{Ce(null),G(ke.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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),h.jsx("polyline",{points:"17 11 19 13 23 9"})]}),Z("contextMenu.addExisting")]}),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{const Re=sn.get(ke.teamId);Re&&tn(ke.teamId,Re.name),Ce(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.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"})]}),Z("contextMenu.deleteTeam")]})]})})(),dt&&(()=>{const W=t.find(tt=>tt.id===dt.agentId);if(!W||!N)return null;const ue=(dt.teamId?sn.get(dt.teamId):void 0)?.managerId===W.id,Re=W.id===e?.id,Fe=rs(W);return h.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:dt.x,top:dt.y,maxHeight:Math.max(160,window.innerHeight-dt.y-8)},onClick:tt=>tt.stopPropagation(),children:[Fe&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:Z("contextMenu.orgSecretaryProtected")}),h.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),h.jsxs("button",{onClick:()=>{ht(null),_(W.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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),Z("contextMenu.viewProfile")]}),W.status==="offline"?h.jsxs("button",{onClick:()=>{At(W.id,"offline"),ht(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),Z("contextMenu.start")]}):h.jsxs("button",{onClick:()=>{At(W.id,W.status??"idle"),ht(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),Z("contextMenu.stop")]}),!Fe&&dt.teamId&&!ue&&h.jsxs("button",{onClick:()=>{Oh(dt.teamId,W.id,"agent"),ht(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.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"})}),Z("contextMenu.setAsManager")]}),!Fe&&dt.teamId&&h.jsxs("button",{onClick:()=>{Qs(dt.teamId,W.id),ht(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"9 14 4 9 9 4"}),h.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),Z("contextMenu.removeFromTeam")]}),!Fe&&(()=>{const tt=i.filter(Ye=>Ye.id!==dt.teamId);if(tt.length===0)return null;const vt=Lt.trim().toLowerCase(),mt=vt?tt.filter(Ye=>Ye.name.toLowerCase().includes(vt)):tt;return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{type:"button",onClick:()=>ss(Ye=>!Ye),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M5 12h14"}),h.jsx("path",{d:"M12 5l7 7-7 7"})]}),h.jsx("span",{className:"flex-1",children:Z("contextMenu.moveTo")}),h.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 ${yt?"rotate-180":""}`,children:h.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),yt&&h.jsxs("div",{className:"px-2 pb-1.5",onClick:Ye=>Ye.stopPropagation(),children:[h.jsx("input",{autoFocus:!0,value:Lt,onChange:Ye=>zs(Ye.target.value),onKeyDown:Ye=>Ye.stopPropagation(),placeholder:Z("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"}),h.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:mt.length===0?h.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:Z("contextMenu.moveToEmpty")}):mt.map(Ye=>h.jsx("button",{type:"button",onClick:async()=>{dt.teamId&&await J.teams.removeMember(dt.teamId,W.id),await J.teams.addMember(Ye.id,W.id,"agent"),O(),p(),Ms(),ht(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Ye.name,children:Ye.name},Ye.id))})]})]})})(),!Fe&&!Re&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{Vs(W.id,W.name,"agent"),ht(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.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"})]}),Z("contextMenu.removeFromOrg")]})]})]})})(),vs&&(()=>{const W=r.find(he=>he.id===vs.userId);return!W||!N?null:h.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:vs.x,top:vs.y},onClick:he=>he.stopPropagation(),children:h.jsxs("button",{onClick:()=>{Vs(W.id,W.name,"human"),bs(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.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"})]}),Z("contextMenu.removeFromOrg")]})})})(),X&&h.jsx(I_,{onClose:()=>M(!1),onCreate:async(W,he)=>{try{const{team:ue}=await J.teams.create(W,he);M(!1),O(),Hr(ue.id),setTimeout(()=>{document.querySelector(`[data-team-id="${ue.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>Hr(null),3e3)}catch(ue){Gr(Z("chat.failedToCreateTeam",{message:ue instanceof Error?ue.message:String(ue)}),"error")}}}),K&&h.jsx(B_,{onClose:()=>{ie(!1),x?.()},onAdd:async(W,he,ue)=>{const{inviteToken:Re}=await J.users.create(W,he,void 0,ue);return x?.(),{inviteToken:Re}}}),oe!==null&&h.jsx(W_,{teamId:oe,ungrouped:U,onClose:()=>G(null),onAdd:async(W,he)=>{await J.teams.addMember(oe,W,he),G(null),O(),Ms()}}),$e&&h.jsx(X_,{onClose:()=>Ie(!1),onConnected:()=>{Ie(!1),p(),O()}}),Ps&&(()=>{const W=o.find(he=>he.id===Ps.gcId);return W?h.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:Ps.x,top:Ps.y},onClick:he=>he.stopPropagation(),children:[W.type==="custom"&&h.jsxs("button",{onClick:()=>{xt(null),k?k(W.channelKey):g(W.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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Z("contextMenu.manageMembers")]}),h.jsxs("button",{onClick:async()=>{xt(null),Mn(Z("modals.deleteGroupChat.title"),Z("modals.deleteGroupChat.message",{name:W.name}),async()=>{await J.groupChats.delete(W.id),y()},Z("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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.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"})]}),Z("modals.deleteGroupChat.menuLabel")]})]}):null})(),We&&h.jsx(q_,{agents:t,humans:r,authUser:e,onClose:()=>Y(!1),onCreate:async(W,he,ue,Re)=>{await J.groupChats.create({name:W,memberIds:he,memberTypes:ue,memberNames:Re,creatorId:e?.id,creatorName:e?.name}),Y(!1),y()}}),ee&&h.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>le(null),children:h.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:W=>W.stopPropagation(),children:[h.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[h.jsx("h3",{className:"text-sm font-semibold",children:Z(ee==="agent"?"chat.addAgent":"chat.newTeam")}),h.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:Z("chat.methodChoiceSubtitle")})]}),h.jsxs("div",{className:"p-3 space-y-2",children:[h.jsxs("button",{onClick:()=>{const W=ee;le(null);const he=t.find(ue=>ue.role==="secretary")??t.find(ue=>ue.name?.toLowerCase().includes("secretary"));he?(f(he.id),Or.navigate(Ht.TEAM,{agentId:he.id,prefillMessage:Z(W==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):W==="agent"?Or.navigate(Ht.STORE):M(!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:[h.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:h.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:[h.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"}),h.jsx("path",{d:"M20 3v4"}),h.jsx("path",{d:"M22 5h-4"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:Z("chat.methodSecretary")}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:Z("chat.methodSecretaryDesc")})]}),h.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:Z("chat.recommended")})]}),h.jsxs("button",{onClick:()=>{const W=ee;le(null),W==="agent"?Or.navigate(Ht.STORE):M(!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:[h.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:h.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:[h.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:Z("chat.methodManual")}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:Z(ee==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),h.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:h.jsx("button",{onClick:()=>le(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:Z("common:cancel")})})]})}),Ei&&h.jsx(Wa,{title:Ei.title,message:Ei.message,confirmLabel:Ei.confirmLabel,checkboxes:Ei.checkboxes,onConfirm:W=>{Ei.onConfirm(W),Kr(null)},onCancel:()=>Kr(null)}),Po&&h.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 ${Po.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:Po.message})]})});function Nm({team:s,agents:e,humans:t,authUser:i,groupChat:r,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:c,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:g,onViewProfile:b,onRefreshAgents:v,onRefreshTeams:m,unreadByAgent:O,width:p,onResizeStart:x,focused:y}){const{t:_}=Pt(["team","common"]),k=wf(),w=_f(Ht.TEAM),S=i?.role==="owner"||i?.role==="admin",Q=C.useMemo(()=>e.filter(X=>X.teamId===s.id),[e,s.id]),I=C.useMemo(()=>{const X=new Set((s.members??[]).filter(M=>M.type==="human").map(M=>M.id));return t.filter(M=>X.has(M.id))},[s.members,t]),D=r&&n==="channel"&&o===r.channelKey,$=C.useMemo(()=>{const X=[];r&&X.push({kind:"channel",id:`channel:${r.channelKey}`,channelKey:r.channelKey});for(const M of Q)X.push({kind:"agent",id:`agent:${M.id}`,agentId:M.id});for(const M of I)X.push({kind:"dm",id:`dm:${M.id}`,userId:M.id});return X},[r,Q,I]),j=C.useRef($);j.current=$;const B=C.useCallback(X=>{X.kind==="channel"?u(X.channelKey):X.kind==="agent"?d(X.agentId):f(X.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${X.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);C.useEffect(()=>{if(!w)return;const X=M=>{if((k?.keyboardPane??"content")!=="l2"||M.metaKey||M.ctrlKey||M.altKey||px(M.target))return;const ie=M.key.length===1?M.key.toLowerCase():M.key;if(ie==="h"||ie==="ArrowLeft"){M.preventDefault(),M.stopPropagation(),k?.setKeyboardPane("l1");return}if(ie==="l"||ie==="ArrowRight"){M.preventDefault(),M.stopPropagation();return}const oe=ie==="j"||ie==="ArrowDown"?1:ie==="k"||ie==="ArrowUp"?-1:0;if(!oe)return;M.preventDefault(),M.stopPropagation();const G=j.current;if(G.length===0)return;let $e=-1;n==="channel"?$e=G.findIndex(We=>We.kind==="channel"&&We.channelKey===o):n==="direct"?$e=G.findIndex(We=>We.kind==="agent"&&We.agentId===a):n==="dm"&&l&&($e=G.findIndex(We=>We.kind==="dm"&&We.userId===l)),$e<0&&($e=oe>0?-1:0);const Ie=Math.max(0,Math.min(G.length-1,$e+oe));B(G[Ie])};return document.addEventListener("keydown",X,!0),()=>document.removeEventListener("keydown",X,!0)},[w,k,n,o,a,l,B]);const F=X=>X?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[V,Z]=C.useState(null),[se,T]=C.useState(!1),[A,N]=C.useState(""),z=C.useCallback((X,M=176,K=220)=>{const ie=window.innerWidth,oe=window.innerHeight,G=8;let $e=X.clientX,Ie=X.clientY;return $e+M>ie-G&&($e=Math.max(G,ie-M-G)),Ie+K>oe-G&&(Ie=Math.max(G,oe-K-G)),$e=Math.max(G,Math.min($e,ie-M-G)),Ie=Math.max(G,Math.min(Ie,oe-K-G)),{x:$e,y:Ie}},[]);C.useEffect(()=>{if(!V)return;const X=()=>Z(null),M=setTimeout(()=>document.addEventListener("click",X),0);return()=>{clearTimeout(M),document.removeEventListener("click",X)}},[V]);const U=C.useCallback(async(X,M)=>{M==="offline"?await J.agents.start(X):await J.agents.stop(X),v()},[v]),ne=C.useCallback(async X=>{await J.teams.update(s.id,{managerId:X,managerType:"agent"}),m()},[s.id,m]),Se=C.useCallback(async X=>{await J.teams.removeMember(s.id,X),m(),v()},[s.id,m,v]),Pe=C.useCallback(async(X,M)=>{await J.teams.removeMember(s.id,X),await J.teams.addMember(M,X,"agent"),m(),v()},[s.id,m,v]);return h.jsxs(h.Fragment,{children:[h.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:p!=null?{width:p}:{width:260},children:[h.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[h.jsx("button",{onClick:g,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:_("common:back",{defaultValue:"Back"}),children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),h.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&h.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[r&&h.jsxs("div",{className:"mb-3",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:_("chat.groupChat",{defaultValue:"Group Chat"})}),h.jsxs("button",{"data-l2-nav-id":`channel:${r.channelKey}`,onClick:()=>u(r.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${F(!!D)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:_("chat.members_other",{count:r.memberCount||Q.length+I.length})})]})]})]}),Q.length>0&&h.jsxs("div",{className:"mb-3",children:[h.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.agents",{defaultValue:"Agents"}),h.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:Q.length})]}),Q.map(X=>{const M=n==="direct"&&a===X.id,K=s.managerId===X.id,ie=X.status==="offline",oe=X.status==="idle"?"bg-green-500":X.status==="working"?"bg-blue-500 animate-pulse":X.status==="error"?"bg-red-500":"bg-gray-600";return h.jsxs("button",{"data-l2-nav-id":`agent:${X.id}`,onClick:()=>d(X.id),onContextMenu:G=>{if(!S)return;G.preventDefault();const $e=z(G);T(!1),N(""),Z({agentId:X.id,...$e})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${ie?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${F(M)}`,children:[h.jsx(_s,{name:X.name,avatarUrl:X.avatarUrl,size:28,bgClass:ie?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:X.name}),K&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:h.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),ie&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:_("common:status.offline")})]}),h.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:X.role||" "})]}),(O?.get(X.id)??0)>0&&h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(X.id)}),h.jsx("span",{title:X.status,onClick:G=>{G.stopPropagation(),b(X.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${oe}`})]},X.id)})]}),I.length>0&&h.jsxs("div",{className:"mb-3",children:[h.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.people"),h.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:I.length})]}),I.map(X=>{const M=X.id===i?.id,K=n==="dm"&&l===X.id;return h.jsxs("button",{"data-l2-nav-id":`dm:${X.id}`,onClick:()=>f(X.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(K)}`,children:[h.jsx(_s,{name:X.name,avatarUrl:X.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[X.name,M?` (${_("chat.you",{defaultValue:"You"})})`:""]}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:X.email||X.role})]}),h.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},X.id)})]}),Q.length===0&&I.length===0&&h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:_("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:h.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"})}),V&&(()=>{const X=Q.find(K=>K.id===V.agentId);if(!X||!S)return null;const M=s.managerId===X.id;return h.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:V.x,top:V.y,maxHeight:Math.max(160,window.innerHeight-V.y-8)},onClick:K=>K.stopPropagation(),children:[h.jsxs("button",{onClick:()=>{Z(null),b(X.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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),_("contextMenu.viewProfile")]}),X.status==="offline"?h.jsxs("button",{onClick:()=>{U(X.id,"offline"),Z(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),_("contextMenu.start")]}):h.jsxs("button",{onClick:()=>{U(X.id,X.status??"idle"),Z(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),_("contextMenu.stop")]}),!M&&h.jsxs("button",{onClick:()=>{ne(X.id),Z(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:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.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"})}),_("contextMenu.setAsManager")]}),h.jsxs("button",{onClick:()=>{Se(X.id),Z(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"9 14 4 9 9 4"}),h.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),_("contextMenu.removeFromTeam")]}),(()=>{const K=c.filter(G=>G.id!==s.id);if(K.length===0)return null;const ie=A.trim().toLowerCase(),oe=ie?K.filter(G=>G.name.toLowerCase().includes(ie)):K;return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{type:"button",onClick:()=>T(G=>!G),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M5 12h14"}),h.jsx("path",{d:"M12 5l7 7-7 7"})]}),h.jsx("span",{className:"flex-1",children:_("contextMenu.moveTo")}),h.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 ${se?"rotate-180":""}`,children:h.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),se&&h.jsxs("div",{className:"px-2 pb-1.5",onClick:G=>G.stopPropagation(),children:[h.jsx("input",{autoFocus:!0,value:A,onChange:G=>N(G.target.value),onKeyDown:G=>G.stopPropagation(),placeholder:_("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"}),h.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:oe.length===0?h.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:_("contextMenu.moveToEmpty")}):oe.map(G=>h.jsx("button",{type:"button",onClick:()=>{Pe(X.id,G.id),Z(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:G.name,children:G.name},G.id))})]})]})})(),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:async()=>{await J.agents.remove(X.id),v(),Z(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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.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"})]}),_("contextMenu.removeFromOrg")]})]})})()]})}function uu(){return uu=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},uu.apply(null,arguments)}function Z_(s,e){if(s==null)return{};var t={};for(var i in s)if({}.hasOwnProperty.call(s,i)){if(e.indexOf(i)!==-1)continue;t[i]=s[i]}return t}let fu=[],Sx=[];(()=>{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<s.length;e++)(e%2?Sx:fu).push(t=t+s[e])})();function V_(s){if(s<768)return!1;for(let e=0,t=fu.length;;){let i=e+t>>1;if(s<fu[i])t=i;else if(s>=Sx[i])e=i+1;else return!0;if(e==t)return!1}}function Dm(s){return s>=127462&&s<=127487}const Im=8205;function F_(s,e,t=!0,i=!0){return(t?_x:Y_)(s,e,i)}function _x(s,e,t){if(e==s.length)return e;e&&wx(s.charCodeAt(e))&&kx(s.charCodeAt(e-1))&&e--;let i=sd(s,e);for(e+=Bm(i);e<s.length;){let r=sd(s,e);if(i==Im||r==Im||t&&V_(r))e+=Bm(r),i=r;else if(Dm(r)){let n=0,a=e-2;for(;a>=0&&Dm(sd(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function Y_(s,e,t){for(;e>1;){let i=_x(s,e-2,t);if(i<e)return i;e--}return 0}function sd(s,e){let t=s.charCodeAt(e);if(!kx(t)||e+1==s.length)return t;let i=s.charCodeAt(e+1);return wx(i)?(t-55296<<10)+(i-56320)+65536:t}function wx(s){return s>=56320&&s<57344}function kx(s){return s>=55296&&s<56320}function Bm(s){return s<65536?1:2}let bt=class Cx{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=uo(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),Xi.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=uo(this,e,t);let i=[];return this.decompose(e,t,i,0),Xi.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new oa(this),n=new oa(e);for(let a=t,o=t;;){if(r.next(a),n.next(a),a=0,r.lineBreak!=n.lineBreak||r.done!=n.done||r.value!=n.value)return!1;if(o+=r.value.length,r.done||o>=i)return!0}}iter(e=1){return new oa(this,e)}iterRange(e,t=this.length){return new Px(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Tx(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Cx.empty:e.length<=32?new Ft(e):Xi.from(Ft.split(e,[]))}};class Ft extends bt{constructor(e,t=U_(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let n=0;;n++){let a=this.text[n],o=r+a.length;if((t?i:o)>=e)return new H_(r,o,i,a);r=o+1,i++}}decompose(e,t,i,r){let n=e<=0&&t>=this.length?this:new Ft(Wm(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let a=i.pop(),o=tc(n.text,a.text.slice(),0,n.length);if(o.length<=32)i.push(new Ft(o,a.length+n.length));else{let l=o.length>>1;i.push(new Ft(o.slice(0,l)),new Ft(o.slice(l)))}}else i.push(n)}replace(e,t,i){if(!(i instanceof Ft))return super.replace(e,t,i);[e,t]=uo(this,e,t);let r=tc(this.text,tc(i.text,Wm(this.text,0,e)),t),n=this.length+i.length-(t-e);return r.length<=32?new Ft(r,n):Xi.from(Ft.split(r,[]),n)}sliceString(e,t=this.length,i=`
|
|
@@ -52,7 +52,7 @@ WARNING: This link could potentially be dangerous`)){const O=window.open();if(O)
|
|
|
52
52
|
"""
|
|
53
53
|
${Y}
|
|
54
54
|
"""`}},[N,Se,p,s]),X=C.useCallback((Y,ee)=>{!Y.trim()||!r||(r(Pe(Y.trim(),ee)),S(null),window.getSelection()?.removeAllRanges(),se.current?.clearSelection())},[r,Pe]),M=C.useCallback(async()=>{if(!r||s.kind!=="terminal")return;const Y=(await se.current?.getRecentOutput(80))?.trim();if(!Y)return;const ee=Y.length>40?`${Y.slice(0,24)}…${Y.slice(-12)}`:Y;r({label:`⌘ ${ee}`,content:["[terminal-output]",`Terminal: ${s.title||"Terminal"} (${s.terminalId})`,s.cwd?`Cwd: ${s.cwd}`:"",'"""',Y,'"""'].filter(Boolean).join(`
|
|
55
|
-
`)})},[r,s]);C.useEffect(()=>{if(s.kind!=="terminal"||!r)return;const Y=navigator.platform.toUpperCase().includes("MAC"),ee=le=>{if(!(Y?le.metaKey&&!le.ctrlKey:le.ctrlKey&&!le.metaKey)||!le.shiftKey||le.altKey||le.key.toLowerCase()!=="a")return;const Ce=se.current?.getSelection()?.trim();Ce&&(le.preventDefault(),X(Ce))};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s.kind,r,X]);const K=C.useCallback(Y=>{if(!Y.text.trim()||!r)return;const ee=F.current?.querySelector("iframe")?.getBoundingClientRect(),le=(ee?.left??0)+Y.rect.x+Y.rect.width/2,ke=(ee?.top??0)+Y.rect.y;S({x:le,y:ke,text:Y.text,htmlMeta:{xpath:Y.xpath,cssSelector:Y.cssSelector}})},[r]);C.useEffect(()=>{const Y=F.current;if(!Y||!r)return;const ee=()=>{requestAnimationFrame(()=>{const ke=window.getSelection(),Ce=ke?.toString().trim();if(!Ce||!ke?.rangeCount){S(null);return}const dt=ke.getRangeAt(0);if(!Y.contains(dt.commonAncestorContainer)){S(null);return}const ht=dt.getBoundingClientRect();S({x:ht.left+ht.width/2,y:ht.top,text:Ce})})},le=ke=>{const Ce=document.getElementById("right-panel-selection-toolbar");Ce&&Ce.contains(ke.target)||S(null)};return Y.addEventListener("mouseup",ee),document.addEventListener("mousedown",le),()=>{Y.removeEventListener("mouseup",ee),document.removeEventListener("mousedown",le)}},[r,x.mode]);const ie=()=>{J.files.reveal(N).catch(()=>{})},oe=()=>{navigator.clipboard?.writeText(N).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},G=C.useCallback(async()=>{if(s.kind==="deliverable"){Or.navigate(Ht.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ee=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const le=await window.markusDesktop.browser.getState(s.browserId);if(le.ok){if(le.directoryPath){await J.system.openPath(le.directoryPath).catch(()=>J.files.reveal(le.directoryPath));return}le.url&&le.url!=="about:blank"&&(ee=le.url)}}catch{}if(!ee||ee==="about:blank")return;if(/^https?:\/\//i.test(ee)||/^file:\/\//i.test(ee)){Sl(ee);return}await J.system.openPath(ee).catch(()=>Sl(z0(ee)));return}if(s.kind!=="file")return;const Y=s.path;if(Y){if(/^https?:\/\//i.test(Y)||/^file:\/\//i.test(Y)){Sl(Y);return}await J.system.openPath(Y).catch(()=>Sl(z0(Y)))}},[s]),$e=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,Ie=s.kind==="deliverable"?p("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):p("common:openInSystemBrowser"),We=!!N&&!lu(N)&&(s.kind==="file"||s.kind==="deliverable");return h.jsxs(h.Fragment,{children:[!d&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:i,children:h.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"})}),h.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[h.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:[b&&h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[h.jsx("button",{type:"button",onClick:()=>b("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":g==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),h.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),h.jsx("button",{type:"button",onClick:()=>b("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":g==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 17 10 11 4 5"}),h.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||c?h.jsxs("div",{"data-no-drag":!0,ref:V,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:Y=>{const ee=Y.currentTarget;ee.scrollWidth<=ee.clientWidth||Math.abs(Y.deltaY)<=Math.abs(Y.deltaX)||(ee.scrollLeft+=Y.deltaY,Y.preventDefault())},children:[n?.map(Y=>{const ee=Y.id===a,le=Y.payload.kind==="url"?Y.payload.pageId:void 0,ke=Y.payload.kind==="terminal"?Y.payload.terminalId:void 0,Ce=le!=null?Q[le]:ke?D[ke]:void 0,dt=Ce?`${Y.title} — ${p("common:browserTabControlledBy",{name:Ce.agentName})}`:Y.title;return h.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ee?Ce?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Ce?"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:[h.jsxs("button",{type:"button",role:"tab","aria-selected":ee,ref:ee?Z: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:dt,onPointerDown:ht=>{ht.button===0&&(Y.id!==a&&!A()||o?.(Y.id))},onClick:()=>{Y.id!==a&&!A()||o?.(Y.id)},children:[Ce&&h.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:p("common:browserTabControlledBy",{name:Ce.agentName}),children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),h.jsx("span",{className:"truncate",children:Ce.agentName})]}),h.jsx("span",{className:"truncate min-w-0",children:Y.title})]}),l&&h.jsx("button",{type:"button",onPointerDown:ht=>{ht.button===0&&(ht.preventDefault(),ht.stopPropagation(),!(Y.id===a&&!A())&&l(Y.id))},onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),!(Y.id===a&&!A())&&l(Y.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ee?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:p("common:closeTab",{defaultValue:"Close tab"}),"aria-label":p("common:closeTab",{defaultValue:"Close tab"}),children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},Y.id)}),c&&h.jsx("button",{type:"button",onClick:c,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:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):h.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:N||z,children:z}),h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&r&&h.jsx("button",{type:"button",onClick:()=>{M()},title:p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.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&&h.jsx("button",{type:"button",onClick:()=>{G()},title:Ie,"aria-label":Ie,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:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),We&&h.jsx("button",{onClick:ie,title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":p("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:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&h.jsx("button",{onClick:u,title:d?p("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):p("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 14 10 14 10 20"}),h.jsx("polyline",{points:"20 10 14 10 14 4"}),h.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("polyline",{points:"9 21 3 21 3 15"}),h.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),h.jsx("button",{onClick:()=>{A()&&e()},title:p("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":p("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:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),h.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&h.jsxs("div",{className:"animate-pulse space-y-3",children:[h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),h.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[h.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M9 18V5l12-2v13"}),h.jsx("circle",{cx:"6",cy:"18",r:"3"}),h.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${cu(x.size)}`:""]})]})]}),h.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[h.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),h.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${cu(x.size)}`:""]})]}),x.mode==="binary"&&h.jsxs("div",{className:"space-y-4 py-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${cu(x.size)}`:""]})]})]}),x.reference&&h.jsx("div",{className:"flex items-center gap-2",children:h.jsx("button",{onClick:()=>{J.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="content"&&(()=>{const Y=N?N.replace(/[/\\][^/\\]+$/,""):void 0,ee=N&&!lu(N)?N:"",le=x.format;return ee&&(le==="code"||le==="json"||le==="text")?h.jsx("div",{ref:F,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(q1,{path:ee,initialContent:x.content,language:Ep(ee,le),onDirtyChange:B})}):ee&&(le==="markdown"||le==="html")?h.jsx("div",{ref:F,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(jA,{path:ee,content:x.content,format:le,basePath:Y,onHtmlSelection:K,onDirtyChange:B})}):h.jsx("div",{ref:F,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:h.jsx(du,{content:x.content,format:le,className:"text-fg-secondary text-sm",onHtmlSelection:K,basePath:Y})})})(),x.mode==="artifact"&&h.jsx("div",{ref:F,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:h.jsx(du,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(MA,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?Y=>f(x.browserId,Y):void 0},x.browserId||x.url)}),x.mode==="terminal"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(zA,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:se,onMeta:v,onOpenUrl:m,onOpenPath:O,onSelection:Y=>{if(!Y||!r){S(null);return}S({x:Y.x,y:Y.y,text:Y.text})}},x.terminalId)}),x.mode==="unpreviewable"&&h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?p("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):p("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:ie,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:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),h.jsx("button",{onClick:ie,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:p("common:open",{defaultValue:"Open"})}),h.jsx("button",{onClick:oe,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${_?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:_?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},ne)]}),w&&r&&h.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:w.x,top:w.y-8},children:h.jsxs("button",{onMouseDown:Y=>{Y.preventDefault(),Y.stopPropagation(),X(w.text,w.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const UA=C.lazy(()=>bx(()=>import("./index-DteFMYqJ.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Rp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function bf(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function Y1(s,e){const i={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[s];return i?e(i):s}const U1={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function Gn(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Z0({agentId:s,onBack:e,inline:t,defaultTab:i,onSwipeBack:r,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:c}=Pt(["agent","common"]),d=Sf(),[u,f]=C.useState(null),[g,b]=C.useState(null),[v,m]=C.useState(i??"overview"),O=o&&l?l:v,[p,x]=C.useState(null),y=C.useMemo(()=>Rp.map($=>({...$,label:c(`agent:tabs.${$.key}`)})),[c]),_=C.useMemo(()=>y.map($=>({id:$.key})),[y]),k=C.useMemo(()=>({onSwipeOutLeft:r}),[r]),w=mx(_,v,m,k),S=C.useRef(null);C.useEffect(()=>{const $=S.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[v]);const Q=C.useCallback(()=>{J.agents.get(s).then(f).catch(()=>{})},[s]);if(C.useEffect(()=>(m(i??"overview"),x(null),Q(),J.externalAgents.list().then(j=>{const B=j.agents.find(F=>F.markusAgentId===s);x(B??null)}).catch(()=>{}),gt.on("agent:update",j=>{j.payload.agentId===s&&Q()})),[s,Q]),!u)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:c("agent:profilePage.loadingAgent")});const I=U1[u.state.status]??"bg-gray-500",D=a?.role==="owner"||a?.role==="admin";return o?h.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:h.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(V0,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:D}),h.jsx("div",{className:"mt-6",children:h.jsx(ox,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:D,onAgentStateChange:Q})})]}),O==="files"&&h.jsx(U0,{agentId:s}),O==="tools"&&h.jsx(H0,{tools:u.tools??[],agent:u}),O==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(K0,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(G0,{agentId:s})})]}),O==="deliverables"&&h.jsx(ax,{agentId:s})]})}):h.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(_s,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:u.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${I}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:Y1(u.state.status,c)}),p&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:c("agent:profilePage.badges.external")}),u.agentRole==="manager"&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:c("agent:profilePage.badges.manager")})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),h.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&h.jsxs("button",{onClick:()=>Or.navigate(Ht.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[h.jsx("span",{children:"◈"})," ",c("agent:profilePage.chat")]}),D&&h.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await J.agents.getFilesMap(s),j={type:"agent",name:gx(u.name,u.name),displayName:u.name,version:"1.0.0",description:u.roleDescription??u.role,author:"",category:"general",tags:[],agent:{roleName:u.role,agentRole:u.agentRole},dependencies:{skills:u.skills??[]}};await Ox.publishViaProxy({itemType:"agent",name:u.name,description:j.description,category:"general",config:j,files:$}),b({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){b({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishFailed",{error:String($)}),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:c("agent:profilePage.publishTitle"),children:[h.jsx("span",{children:"↑"})," ",c("agent:profilePage.hub")]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),h.jsx("div",{ref:S,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>h.jsxs("button",{onClick:()=>m($.key),"data-active":v===$.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${v===$.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:[h.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),h.jsxs("div",{className:"p-5",onTouchStart:d?w.onTouchStart:void 0,onTouchEnd:d?w.onTouchEnd:void 0,children:[(v==="overview"||v==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(V0,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:D}),h.jsx("div",{className:"mt-6",children:h.jsx(ox,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:D,onAgentStateChange:Q})})]}),v==="files"&&h.jsx(U0,{agentId:s}),v==="tools"&&h.jsx(H0,{tools:u.tools??[],agent:u}),v==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(K0,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(G0,{agentId:s})})]}),v==="deliverables"&&h.jsx(ax,{agentId:s})]}),g&&h.jsx(Wa,{alertOnly:!0,variant:g.variant??"primary",title:g.title,message:g.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function V0({agent:s,onUpdate:e,externalInfo:t,t:i,canManageAgents:r}){const[n,a]=C.useState(null),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(null),[g,b]=C.useState(""),[v,m]=C.useState([]);C.useEffect(()=>{J.usage.agents().then(w=>{const S=w.agents.find(Q=>Q.agentId===s.id);S&&a(S)}).catch(()=>{}),J.agents.getRecentActivities(s.id).then(w=>l(w.activities)).catch(()=>{}),J.system.storage().then(w=>{b(w.dataDir+"/agents/"+s.id);const S=w.agents.find(Q=>Q.id===s.id);S&&f(S)}).catch(()=>{}),s.state.activeTaskIds?.length&&J.tasks.list({assignedAgentId:s.id}).then(w=>{m(w.tasks.filter(S=>s.state.activeTaskIds?.includes(S.id)))}).catch(()=>{})},[s.id,s.state.activeTaskIds]);const O=()=>{s.state.status==="offline"?J.agents.start(s.id).then(e):J.agents.stop(s.id).then(e)},p=C.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]),x=C.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(t)return h.jsxs("div",{className:"space-y-4",children:[h.jsx(Gt,{title:i("agent:profilePage.overview.identity"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.name"),children:s.name}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():i("agent:profilePage.emDash")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.connectionStatus"),children:h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.labels.connection"),value:t.connected?i("common:status.online"):i("common:status.offline"),color:t.connected?"green":"gray"}),h.jsx(as,{label:i("agent:profilePage.overview.labels.platform"),value:i("agent:profilePage.overview.openClaw")}),h.jsx(as,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.externalAgentDetails"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):i("agent:profilePage.overview.noneDeclared")}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():i("agent:profilePage.never")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.syncContextTitle"),children:h.jsx("div",{className:"space-y-1.5",children:x.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:w.field}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:w.desc})]},w.field))})}),h.jsx(Gt,{title:i("agent:profilePage.overview.gatewayEndpoints"),children:h.jsx("div",{className:"space-y-1.5",children:p.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${w.method==="POST"?"text-amber-600":"text-green-600"}`,children:w.method}),h.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:w.path}),h.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:w.desc})]},w.path))})})]});const y=o.filter(w=>w.type==="heartbeat").length,_=o.filter(w=>w.type==="chat").length,k=s.state.activeTaskIds?.length??0;return h.jsxs("div",{className:"space-y-4",children:[h.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:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():i("agent:profilePage.emDash")})]}),h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${U1[s.state.status]||"bg-gray-500"}`}),h.jsx("span",{className:`text-sm font-semibold ${s.state.status==="idle"?"text-green-500":s.state.status==="working"?"text-blue-400":s.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:Y1(s.state.status,i)})]}),h.jsx(as,{label:i("agent:profilePage.overview.labels.tokensToday"),value:Gn(s.state.tokensUsedToday)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(k),color:k>0?"blue":void 0}),h.jsx(as,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")}),r&&h.jsx("button",{onClick:O,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?i("agent:profilePage.overview.startAgent"):i("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&h.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-red-500",children:i("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&h.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),h.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:Oc(s.state.lastError,i)||s.state.lastError||i("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&k>0&&h.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:h.jsx("div",{className:"space-y-1",children:v.map(w=>h.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),h.jsx("span",{className:"text-fg-secondary truncate flex-1",children:w.title}),h.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:bf(w.status,i)})]},w.id))})}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.labels.totalTokens"),value:Gn(n.totalTokens)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.promptTokens"),value:Gn(n.promptTokens)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.completionTokens"),value:Gn(n.completionTokens)}),h.jsx(as,{label:"CU Used",value:Gn(n.cuUsed??0)})]})]}),u&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.storage"),value:sx(u.size)}),u.subItems.filter(w=>w.size>0).map(w=>h.jsx(as,{label:w.name,value:sx(w.size)},w.name)),h.jsxs("button",{onClick:()=>{J.system.openPath(g)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[i("agent:profilePage.overview.openFolder")," →"]})]})]})]}),y>0&&h.jsx(Gt,{title:i("agent:profilePage.overview.recentHeartbeats"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.heartbeatRuns",{count:y})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="heartbeat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s.id,activityId:w.id})})]},w.id)})})}),_>0&&h.jsx(Gt,{title:i("agent:profilePage.overview.recentA2A"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.conversations",{count:_})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="chat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s.id,activityId:w.id})})]},w.id)})})})]})}function HA(s,e){const t=s.split(`
|
|
55
|
+
`)})},[r,s]);C.useEffect(()=>{if(s.kind!=="terminal"||!r)return;const Y=navigator.platform.toUpperCase().includes("MAC"),ee=le=>{if(!(Y?le.metaKey&&!le.ctrlKey:le.ctrlKey&&!le.metaKey)||!le.shiftKey||le.altKey||le.key.toLowerCase()!=="a")return;const Ce=se.current?.getSelection()?.trim();Ce&&(le.preventDefault(),X(Ce))};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[s.kind,r,X]);const K=C.useCallback(Y=>{if(!Y.text.trim()||!r)return;const ee=F.current?.querySelector("iframe")?.getBoundingClientRect(),le=(ee?.left??0)+Y.rect.x+Y.rect.width/2,ke=(ee?.top??0)+Y.rect.y;S({x:le,y:ke,text:Y.text,htmlMeta:{xpath:Y.xpath,cssSelector:Y.cssSelector}})},[r]);C.useEffect(()=>{const Y=F.current;if(!Y||!r)return;const ee=()=>{requestAnimationFrame(()=>{const ke=window.getSelection(),Ce=ke?.toString().trim();if(!Ce||!ke?.rangeCount){S(null);return}const dt=ke.getRangeAt(0);if(!Y.contains(dt.commonAncestorContainer)){S(null);return}const ht=dt.getBoundingClientRect();S({x:ht.left+ht.width/2,y:ht.top,text:Ce})})},le=ke=>{const Ce=document.getElementById("right-panel-selection-toolbar");Ce&&Ce.contains(ke.target)||S(null)};return Y.addEventListener("mouseup",ee),document.addEventListener("mousedown",le),()=>{Y.removeEventListener("mouseup",ee),document.removeEventListener("mousedown",le)}},[r,x.mode]);const ie=()=>{J.files.reveal(N).catch(()=>{})},oe=()=>{navigator.clipboard?.writeText(N).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},G=C.useCallback(async()=>{if(s.kind==="deliverable"){Or.navigate(Ht.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ee=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const le=await window.markusDesktop.browser.getState(s.browserId);if(le.ok){if(le.directoryPath){await J.system.openPath(le.directoryPath).catch(()=>J.files.reveal(le.directoryPath));return}le.url&&le.url!=="about:blank"&&(ee=le.url)}}catch{}if(!ee||ee==="about:blank")return;if(/^https?:\/\//i.test(ee)||/^file:\/\//i.test(ee)){Sl(ee);return}await J.system.openPath(ee).catch(()=>Sl(z0(ee)));return}if(s.kind!=="file")return;const Y=s.path;if(Y){if(/^https?:\/\//i.test(Y)||/^file:\/\//i.test(Y)){Sl(Y);return}await J.system.openPath(Y).catch(()=>Sl(z0(Y)))}},[s]),$e=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,Ie=s.kind==="deliverable"?p("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):p("common:openInSystemBrowser"),We=!!N&&!lu(N)&&(s.kind==="file"||s.kind==="deliverable");return h.jsxs(h.Fragment,{children:[!d&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:i,children:h.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"})}),h.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[h.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:[b&&h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[h.jsx("button",{type:"button",onClick:()=>b("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":g==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),h.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),h.jsx("button",{type:"button",onClick:()=>b("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":g==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 17 10 11 4 5"}),h.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||c?h.jsxs("div",{"data-no-drag":!0,ref:V,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:Y=>{const ee=Y.currentTarget;ee.scrollWidth<=ee.clientWidth||Math.abs(Y.deltaY)<=Math.abs(Y.deltaX)||(ee.scrollLeft+=Y.deltaY,Y.preventDefault())},children:[n?.map(Y=>{const ee=Y.id===a,le=Y.payload.kind==="url"?Y.payload.pageId:void 0,ke=Y.payload.kind==="terminal"?Y.payload.terminalId:void 0,Ce=le!=null?Q[le]:ke?D[ke]:void 0,dt=Ce?`${Y.title} — ${p("common:browserTabControlledBy",{name:Ce.agentName})}`:Y.title;return h.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ee?Ce?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Ce?"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:[h.jsxs("button",{type:"button",role:"tab","aria-selected":ee,ref:ee?Z: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:dt,onPointerDown:ht=>{ht.button===0&&(Y.id!==a&&!A()||o?.(Y.id))},onClick:()=>{Y.id!==a&&!A()||o?.(Y.id)},children:[Ce&&h.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:p("common:browserTabControlledBy",{name:Ce.agentName}),children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),h.jsx("span",{className:"truncate",children:Ce.agentName})]}),h.jsx("span",{className:"truncate min-w-0",children:Y.title})]}),l&&h.jsx("button",{type:"button",onPointerDown:ht=>{ht.button===0&&(ht.preventDefault(),ht.stopPropagation(),!(Y.id===a&&!A())&&l(Y.id))},onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),!(Y.id===a&&!A())&&l(Y.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ee?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:p("common:closeTab",{defaultValue:"Close tab"}),"aria-label":p("common:closeTab",{defaultValue:"Close tab"}),children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},Y.id)}),c&&h.jsx("button",{type:"button",onClick:c,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:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):h.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:N||z,children:z}),h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&r&&h.jsx("button",{type:"button",onClick:()=>{M()},title:p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.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&&h.jsx("button",{type:"button",onClick:()=>{G()},title:Ie,"aria-label":Ie,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:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),We&&h.jsx("button",{onClick:ie,title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":p("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:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&h.jsx("button",{onClick:u,title:d?p("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):p("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 14 10 14 10 20"}),h.jsx("polyline",{points:"20 10 14 10 14 4"}),h.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("polyline",{points:"9 21 3 21 3 15"}),h.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),h.jsx("button",{onClick:()=>{A()&&e()},title:p("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":p("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:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),h.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&h.jsxs("div",{className:"animate-pulse space-y-3",children:[h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),h.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[h.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M9 18V5l12-2v13"}),h.jsx("circle",{cx:"6",cy:"18",r:"3"}),h.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${cu(x.size)}`:""]})]})]}),h.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[h.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),h.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${cu(x.size)}`:""]})]}),x.mode==="binary"&&h.jsxs("div",{className:"space-y-4 py-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${cu(x.size)}`:""]})]})]}),x.reference&&h.jsx("div",{className:"flex items-center gap-2",children:h.jsx("button",{onClick:()=>{J.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="content"&&(()=>{const Y=N?N.replace(/[/\\][^/\\]+$/,""):void 0,ee=N&&!lu(N)?N:"",le=x.format;return ee&&(le==="code"||le==="json"||le==="text")?h.jsx("div",{ref:F,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(q1,{path:ee,initialContent:x.content,language:Ep(ee,le),onDirtyChange:B})}):ee&&(le==="markdown"||le==="html")?h.jsx("div",{ref:F,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(jA,{path:ee,content:x.content,format:le,basePath:Y,onHtmlSelection:K,onDirtyChange:B})}):h.jsx("div",{ref:F,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:h.jsx(du,{content:x.content,format:le,className:"text-fg-secondary text-sm",onHtmlSelection:K,basePath:Y})})})(),x.mode==="artifact"&&h.jsx("div",{ref:F,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:h.jsx(du,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(MA,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?Y=>f(x.browserId,Y):void 0},x.browserId||x.url)}),x.mode==="terminal"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(zA,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:se,onMeta:v,onOpenUrl:m,onOpenPath:O,onSelection:Y=>{if(!Y||!r){S(null);return}S({x:Y.x,y:Y.y,text:Y.text})}},x.terminalId)}),x.mode==="unpreviewable"&&h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?p("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):p("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:ie,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:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),h.jsx("button",{onClick:ie,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:p("common:open",{defaultValue:"Open"})}),h.jsx("button",{onClick:oe,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${_?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:_?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},ne)]}),w&&r&&h.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:w.x,top:w.y-8},children:h.jsxs("button",{onMouseDown:Y=>{Y.preventDefault(),Y.stopPropagation(),X(w.text,w.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.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"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const UA=C.lazy(()=>bx(()=>import("./index-BMzsi3-i.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Rp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function bf(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function Y1(s,e){const i={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[s];return i?e(i):s}const U1={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function Gn(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Z0({agentId:s,onBack:e,inline:t,defaultTab:i,onSwipeBack:r,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:c}=Pt(["agent","common"]),d=Sf(),[u,f]=C.useState(null),[g,b]=C.useState(null),[v,m]=C.useState(i??"overview"),O=o&&l?l:v,[p,x]=C.useState(null),y=C.useMemo(()=>Rp.map($=>({...$,label:c(`agent:tabs.${$.key}`)})),[c]),_=C.useMemo(()=>y.map($=>({id:$.key})),[y]),k=C.useMemo(()=>({onSwipeOutLeft:r}),[r]),w=mx(_,v,m,k),S=C.useRef(null);C.useEffect(()=>{const $=S.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[v]);const Q=C.useCallback(()=>{J.agents.get(s).then(f).catch(()=>{})},[s]);if(C.useEffect(()=>(m(i??"overview"),x(null),Q(),J.externalAgents.list().then(j=>{const B=j.agents.find(F=>F.markusAgentId===s);x(B??null)}).catch(()=>{}),gt.on("agent:update",j=>{j.payload.agentId===s&&Q()})),[s,Q]),!u)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:c("agent:profilePage.loadingAgent")});const I=U1[u.state.status]??"bg-gray-500",D=a?.role==="owner"||a?.role==="admin";return o?h.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:h.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(V0,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:D}),h.jsx("div",{className:"mt-6",children:h.jsx(ox,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:D,onAgentStateChange:Q})})]}),O==="files"&&h.jsx(U0,{agentId:s}),O==="tools"&&h.jsx(H0,{tools:u.tools??[],agent:u}),O==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(K0,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(G0,{agentId:s})})]}),O==="deliverables"&&h.jsx(ax,{agentId:s})]})}):h.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(_s,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:u.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${I}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:Y1(u.state.status,c)}),p&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:c("agent:profilePage.badges.external")}),u.agentRole==="manager"&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:c("agent:profilePage.badges.manager")})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),h.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&h.jsxs("button",{onClick:()=>Or.navigate(Ht.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[h.jsx("span",{children:"◈"})," ",c("agent:profilePage.chat")]}),D&&h.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await J.agents.getFilesMap(s),j={type:"agent",name:gx(u.name,u.name),displayName:u.name,version:"1.0.0",description:u.roleDescription??u.role,author:"",category:"general",tags:[],agent:{roleName:u.role,agentRole:u.agentRole},dependencies:{skills:u.skills??[]}};await Ox.publishViaProxy({itemType:"agent",name:u.name,description:j.description,category:"general",config:j,files:$}),b({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){b({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishFailed",{error:String($)}),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:c("agent:profilePage.publishTitle"),children:[h.jsx("span",{children:"↑"})," ",c("agent:profilePage.hub")]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),h.jsx("div",{ref:S,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>h.jsxs("button",{onClick:()=>m($.key),"data-active":v===$.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${v===$.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:[h.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),h.jsxs("div",{className:"p-5",onTouchStart:d?w.onTouchStart:void 0,onTouchEnd:d?w.onTouchEnd:void 0,children:[(v==="overview"||v==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(V0,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:D}),h.jsx("div",{className:"mt-6",children:h.jsx(ox,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:D,onAgentStateChange:Q})})]}),v==="files"&&h.jsx(U0,{agentId:s}),v==="tools"&&h.jsx(H0,{tools:u.tools??[],agent:u}),v==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(K0,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(G0,{agentId:s})})]}),v==="deliverables"&&h.jsx(ax,{agentId:s})]}),g&&h.jsx(Wa,{alertOnly:!0,variant:g.variant??"primary",title:g.title,message:g.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function V0({agent:s,onUpdate:e,externalInfo:t,t:i,canManageAgents:r}){const[n,a]=C.useState(null),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(null),[g,b]=C.useState(""),[v,m]=C.useState([]);C.useEffect(()=>{J.usage.agents().then(w=>{const S=w.agents.find(Q=>Q.agentId===s.id);S&&a(S)}).catch(()=>{}),J.agents.getRecentActivities(s.id).then(w=>l(w.activities)).catch(()=>{}),J.system.storage().then(w=>{b(w.dataDir+"/agents/"+s.id);const S=w.agents.find(Q=>Q.id===s.id);S&&f(S)}).catch(()=>{}),s.state.activeTaskIds?.length&&J.tasks.list({assignedAgentId:s.id}).then(w=>{m(w.tasks.filter(S=>s.state.activeTaskIds?.includes(S.id)))}).catch(()=>{})},[s.id,s.state.activeTaskIds]);const O=()=>{s.state.status==="offline"?J.agents.start(s.id).then(e):J.agents.stop(s.id).then(e)},p=C.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]),x=C.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(t)return h.jsxs("div",{className:"space-y-4",children:[h.jsx(Gt,{title:i("agent:profilePage.overview.identity"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.name"),children:s.name}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():i("agent:profilePage.emDash")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.connectionStatus"),children:h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.labels.connection"),value:t.connected?i("common:status.online"):i("common:status.offline"),color:t.connected?"green":"gray"}),h.jsx(as,{label:i("agent:profilePage.overview.labels.platform"),value:i("agent:profilePage.overview.openClaw")}),h.jsx(as,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.externalAgentDetails"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):i("agent:profilePage.overview.noneDeclared")}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():i("agent:profilePage.never")})]})}),h.jsx(Gt,{title:i("agent:profilePage.overview.syncContextTitle"),children:h.jsx("div",{className:"space-y-1.5",children:x.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:w.field}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:w.desc})]},w.field))})}),h.jsx(Gt,{title:i("agent:profilePage.overview.gatewayEndpoints"),children:h.jsx("div",{className:"space-y-1.5",children:p.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${w.method==="POST"?"text-amber-600":"text-green-600"}`,children:w.method}),h.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:w.path}),h.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:w.desc})]},w.path))})})]});const y=o.filter(w=>w.type==="heartbeat").length,_=o.filter(w=>w.type==="chat").length,k=s.state.activeTaskIds?.length??0;return h.jsxs("div",{className:"space-y-4",children:[h.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:[h.jsx(Ds,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),h.jsx(Ds,{label:i("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():i("agent:profilePage.emDash")})]}),h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${U1[s.state.status]||"bg-gray-500"}`}),h.jsx("span",{className:`text-sm font-semibold ${s.state.status==="idle"?"text-green-500":s.state.status==="working"?"text-blue-400":s.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:Y1(s.state.status,i)})]}),h.jsx(as,{label:i("agent:profilePage.overview.labels.tokensToday"),value:Gn(s.state.tokensUsedToday)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(k),color:k>0?"blue":void 0}),h.jsx(as,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")}),r&&h.jsx("button",{onClick:O,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?i("agent:profilePage.overview.startAgent"):i("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&h.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-red-500",children:i("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&h.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),h.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:Oc(s.state.lastError,i)||s.state.lastError||i("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&k>0&&h.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:h.jsx("div",{className:"space-y-1",children:v.map(w=>h.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),h.jsx("span",{className:"text-fg-secondary truncate flex-1",children:w.title}),h.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:bf(w.status,i)})]},w.id))})}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.labels.totalTokens"),value:Gn(n.totalTokens)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.promptTokens"),value:Gn(n.promptTokens)}),h.jsx(as,{label:i("agent:profilePage.overview.labels.completionTokens"),value:Gn(n.completionTokens)}),h.jsx(as,{label:"CU Used",value:Gn(n.cuUsed??0)})]})]}),u&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(as,{label:i("agent:profilePage.overview.storage"),value:sx(u.size)}),u.subItems.filter(w=>w.size>0).map(w=>h.jsx(as,{label:w.name,value:sx(w.size)},w.name)),h.jsxs("button",{onClick:()=>{J.system.openPath(g)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[i("agent:profilePage.overview.openFolder")," →"]})]})]})]}),y>0&&h.jsx(Gt,{title:i("agent:profilePage.overview.recentHeartbeats"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.heartbeatRuns",{count:y})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="heartbeat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s.id,activityId:w.id})})]},w.id)})})}),_>0&&h.jsx(Gt,{title:i("agent:profilePage.overview.recentA2A"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.conversations",{count:_})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="chat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s.id,activityId:w.id})})]},w.id)})})})]})}function HA(s,e){const t=s.split(`
|
|
56
56
|
`),i=e.split(`
|
|
57
57
|
`),r=t.length,n=i.length,a=Array.from({length:r+1},()=>new Array(n+1).fill(0));for(let f=r-1;f>=0;f--)for(let g=n-1;g>=0;g--)a[f][g]=t[f]===i[g]?a[f+1][g+1]+1:Math.max(a[f+1][g],a[f][g+1]);const o=[];let l=0,c=0,d=1,u=1;for(;l<r||c<n;)l<r&&c<n&&t[l]===i[c]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,c++):c<n&&(l>=r||a[l][c+1]>=a[l+1][c])?(o.push({type:"add",content:i[c],lineNum:u++}),c++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function F0(s){return s.match(/\S+|\s+/g)??[""]}function Y0({oldText:s,newText:e,mode:t}){const i=F0(s),r=F0(e),n=i.length,a=r.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=i[u]===r[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let c=0,d=0;for(;c<n||d<a;)c<n&&d<a&&i[c]===r[d]?(l.push({text:t==="remove"?i[c]:r[d],changed:!1}),c++,d++):d<a&&(c>=n||o[c][d+1]>=o[c+1][d])?(t==="add"&&l.push({text:r[d],changed:!0}),d++):(t==="remove"&&l.push({text:i[c],changed:!0}),c++);return h.jsx("span",{children:l.map((u,f)=>u.changed?h.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):h.jsx("span",{children:u.text},f))})}function GA({agent:s,template:e,templateId:t}){const{t:i}=Pt(["agent","common"]),r=C.useMemo(()=>HA(s,e),[s,e]),[n,a]=C.useState(!0),o=3,l=C.useMemo(()=>{const g=r.map((O,p)=>O.type!=="equal"?p:-1).filter(O=>O>=0);if(g.length===0)return[];const b=[];let v=Math.max(0,g[0]-o),m=Math.min(r.length-1,g[0]+o);for(let O=1;O<g.length;O++){const p=Math.max(0,g[O]-o),x=Math.min(r.length-1,g[O]+o);p<=m+1||(b.push({start:v,end:m}),v=p),m=x}return b.push({start:v,end:m}),b},[r]),c=(g,b,v)=>{const m=g.type==="add"?"+":g.type==="remove"?"-":" ",O=g.type==="add"?"bg-green-500/8":g.type==="remove"?"bg-red-500/8":"",p=g.type==="add"?"text-green-600/90":g.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=g.type==="add"?"text-green-500":g.type==="remove"?"text-red-500":"text-fg-muted",y=g.type==="remove"?g.oldLineNum:g.lineNum;let _=null;return g.type==="remove"&&b+1<v.length&&v[b+1].type==="add"?_=h.jsx(Y0,{oldText:g.content,newText:v[b+1].content,mode:"remove"}):g.type==="add"&&b>0&&v[b-1].type==="remove"&&(_=h.jsx(Y0,{oldText:v[b-1].content,newText:g.content,mode:"add"})),h.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[h.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),h.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:m}),h.jsxs("span",{className:`flex-1 text-[11px] font-mono ${p} whitespace-pre-wrap break-words leading-[20px]`,children:[_??g.content,g.content===""&&" "]})]},b)},d=r.filter(g=>g.type==="add").length,u=r.filter(g=>g.type==="remove").length,f=n?l.flatMap(g=>{const b=[];for(let v=g.start;v<=g.end;v++)b.push({...r[v],_idx:v});return b}):r.map((g,b)=>({...g,_idx:b}));return h.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.diff.title",{templateId:t})}),h.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),h.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),h.jsx("button",{onClick:()=>a(g=>!g),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:i(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),h.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&h.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:l[0].start})}),f.map((g,b)=>{const v=b>0?f[b-1]:null,m=n&&v&&g._idx-v._idx>1;return h.jsxs("div",{children:[m&&h.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:"···"}),c(g,g._idx,r)]},b)}),n&&l.length>0&&l[l.length-1].end<r.length-1&&h.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:r.length-1-l[l.length-1].end})}),l.length===0&&h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:i("agent:profilePage.diff.identical")})]})]})}function KA(s,e){const t=s.split(`
|
|
58
58
|
`),i=e.split(`
|
|
@@ -69,7 +69,7 @@ ${Y}
|
|
|
69
69
|
`+se.join(`
|
|
70
70
|
---
|
|
71
71
|
|
|
72
|
-
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Or.navigate(Ht.TEAM,{agentId:s,prefillMessage:T})},D=async V=>{if(y?.file===V){_(null);return}try{const Z=await J.agents.roleDiff(s,V);Z.agentContent!=null&&Z.templateContent!=null&&_({file:V,agent:Z.agentContent,template:Z.templateContent})}catch{}};if(r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},j=V=>{const Z=$[V];return Z?e(`agent:profilePage.filesTab.fileLabels.${Z}`):V},B=p?.hasTemplate&&!p.isUpToDate,F=a?Q.some(V=>V.file===a):!1;return h.jsxs("div",{className:"space-y-4",children:[B&&h.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[h.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),h.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:Q.length,templateId:p.templateId})," ",Q.map(V=>V.file).join(", ")]})]}),h.jsx("button",{onClick:()=>I(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),h.jsxs(Gt,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",h.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[h.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(V=>{const Z=Q.some(se=>se.file===V.name);return h.jsxs("button",{onClick:()=>w(V.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===V.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[V.name,Z&&h.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},V.name)})}),a&&h.jsxs("div",{children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("div",{className:"text-xs text-fg-secondary",children:j(a)}),h.jsxs("div",{className:"flex gap-2 items-center",children:[F&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>D(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),h.jsx("button",{onClick:()=>I(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),b&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&h.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[h.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),g(!0),setTimeout(()=>g(!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:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),h.jsx("button",{onClick:()=>{J.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&h.jsx(GA,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),h.jsx(JA,{content:t.find(V=>V.name===a)?.content??"",editContent:l,setEditContent:V=>{c(V),O(!0)},dirty:m,onSave:S}),a==="ROLE.md"&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&h.jsx(Gc,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function JA({content:s,editContent:e,setEditContent:t,dirty:i,onSave:r}){const[n,a]=C.useState(!1),o=C.useRef(null);return C.useEffect(()=>{n&&o.current?.focus()},[n]),C.useEffect(()=>{a(!1)},[s]),n||i?h.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&r(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):h.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[h.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(UA,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const eM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{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 tM(s,e){const t=new Map,i=new Set;for(const{id:a,prefixes:o}of eM){const l=e(`agent:toolCategories.${a}`),c=s.filter(d=>!i.has(d.name)&&o.some(u=>d.name.startsWith(u)));c.length>0&&(t.set(l,c),c.forEach(d=>i.add(d.name)))}const r=s.filter(a=>!i.has(a.name));for(const a of r){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),c=e("agent:toolCategories.mcp",{server:l});t.has(c)||t.set(c,[]),t.get(c).push(a),i.add(a.name)}}const n=s.filter(a=>!i.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function sM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function iM({tools:s}){const{t:e}=Pt(["agent","common"]),t=tM(s,e);return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(i=>h.jsx(Gt,{title:`${i.category} (${i.tools.length})`,children:h.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:i.tools.map(r=>{const n=n_(r.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=r.name.includes("__"),l=o?r.name.split("__").pop():r.name,c=sM(r.description||"");return h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[h.jsx(o_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&h.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&h.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),c&&h.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:c,children:c})]})]},r.name)})})},i.category)),s.length===0&&h.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function rM({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[i,r]=C.useState(null),[n,a]=C.useState(null),[o,l]=C.useState(!1),c=s.availableSkills??[],d=new Map;for(const m of c){const O=m.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(m)}const u=async m=>{if(i===m){r(null),a(null);return}r(m),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(m)}`);if(O.ok){const p=await O.json();a(p.skill)}else a(null)}catch{a(null)}l(!1)},f={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"},g=m=>{const O=t[m.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:O.uses,successes:O.successes}),O.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(O.lastUsed).toLocaleDateString()})]}),y=i===m.name;return h.jsxs("div",{children:[h.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(m.name),children:[h.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:m.name}),m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),m.builtIn&&!m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!m.builtIn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:m.description}),x]}),p!==null&&h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:h.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&h.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(_=>h.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:_},_))]}),n.description&&h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&h.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(_=>h.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",_]},_))}),(n.toolDetails??n.tools??[]).length>0&&h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),h.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(_=>h.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:_.name}),_.description&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:_.description})]},_.name))})]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},m.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],v=[...d.entries()].sort((m,O)=>{const p=b.indexOf(m[0]),x=b.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:c.length})})}),v.map(([m,O])=>h.jsx(Gt,{title:h.jsxs("span",{className:"capitalize",children:[m," ",h.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:h.jsx("div",{className:"space-y-2",children:O.map(p=>g(p))})},m)),c.length===0&&h.jsx(Gc,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function H0({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[i,r]=C.useState("tools");return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>h.jsx("button",{onClick:()=>r(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${i===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),i==="tools"?h.jsx(iM,{tools:s}):h.jsx(rM,{agent:e})]})}function G0({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,i]=C.useState(null),[r,n]=C.useState(!0),[a,o]=C.useState("longterm"),[l,c]=C.useState(""),[d,u]=C.useState(""),[f,g]=C.useState(!1),[b,v]=C.useState(null),[m,O]=C.useState(null),[p,x]=C.useState([]),[y,_]=C.useState(!1),k=C.useCallback(()=>{n(!0),J.agents.getMemory(s).then($=>{i($),c($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);C.useEffect(()=>{k()},[k]);const w=async()=>{g(!0),await J.agents.updateDailyMemory(s,l).catch(()=>{}),g(!1),k()},S=async()=>{g(!0),await J.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),g(!1),k()},Q=l!==(t?.recentDailyLogs??""),I=d!==(t?.longTermMemory??"");if(r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const D=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex gap-2",children:D.map($=>h.jsx("button",{onClick:()=>o($.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===$.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:$.label},$.key))}),a==="entries"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?h.jsx(Gc,{text:e("agent:profilePage.memoryTab.noEntries")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,j)=>{const B=b===j;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>v(B?null:j),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:[h.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.type==="fact"?"bg-blue-500/15 text-blue-600":$.type==="task"?"bg-green-500/15 text-green-600":$.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:$.type}),h.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:$.content}),h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&h.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${$.importance>=7?"bg-red-500/15 text-red-500":$.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",$.importance]}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&h.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[h.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),h.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[h.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&h.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),h.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},j)})})}),a==="sessions"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?h.jsx(Gc,{text:e("agent:profilePage.memoryTab.noSessions")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const j=m===$.id,B=async()=>{if(j){O(null),x([]);return}O($.id),_(!0);try{const F=await J.agents.getMemorySession(s,$.id);x(F.messages)}catch{x([])}_(!1)};return h.jsxs("div",{children:[h.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[h.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:j?"▲":"▼"})]}),j&&h.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const F=new Map;for(const V of p)V.role==="tool"&&V.toolCallId&&F.set(V.toolCallId,V.content);return h.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(V=>V.role!=="tool").map((V,Z)=>h.jsxs("div",{className:"px-3 py-2",children:[(V.role==="user"||V.role==="system")&&h.jsxs("div",{children:[h.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${V.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${V.role}`,{defaultValue:V.role})}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(ma,{content:V.content,className:"text-xs text-fg-secondary"})})]}),V.role==="assistant"&&h.jsxs("div",{className:"space-y-1",children:[V.content&&h.jsxs("div",{children:[h.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(ma,{content:V.content,className:"text-xs text-fg-secondary"})})]}),V.toolCalls&&V.toolCalls.length>0&&h.jsx("div",{className:"space-y-0.5",children:V.toolCalls.map(se=>{let T;try{T=JSON.parse(se.arguments)}catch{}const A={tool:se.name,status:"done",args:T,result:F.get(se.id)};return h.jsx(e_,{entry:{type:"tool",info:A}},se.id)})})]})]},Z))})})()})]},$.id)})})}),a==="daily"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:Q?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>c(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:w,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:l,onChange:$=>c($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:I?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:S,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:d,onChange:$=>u($.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function K0({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[i,r]=C.useState(e??null),[n,a]=C.useState(!e),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(!1),[g,b]=C.useState(null),v=C.useCallback(()=>Promise.all([J.agents.getHeartbeat(s).then(r).catch(()=>{}),J.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);C.useEffect(()=>{a(!0),v().finally(()=>a(!1))},[v]),C.useEffect(()=>gt.on("agent:update",_=>{_.payload?.agentId===s&&v()}),[s,v]);const m=async()=>{f(!0),b(null);try{const y=await J.agents.triggerHeartbeat(s);b(y.message),setTimeout(()=>b(null),4e3),setTimeout(v,2e3)}catch(y){b(String(y).replace("Error: ",""))}f(!1)},O=async y=>{try{await J.agents.cancelWakeup(s,y),v()}catch{}};if(n)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=y=>y?y<1e3?`${y}ms`:y<6e4?`${(y/1e3).toFixed(1)}s`:`${(y/6e4).toFixed(1)}m`:null,x=y=>{if(!y)return null;const _=Date.now()-new Date(y).getTime();if(_<0){const k=Math.abs(_);return k<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(k/1e3)}):k<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(k/6e4)}):t("agent:profilePage.relative.inHours",{hours:(k/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return h.jsxs("div",{className:"space-y-4",children:[h.jsxs(Gt,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:v,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),h.jsx("button",{onClick:m,disabled:u||!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:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[h.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[h.jsx(as,{label:t("agent:profilePage.overview.labels.status"),value:i.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:i.running?"green":"gray"}),h.jsx(oM,{agentId:s,intervalMs:i.intervalMs,onChanged:v}),h.jsx(as,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:i.lastHeartbeat?x(i.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),h.jsx(as,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:i.nextWakeAt?x(i.nextWakeAt)??t("agent:profilePage.emDash"):i.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),h.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),g&&h.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:g})]}),i.wakeups&&i.wakeups.length>0&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:i.wakeups.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.wakeups.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[x(y.wakeAt)??new Date(y.wakeAt).toLocaleString(),y.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${y.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),h.jsx("button",{onClick:()=>O(y.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},y.id))})}),i.pendingCallbacks&&i.pendingCallbacks.length>0&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:i.pendingCallbacks.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.pendingCallbacks.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${y.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${x(y.timeoutAt)??new Date(y.timeoutAt).toLocaleString()}`]})]})]},y.id))})}),i.lastSummary&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:i.lastSummaryAt?h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(i.lastSummaryAt).toLocaleString()}):void 0,children:h.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:h.jsx(ma,{content:i.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const _=c===y.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(_?null:y.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),h.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:h.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s,activityId:y.id})})]},y.id)})})}):i.lastHeartbeat?null:h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:h.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[h.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),h.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),h.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:i.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(i.intervalMs-i.uptimeMs%i.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),i.running&&h.jsx("button",{onClick:m,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function nM({taskId:s,isLive:e}){const{t}=Pt("agent"),[i,r]=C.useState([]),[n,a]=C.useState(""),[o,l]=C.useState(!0),[c,d]=C.useState("compact");if(C.useEffect(()=>{l(!0),a(""),J.tasks.getLogs(s).then(g=>{r(g.logs),l(!1)}).catch(()=>l(!1))},[s]),C.useEffect(()=>{if(!e)return;const g=gt.on("task:log",v=>{const m=v.payload;if(m.taskId!==s)return;const O={id:m.id,taskId:m.taskId,agentId:m.agentId,seq:m.seq,type:m.logType,content:m.content,metadata:m.metadata,createdAt:m.createdAt};r(p=>O.id&&p.some(x=>x.id===O.id)?p:[...p,O]),O.type==="text"&&a("")}),b=gt.on("task:log:delta",v=>{const m=v.payload;m.taskId===s&&a(O=>O+m.text)});return()=>{g(),b()}},[s,e]),o)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(i.length===0&&!n)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=i.map(g=>r_(g)),f=new Set(u.filter(g=>g.executionRound!=null).map(g=>g.executionRound)).size>1;return h.jsx("div",{className:"px-3 py-2",children:c==="compact"?h.jsx(xx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):h.jsx(vx,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Ba({agentId:s,activityId:e,isLive:t=!1}){const{t:i}=Pt("agent"),[r,n]=C.useState([]),[a,o]=C.useState(!0),[l,c]=C.useState("compact");if(C.useEffect(()=>{o(!0),J.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),C.useEffect(()=>t?gt.on("agent:activity_log",f=>{const g=f.payload;if(g.agentId!==s||g.activityId!==e)return;const b={seq:g.seq,type:g.type,content:g.content,metadata:g.metadata,createdAt:g.createdAt};n(v=>v.some(m=>m.seq===b.seq)?v:[...v,b])}):void 0,[s,e,t]),a)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.loading")});if(r.length===0)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.noLogs")});const d=r.map(u=>i_(u,e,s)).filter(u=>u!==null);return h.jsx("div",{className:"px-3 py-2",children:l==="compact"?h.jsx(xx,{entries:d,isActive:t,onExpand:()=>c("full")}):h.jsx(vx,{entries:d,isActive:t,onCollapse:()=>c("compact")})})}function Gt({title:s,action:e,children:t}){return h.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[h.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Ds({label:s,mono:e,children:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),h.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function as({label:s,value:e,color:t}){const i=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return h.jsxs("div",{className:"flex items-baseline gap-1.5",children:[h.jsx("span",{className:`text-sm font-semibold ${i}`,children:e}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const J0=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],ex=5,tx=1440;function oM({agentId:s,intervalMs:e,onChanged:t}){const{t:i}=Pt(["agent","common"]),[r,n]=C.useState(!1),[a,o]=C.useState(null),[l,c]=C.useState(!1),[d,u]=C.useState(String(Math.round(e/6e4))),f=p=>p%(3600*1e3)===0?i("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):i("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),g=async p=>{n(!0),o(null);try{await J.agents.updateConfig(s,{heartbeatIntervalMs:p}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},b=p=>{if(p.target.value==="custom"){c(!0);return}c(!1),g(Number(p.target.value))},v=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<ex||p>tx){o(i("agent:profilePage.heartbeatTab.intervalRangeHint"));return}g(p*60*1e3)},m=J0.includes(e),O=l||!m?"custom":String(e);return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.heartbeatTab.safetyNetInterval")}),h.jsxs("select",{value:O,onChange:b,disabled:r,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:[!m&&h.jsx("option",{value:String(e),children:f(e)}),J0.map(p=>h.jsx("option",{value:String(p),children:f(p)},p)),h.jsx("option",{value:"custom",children:i("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!m)&&h.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[h.jsx("input",{type:"number",min:ex,max:tx,value:d,onChange:p=>u(p.target.value),disabled:r,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"}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.heartbeatTab.intervalCustomUnit")}),h.jsx("button",{onClick:v,disabled:r,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(r?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&h.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Gc({text:s}){return h.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function sx(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),i=s/Math.pow(1024,t);return`${i<10?i.toFixed(1):Math.round(i)} ${e[t]}`}const ix={0:"0",1:"1",2:"2",3:"3",4:"4"},rx={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},aM={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"},lM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Hl={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:"🧠"},cM=["all","interaction","task","notification","system"],hM={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"]},dM={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"},uM={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 hu(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function nx(s,e){const t=s.payload,i=t?.summary??"",r=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=i.match(/^Task "(.+?)" status:/),o=i.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??i;if(o){const d=o[1],u=o[2],f=bf(d,e),g=bf(u,e),b=uM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:g}),badge:{label:g,color:b}}}const c=i.match(/^Task:\s*(.+)/);return c?{title:c[1]}:{title:l}}case"task_comment":{const a=i.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=hu(r);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:i}}case"requirement_update":{const a=i.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:i}}case"requirement_comment":{const a=i.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=hu(r);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:i}}case"human_chat":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(r.length>120?"…":"")}}case"a2a_message":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(r.length>120?"…":"")}}case"mention":{const a=i.match(/from (.+)$/),o=hu(r);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(r.length>120?"…":"")}}case"session_reply":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(r.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=i.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:i||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:i||s.sourceType}}}function ox({agentId:s,highlightId:e,agentStatus:t,canManageAgents:i,onAgentStateChange:r}){const{t:n}=Pt(["agent","common","team"]),[a,o]=C.useState(null),[l,c]=C.useState(null),[d,u]=C.useState(!0),[f,g]=C.useState("all"),[b,v]=C.useState("all"),[m,O]=C.useState(e??null),[p,x]=C.useState(e??null),[y,_]=C.useState(!1),[k,w]=C.useState(!0),[S,Q]=C.useState(null),I=50,D=3,$=C.useCallback(async(T=!0)=>{T&&u(!0);try{const A=f==="all"?void 0:f,N=b==="all"?void 0:b,[z,U]=await Promise.all([J.agents.getMindState(s),J.agents.getMailbox(s,{limit:I,category:A,status:N})]);o(z),c(U),w((U.history?.length??0)>=I)}catch{}u(!1)},[s,f,b]),j=C.useCallback(async()=>{if(!l)return;const T=f==="all"?void 0:f,A=b==="all"?void 0:b;try{const N=await J.agents.getMailbox(s,{limit:I,offset:l.history.length,category:T,status:A});c(z=>z?{...z,history:[...z.history,...N.history]}:N),w((N.history?.length??0)>=I)}catch{}},[s,l,f,b]);C.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const B=C.useRef(!1);if(C.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){B.current=!1;const A=document.getElementById(`mbx-${p}`);if(A){setTimeout(()=>A.scrollIntoView({behavior:"smooth",block:"center"}),100);const N=setTimeout(()=>x(null),3e3);return()=>clearTimeout(N)}}else k&&!B.current&&(B.current=!0,(async()=>{let A=l?.history??[],N=k;for(;N;)try{const z=await J.agents.getMailbox(s,{limit:I,offset:A.length}),U=[...A,...z.history];A=U,N=(z.history?.length??0)>=I;const ne=z.history.some(Se=>Se.id===p);if(c(Se=>Se?{...Se,history:U}:z),w(N),ne||!N)break}catch{break}B.current=!1})())},[p,d,l,k,s]),C.useEffect(()=>{let T=null;const A=z=>{z.payload?.agentId===s&&(T&&clearTimeout(T),T=setTimeout(()=>{T=null,$(!1)},500))},N=[gt.on("agent:mailbox",A),gt.on("agent:decision",A),gt.on("agent:attention",A),gt.on("agent:focus",A),gt.on("agent:update",A),gt.on("agent:triage",A)];return()=>{T&&clearTimeout(T),N.forEach(z=>z())}},[s,$]),d&&!a)return h.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:n("agent:profilePage.mind.loading")});const F=a?.mailboxDepth??a?.queuedItems?.length??0,V=(()=>{const T=a?.attentionState??"idle";return T==="deciding"||T==="idle"&&F>0?"deciding":T!=="idle"&&!a?.currentFocus?"idle":T})(),Z=V==="idle"&&l?.history?.some(T=>T.status==="processing"),se=(a?.attentionState??"idle")==="idle"&&F>0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[h.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${lM[V]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${V}`)}),a?.currentFocus?(()=>{const T=nx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return h.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[h.jsxs("span",{children:[Hl[a.currentFocus.type]??"●"," ",h.jsx("span",{className:"text-fg-primary font-medium",children:T.title}),T.subtitle&&h.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:T.subtitle}),h.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),i&&h.jsxs("button",{onClick:()=>Q(a.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:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]})})():se?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.queuedButIdle",{count:F,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:F})}):h.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[i&&t==="offline"&&h.jsxs("button",{onClick:()=>{J.agents.start(s).then(()=>{r?.(),$()})},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:["▶ ",n("agent:profilePage.mind.continueBtn")]}),i&&(t==="working"||t==="idle")&&h.jsxs("button",{onClick:()=>{J.agents.stop(s).then(()=>{r?.(),$()})},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:["■ ",n("team:contextMenu.stop")]}),h.jsx("button",{onClick:()=>{$()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:n("agent:profilePage.mind.refresh")})]})]}),Z&&h.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:[h.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),h.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const T=a.queuedItems,A=T.length>D,N=A&&!y?T.slice(0,D):T,z=T.reduce((U,ne)=>(U[ne.sourceType]=(U[ne.sourceType]??0)+1,U),{});return h.jsxs("div",{className:"mb-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:T.length})}),h.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(z).map(([U,ne])=>h.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Hl[U]??"●"," ",ne]},U))})]}),h.jsxs("div",{className:"space-y-1",children:[N.map((U,ne)=>h.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:[h.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:ne+1}),h.jsx("span",{className:"text-sm",children:Hl[U.sourceType]??"●"}),h.jsx("span",{className:`text-[10px] ${rx[U.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${ix[U.priority]??U.priority}`,{defaultValue:`P${U.priority}`})}),h.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:U.summary}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(U.queuedAt).toLocaleTimeString()})]},U.id)),A&&h.jsx("button",{onClick:()=>_(!y),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:y?n("agent:profilePage.mind.collapseQueue"):n("agent:profilePage.mind.expandQueue",{count:T.length-D})})]})]})})()]}),(a?.notebook?.length??0)>0&&h.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:h.jsxs("details",{open:!0,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"📓"}),h.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),h.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),h.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(T=>{const A=Date.now()-T.updatedAt,N=A<6e4?`${Math.round(A/1e3)}s ago`:A<36e5?`${Math.round(A/6e4)}min ago`:`${(A/36e5).toFixed(1)}h ago`,z=T.managed==="system"?"text-blue-400":T.managed==="cpp"?"text-purple-400":"text-emerald-400";return h.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary",children:T.key}),h.jsxs("span",{className:`text-[10px] ${z}`,children:["[",T.managed,"]"]}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:N})]}),h.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:T.text.length>500?T.text.slice(0,500)+"…":T.text})]},T.key)})})]})}),a?.deliberationActivity&&h.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),h.jsx(Ba,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return h.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:h.jsxs("details",{open:!A,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),h.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:n("agent:profilePage.mind.deferred",{count:a.lastTriage.deferredItemIds.length})}),a.lastTriage.droppedItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:n("agent:profilePage.mind.dropped",{count:a.lastTriage.droppedItemIds.length})}),(a.lastTriage.inlineCompletedIds?.length??0)>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:n("agent:profilePage.mind.inlineCompleted",{count:a.lastTriage.inlineCompletedIds.length})})]})]})})})(),h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),h.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:cM.map(T=>{const A=l?.sourceTypeCounts,N=T==="all"?A?Object.values(A).reduce((z,U)=>z+U,0):void 0:A?(hM[T]??[]).reduce((z,U)=>z+(A[U]??0),0):void 0;return h.jsxs("button",{onClick:()=>g(T),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===T?"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:[n(`agent:profilePage.mind.categoryFilters.${T}`),N!=null&&N>0&&h.jsx("span",{className:"ml-1 opacity-60",children:N})]},T)})})]}),h.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(T=>{const A=l?.statusCounts,N=T.key==="all"?A?Object.values(A).reduce((z,U)=>z+U,0):void 0:A?.[T.key];return h.jsxs("button",{onClick:()=>v(T.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${b===T.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:[T.dot&&h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T.dot}`}),n(`agent:profilePage.mind.statusFilters.${T.key}`),N!=null&&N>0&&h.jsx("span",{className:"ml-1 opacity-60",children:N})]},T.key)})}),(!l?.history||l.history.length===0)&&!d&&h.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),h.jsx("div",{className:"space-y-1",children:l?.history?.map(T=>{const A=m===T.id,N=Hl[T.sourceType]??"●",z=nx(T,n),U=T.metadata?.senderName,ne=T.metadata?.senderRole,Se=p===T.id;return h.jsxs("div",{id:`mbx-${T.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${Se?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[h.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:()=>O(A?null:T.id),children:[h.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),h.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${dM[T.status]??"bg-gray-400"}`}),h.jsx("span",{className:"text-sm",children:N}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:z.title}),z.badge&&h.jsx("span",{className:`text-[10px] font-medium shrink-0 ${z.badge.color}`,children:z.badge.label}),h.jsx("span",{className:`text-[10px] shrink-0 ${rx[T.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${ix[T.priority]??T.priority}`,{defaultValue:""})})]}),z.subtitle&&h.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:z.subtitle}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[h.jsx("span",{children:new Date(T.queuedAt).toLocaleString()}),T.completedAt&&h.jsxs("span",{children:["→ ",new Date(T.completedAt).toLocaleTimeString()]}),T.activity&&h.jsxs(h.Fragment,{children:[T.activity.totalTokens>0&&h.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:Gn(T.activity.totalTokens)})}),T.activity.totalTools>0&&h.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:T.activity.totalTools})})]})]})]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:T.sourceType}),i&&T.status==="processing"&&h.jsxs("button",{onClick:Pe=>{Pe.stopPropagation(),Q(T.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:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]}),A&&h.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[U&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",h.jsx("span",{className:"text-fg-secondary",children:U}),ne&&h.jsxs("span",{className:"text-fg-tertiary",children:[" (",ne,")"]})]}),T.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(T.sourceType)&&h.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:T.payload.content}),T.decisions&&T.decisions.length>0&&h.jsxs("div",{children:[h.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),h.jsx("div",{className:"space-y-1",children:T.decisions.map(Pe=>h.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${aM[Pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:Pe.decisionType}),h.jsx("span",{className:"text-fg-secondary flex-1",children:Pe.reasoning}),h.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(Pe.createdAt).toLocaleTimeString()})]},Pe.id))})]}),T.activity?h.jsxs("div",{children:[h.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:T.activity.label}),h.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${T.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:T.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),T.activity.type==="task"&&T.payload?.taskId?h.jsx(nM,{taskId:T.payload.taskId,isLive:!T.activity.endedAt}):h.jsx(Ba,{agentId:s,activityId:T.activity.id,isLive:!T.activity.endedAt})]}):T.status==="processing"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):T.status==="completed"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},T.id)})}),k&&(l?.history?.length??0)>0&&h.jsx("div",{className:"text-center mt-3",children:h.jsx("button",{onClick:j,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),S&&h.jsx(Wa,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{Q(null),J.agents.cancelProcessing(s).then(()=>{let T=0;const A=()=>{T+=1,$(),T<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>Q(null)})]})}function ax({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,i]=C.useState([]),[r,n]=C.useState(!0),[a,o]=C.useState(null),l=C.useCallback(async()=>{n(!0);try{const{results:c}=await J.deliverables.search({agentId:s,limit:200});i(c)}catch{i([])}n(!1)},[s]);return C.useEffect(()=>{l()},[l]),C.useEffect(()=>{const c=gt.on("deliverable:created",()=>l()),d=gt.on("deliverable:updated",()=>l()),u=gt.on("deliverable:removed",()=>l());return()=>{c(),d(),u()}},[l]),r?h.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(c=>h.jsxs("div",{className:"animate-pulse space-y-2",children:[h.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),h.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},c))}):t.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[h.jsx("span",{className:"text-3xl mb-3",children:"📦"}),h.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),h.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:t.length})}),t.map(c=>{const d=t_[c.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=Sm[c.status]??Sm.active;return h.jsxs("button",{onClick:()=>o(c),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:[h.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:c.title}),h.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:c.status})]}),c.summary&&h.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:c.summary}),h.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[h.jsx("span",{children:new Date(c.createdAt).toLocaleDateString()}),c.tags.length>0&&h.jsx("span",{children:c.tags.slice(0,3).join(", ")})]})]}),h.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:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},c.id)})]}),a&&h.jsx(s_,{item:a,onClose:()=>o(null),onOpenInPage:c=>{o(null),Or.navigate(Ht.DELIVERABLES,{openDeliverable:c})}})]})}const fM=C.lazy(()=>bx(()=>import("./index-DteFMYqJ.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Ap=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],lx={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function cx({teamId:s,onBack:e,inline:t,headless:i,activeTab:r,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=C.useState(null),[c,d]=C.useState(null),[u,f]=C.useState("overview"),g=i&&r?r:u,[b,v]=C.useState(""),[m,O]=C.useState(""),[p,x]=C.useState(!1),[y,_]=C.useState(!1),[k,w]=C.useState(""),[S,Q]=C.useState(""),I=C.useRef(null),D=C.useRef(null),$=C.useRef(null),j=C.useRef(null),[B,F]=C.useState(!1),[V,Z]=C.useState(!1),[se,T]=C.useState(""),[A,N]=C.useState(""),[z,U]=C.useState(!1),[ne,Se]=C.useState([]),Pe=C.useRef(null),X=C.useCallback(async()=>{try{const ee=(await J.teams.list()).teams.find(ke=>ke.id===s);ee&&l(ee);const le=await J.teams.status(s);Se(le.agents)}catch{}},[s]),M=C.useCallback(async()=>{try{const Y=await J.teams.getFile(s,"ANNOUNCEMENT.md");v(Y.content)}catch{v("")}try{const Y=await J.teams.getFile(s,"NORMS.md");O(Y.content)}catch{O("")}},[s]);C.useEffect(()=>{f("overview"),X(),M()},[s,X,M]),C.useEffect(()=>{p&&D.current&&D.current.focus()},[p]),C.useEffect(()=>{y&&j.current&&j.current.focus()},[y]);const K=async(Y,ee)=>{F(!0);try{await J.teams.updateFile(s,Y,ee),Y==="ANNOUNCEMENT.md"?(v(ee),x(!1)):(O(ee),_(!1))}catch{}F(!1)},ie=async()=>{se.trim()&&(await J.teams.update(s,{name:se.trim()}),Z(!1),X())},oe=async()=>{await J.teams.update(s,{description:A}),U(!1),X()};if(!o)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const G=o.members.find(Y=>Y.agentRole==="manager"),$e=ne.filter(Y=>Y.status!=="offline").length,Ie=g==="announcements"&&p||g==="norms"&&y;if(i)return h.jsx("div",{className:`flex-1 bg-surface-primary ${Ie?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:h.jsxs("div",{className:`${Ie?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:G?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Y=>{const ee=ne.find(Ce=>Ce.id===Y.id),le=lx[ee?.status??"offline"]??"bg-gray-500",ke=Y.type==="agent";return h.jsxs("div",{onClick:()=>ke&&n?.(Y.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ke&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(_s,{name:Y.name,avatarUrl:Y.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:Y.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${le}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ee?.status??"offline"}),Y.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Y.role," · ",Y.type]})]}),ke&&n&&h.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:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Y.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),g==="announcements"&&h.jsx(Gl,{content:b,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:D,contentRef:I,saving:B,onSave:()=>K("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),g==="norms"&&h.jsx(Gl,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:B,onSave:()=>K("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),g==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),V?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:Pe,value:se,onChange:Y=>T(Y.target.value),onKeyDown:Y=>Y.key==="Enter"&&ie(),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}),h.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),z?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:Y=>N(Y.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}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:oe,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{N(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(hx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const We=u==="announcements"&&p||u==="norms"&&y;return h.jsxs("div",{className:`flex-1 bg-surface-primary ${We?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.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:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:o.name}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[$e," online"]})]}),h.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),h.jsxs("button",{onClick:async()=>{if(o)try{const{files:Y}=await J.teams.getFilesMap(o.id),ee=o.members.filter(ke=>ke.type==="agent"),le={type:"team",name:gx(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:ee.map(ke=>({name:ke.name,roleName:ke.role,role:ke.agentRole??"worker",count:1,skills:[]}))}};await Ox.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:le,files:Y}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Y){d({title:"Hub",message:`Failed to publish: ${Y}`,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:[h.jsx("span",{children:"↑"})," Hub"]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),h.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Ap.map(Y=>h.jsxs("button",{onClick:()=>f(Y.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===Y.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Y.icon," ",a(Y.labelKey)]},Y.key))})]}),h.jsxs("div",{className:`${We?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:G?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Y=>{const ee=ne.find(Ce=>Ce.id===Y.id),le=lx[ee?.status??"offline"]??"bg-gray-500",ke=Y.type==="agent";return h.jsxs("div",{onClick:()=>ke&&n?.(Y.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ke&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(_s,{name:Y.name,avatarUrl:Y.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:Y.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${le}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ee?.status??"offline"}),Y.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Y.role," · ",Y.type]})]}),ke&&n&&h.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:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Y.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&h.jsx(Gl,{content:b,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:D,contentRef:I,saving:B,onSave:()=>K("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&h.jsx(Gl,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:B,onSave:()=>K("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),V?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:Pe,value:se,onChange:Y=>T(Y.target.value),onKeyDown:Y=>Y.key==="Enter"&&ie(),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}),h.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),z?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:Y=>N(Y.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}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:oe,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{N(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(hx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),c&&h.jsx(Wa,{alertOnly:!0,variant:c.variant??"primary",title:c.title,message:c.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function Gl({content:s,draft:e,setDraft:t,editing:i,setEditing:r,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:c,emptyText:d}){return i?h.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[h.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():r(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),r(!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:c}),o&&h.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):h.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),r(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),r(!0))},children:s.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(fM,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function hx({teamId:s,teamName:e,onDeleted:t}){const[i,r]=C.useState(!1),[n,a]=C.useState(!1),[o,l]=C.useState(!1),[c,d]=C.useState(!1);return h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[h.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),i?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{disabled:c,onClick:async()=>{d(!0);try{await J.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:c?"Deleting...":"Confirm Delete"}),h.jsx("button",{onClick:()=>r(!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"})]})]}):h.jsx("button",{onClick:()=>r(!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 Kl(s,e,t,i){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${i??""}`:e||"_direct"}class mr{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(e){return this.phase.get(e)??"idle"}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e){this.phase.set(e,"idle"),this.activeSession.delete(e)}updateMessages(e,t,i){const r=this.activeSession.get(e),n=!i||r===i||r===void 0,a=n?this.msgBuffers.get(e)??[]:this.sessionMsgCache.get(i)??[];let o=t(a);o.length>mr.MAX_MESSAGES&&(o=o.slice(-500));let l=!1;return n&&(this.msgBuffers.set(e,o),this.evictIfNeeded(e),l=this.currentConvKey===e),i&&i!==mr.NEW_CHAT_ID&&(this.sessionMsgCache.set(i,o),this.touchSessionCache(i)),{displayChanged:l,newMessages:l?o:void 0}}applyLoadResult(e,t,i){const r=this.isCacheFresher(t,i);r||(this.sessionMsgCache.set(t,i),this.touchSessionCache(t));const n=this.getPhase(e),a=this.activeSession.get(e);if(this.currentConvKey===e&&(this.loadingSession===t||a===t)&&n!=="streaming"){const l=r?this.sessionMsgCache.get(t):i;return this.msgBuffers.set(e,l),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:l}}return{displayChanged:!1}}appendActivity(e,t,i){const r=i??e,n=[...this.actBuffers.get(r)??[],t];if(this.actBuffers.set(r,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.activeSession.get(e);return!i||!a||a===i?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.activeSession.get(e)}setActiveSession(e,t){this.activeSession.set(e,t)}saveToCache(e,t){if(!t||t===mr.NEW_CHAT_ID)return;const i=this.msgBuffers.get(e);i&&i.length>0&&(this.sessionMsgCache.set(t,i),this.touchSessionCache(t))}restoreFromCache(e,t){const i=this.sessionMsgCache.get(t);if(i&&i.length>0)return this.msgBuffers.set(e,i),i;this.msgBuffers.delete(e)}isCacheFresher(e,t){const i=this.sessionMsgCache.get(e);if(!i||i.length===0)return!1;if(i.length>t.length)return!0;const r=i.reduce((l,c)=>l+c.text.length,0),n=t.reduce((l,c)=>l+c.text.length,0);if(r>n)return!0;const a=i.reduce((l,c)=>l+(c.segments?.length??0),0),o=t.reduce((l,c)=>l+(c.segments?.length??0),0);return a>o}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const i=this.streamingSessions.get(e)??new Set;i.add(t),this.streamingSessions.set(e,i)}removeStreamSession(e,t){if(t){const i=this.streamingSessions.get(e);i&&(i.delete(t),i.size===0&&this.streamingSessions.delete(e))}else this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}getMessages(e){return this.msgBuffers.get(e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.msgBuffers.delete(e)}evictIfNeeded(e){if(this.msgBuffers.size<=mr.MAX_CONVERSATIONS)return;const t=[...this.msgBuffers.keys()],i=t.filter(r=>r!==e&&r!==this.currentConvKey).slice(0,t.length-mr.MAX_CONVERSATIONS);for(const r of i)this.msgBuffers.delete(r),this.actBuffers.delete(r),this.sessionTabs.delete(r),this.activeSession.delete(r)}touchSessionCache(e){const t=this.sessionCacheOrder.indexOf(e);for(t!==-1&&this.sessionCacheOrder.splice(t,1),this.sessionCacheOrder.push(e);this.sessionCacheOrder.length>mr.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 St=mr.NEW_CHAT_ID;function pM(s){const e=C.useRef(new mr),[t,i]=C.useState(s??[]),[r,n]=C.useState(!1),[a,o]=C.useState([]),l=C.useRef(null);C.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const c=C.useCallback((p,x,y)=>{const _=e.current.updateMessages(p,x,y);_.displayChanged&&_.newMessages&&i(_.newMessages)},[]),d=C.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const k=e.current.getMessages(p);k&&e.current.currentConvKey===p&&i([...k])}))},[]),u=C.useCallback((p,x,y)=>{const _=e.current.appendActivity(p,x,y);_.displayChanged&&_.newActivities&&o(_.newActivities)},[]),f=C.useCallback(p=>e.current.getPhase(p),[]),g=C.useCallback(p=>e.current.beginLoad(p),[]),b=C.useCallback(p=>e.current.beginStream(p),[]),v=C.useCallback(p=>e.current.endStream(p),[]),m=C.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=C.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const _=await y(),k=e.current.applyLoadResult(x,p,_.messages);return k.displayChanged&&k.newMessages&&i(k.newMessages),{count:_.messages.length,hasMore:_.hasMore,oldestCursor:_.oldestCursor}}catch{return e.current.currentConvKey===x&&e.current.getPhase(x)!=="streaming"&&(i([]),e.current.completeLoad(x)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:i,sending:r,setSending:n,activities:a,setActivities:o,get msgBuffers(){return e.current.msgBuffers},get sessionMsgCache(){return e.current.sessionMsgCache},get activeSessionBuffer(){return e.current.activeSession},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(p){e.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(p){e.current.loadingSession=p}}},updateConvMsgs:c,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:g,beginStream:b,endStream:v,resetConv:m,loadAndDisplay:O,incrementSending:p=>e.current.incrementSend(p),decrementSending:p=>e.current.decrementSend(p),resetSending:p=>e.current.resetSend(p),isSendingFor:p=>e.current.isSending(p),setStreamSession:(p,x)=>e.current.addStreamSession(p,x),clearStreamSession:(p,x)=>e.current.removeStreamSession(p,x),getStreamSession:p=>e.current.getStreamSessions(p),saveSessionToCache:(p,x)=>e.current.saveToCache(p,x),restoreSessionFromCache:(p,x)=>{const y=e.current.restoreFromCache(p,x);return i(y??[]),y},isSessionCacheFresherThanDb:(p,x)=>e.current.isCacheFresher(p,x)}}function mM({value:s,onSelect:e,disabled:t}){const{t:i}=Pt("team"),[r,n]=C.useState(!1),[a,o]=C.useState(!0),[l,c]=C.useState(""),[d,u]=C.useState(!1),[f,g]=C.useState([]),[b,v]=C.useState(null),m=C.useRef(null),O=C.useCallback(async()=>{u(!0);try{const w=await fetch("/api/settings/llm",{credentials:"include"});if(!w.ok)throw new Error(`HTTP ${w.status}`);const S=await w.json(),Q=S.providers?.markus;if(Q?.configured&&Q.enabled!==!1&&(!Q.models||Q.models.length===0))try{const j=await fetch("/api/models/live/markus",{credentials:"include"});if(j.ok){const B=await j.json();B.models?.length&&(Q.models=B.models)}}catch{}const I=[];for(const[j,B]of Object.entries(S.providers??{})){if(!B.configured||B.enabled===!1)continue;const F=(B.models??[]).map(V=>({id:V.id,name:V.name}));F.length!==0&&I.push({provider:j,displayName:B.displayName??j,models:F})}I.sort((j,B)=>j.displayName.localeCompare(B.displayName)),g(I);const D=j=>!j?.provider||!j.model?!1:!!I.find(F=>F.provider===j.provider)?.models.some(F=>F.id===j.model);let $=null;if(S.routingDefaultModel?.provider&&S.routingDefaultModel?.model)$={provider:S.routingDefaultModel.provider,model:S.routingDefaultModel.model};else if(S.defaultProvider){const j=S.providers?.[S.defaultProvider];j?.model&&($={provider:S.defaultProvider,model:j.model})}if($&&!D($)){const j=I.find(F=>F.provider==="markus"),B=j?.models[0]?{provider:"markus",model:j.models[0].id}:I[0]?.models[0]?{provider:I[0].provider,model:I[0].models[0].id}:null;B?($=B,J.settings.updateRouting({defaultProvider:B.provider,routingDefaultModel:B}).catch(()=>{})):$=null}v($)}catch{g([])}finally{u(!1)}},[]);C.useEffect(()=>{O()},[O]),C.useEffect(()=>{r&&(o(!0),c(""),O())},[r,O]),C.useEffect(()=>{if(!r)return;const w=S=>{m.current?.contains(S.target)||n(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[r]);const p=C.useMemo(()=>{const w=l.trim().toLowerCase();return f.map(S=>({...S,models:w?S.models.filter(Q=>Q.id.toLowerCase().includes(w)||(Q.name?.toLowerCase().includes(w)??!1)||S.displayName.toLowerCase().includes(w)||S.provider.toLowerCase().includes(w)):S.models})).filter(S=>S.models.length>0)},[f,l]),x=C.useCallback(w=>!w?.provider||!w.model?!1:f.length===0?!0:!!f.find(Q=>Q.provider===w.provider)?.models.some(Q=>Q.id===w.model),[f]);C.useEffect(()=>{if(!s||f.length===0||x(s))return;const w=b&&x(b)?b:(()=>{const S=f.find(Q=>Q.provider==="markus");return S?.models[0]?{provider:"markus",model:S.models[0].id}:f[0]?.models[0]?{provider:f[0].provider,model:f[0].models[0].id}:null})();w&&e(w,!1)},[s,f,b,x,e]);const y=s&&x(s)?s:b,k=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||i("chatModel.title",{defaultValue:"Model"});return h.jsxs("div",{ref:m,className:"relative shrink-0",children:[h.jsxs("button",{type:"button",disabled:t,onClick:()=>n(w=>!w),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:y?`${y.provider}: ${y.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[h.jsx("span",{className:"truncate",children:k}),h.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r&&h.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:[h.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[h.jsx("input",{autoFocus:!0,value:l,onChange:w=>c(w.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"}),h.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[h.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),h.jsx("button",{type:"button",role:"switch","aria-checked":a,onClick:()=>o(w=>!w),className:`relative w-9 h-5 rounded-full transition-colors ${a?"bg-brand-600":"bg-fg-tertiary/30"}`,children:h.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${a?"translate-x-4":""}`})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[d&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!d&&p.length===0&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!d&&p.map(w=>h.jsxs("div",{className:"mb-1",children:[h.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:w.displayName}),w.models.slice(0,80).map(S=>{const Q=y?.provider===w.provider&&y?.model===S.id;return h.jsxs("button",{type:"button",onClick:()=>{e({provider:w.provider,model:S.id},a),a&&v({provider:w.provider,model:S.id}),n(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[h.jsx("span",{className:"truncate flex-1",children:S.id}),Q&&h.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:h.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${w.provider}:${S.id}`)})]},w.provider))]})]})]})}async function gM(s,e,t){s&&!s.startsWith("new_")&&await J.sessions.setModelOverride(s,e),t&&await J.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const dx="markus_team_sidebars_c";function OM(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}const xM=["chat","overview","files","tools","memory","deliverables"],vM=["chat","overview","announcements","norms","settings"];function bM(s,e){if(s==="chat")return e("page.chatTitle");if(Rp.find(r=>r.key===s))return e(`agent:tabs.${s}`);const i=Ap.find(r=>r.key===s);return i?e(i.labelKey):s}function yM(s){if(s==="chat")return"💬";const e=Rp.find(i=>i.key===s);if(e)return e.icon;const t=Ap.find(i=>i.key===s);return t?t.icon:""}function cr(s){return s!=="chat"}const yf=new Set;function SM(){return window.location.hash}function _M(s){return yf.add(s),()=>{yf.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>yf.forEach(s=>s()));function NM({initialAgentId:s,authUser:e,previewMode:t,previewData:i}={}){const{t:r,i18n:n}=Pt(["team","common"]),a=C.useMemo(()=>({today:r("page.dateToday"),yesterday:r("page.dateYesterday")}),[r]),o=_f(Ht.TEAM),[l,c]=C.useState(i?.agents??[]),[d,u]=C.useState(i?.humans??[]),[f,g]=C.useState(!i),b=Sf(),v=C.useSyncExternalStore(_M,SM),m=b&&(v.startsWith(`#${Ht.TEAM}/`)||v.startsWith("#chat/")),O=b&&v.match(/^#team\/t\/(.+)$/),p=b?O?"team":m?"chat":"roster":"roster",x=O?O[1]:null,y=C.useRef(Ht.TEAM),_=C.useCallback(()=>{y.current=window.location.hash.slice(1)||Ht.TEAM,window.location.hash=`${Ht.TEAM}/d`},[]),k=C.useCallback(P=>{window.location.hash=`${Ht.TEAM}/t/${P}`},[]);C.useEffect(()=>{if(!b)return;const P=()=>{cr(Q.current)&&S("chat")};return window.addEventListener("popstate",P),()=>window.removeEventListener("popstate",P)},[b]);const[w,S]=C.useState("chat"),Q=C.useRef("chat");Q.current=w;const I=_m({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[D,$]=C.useState(()=>{try{return localStorage.getItem(dx)==="1"}catch{return!1}}),j=C.useCallback(P=>{$(P);try{localStorage.setItem(dx,P?"1":"0")}catch{}},[]),B=wf(),F=B?.leftCollapsed??!1,V=B?.rightPanel??null,Z=B?.rightPanelTabs??[],se=B?.activeRightPanelTabId??null,T=B?.rightPanelFullscreen??!1,A=V?"2xl:pr-8":"2xl:pr-[280px]",N=B?.setHostAvailable,z=B?.collapseRightPanelOnly??B?.toggleRightPanel,U=B?.openRightPanel,ne=400,Se=320,Pe=6,[X,M]=C.useState(typeof window<"u"?window.innerWidth:1440),[K,ie]=C.useState("auto"),oe=C.useRef(F);C.useEffect(()=>{oe.current!==F&&(oe.current=F,$(F))},[F]);const G=B?.keyboardPane??"content",$e=C.useRef(!1),Ie=C.useRef(G);C.useEffect(()=>{if(t||b||!o)return;const P=Ie.current;Ie.current=G,(G==="l1"||G==="l2")&&P!==G&&D&&($(!1),B?.setLeftCollapsed(!1))},[G,t,b,o,D,B]),C.useEffect(()=>{if(t||b||!o)return;const P=E=>{const R=B?.keyboardPane??"content";if(R==="l0"||R==="l1"||R==="l2"||E.metaKey||E.ctrlKey||E.altKey)return;if(E.target instanceof HTMLElement){const H=E.target.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||E.target.isContentEditable||E.target.closest(".xterm"))return}const q=E.key.length===1?E.key.toLowerCase():E.key;q!=="h"&&q!=="ArrowLeft"||(E.preventDefault(),D&&(j(!1),B?.setLeftCollapsed(!1)),B?.setKeyboardPane($e.current?"l2":"l1"))};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[t,b,o,B,D,j]),C.useEffect(()=>{if(N)return N(o&&!b),()=>N(!1)},[o,b,N]),C.useEffect(()=>t||b||!o?void 0:gt.on("ui:right_panel",E=>{const R=E.payload;if(R.action==="collapse"){z?.();return}if(R.action!=="open"||!R.panel||!U)return;const q=R.panel;if(q.kind==="url"&&q.url){const H=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;U({kind:"url",url:q.url,title:q.title||q.url,browserId:H});return}if(q.kind==="file"&&q.path){U({kind:"file",path:q.path,title:q.title});return}if(q.kind==="terminal"){const H=q.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;U({kind:"terminal",terminalId:H,title:q.title||"Terminal",cwd:q.cwd});return}q.kind==="deliverable"&&q.deliverableId&&J.deliverables.get(q.deliverableId).then(H=>{H.deliverable&&U({kind:"deliverable",deliverable:H.deliverable})}).catch(()=>{})}),[t,b,o,z,U]);const We=C.useCallback(P=>{const E=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Ai(R=>[...R,{id:E,...P}]),requestAnimationFrame(()=>sr.current?.focus())},[]),[Y,ee]=C.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),le=_m({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),ke=C.useRef(null),[Ce,dt]=C.useState(!1),[ht,yt]=C.useState(!1),ss=C.useCallback(()=>{Ce?yt(P=>!P):ee(P=>{const E=!P;try{localStorage.setItem("markus_team_panel_visible",String(E))}catch{}return E})},[Ce]);C.useEffect(()=>{if(b)return;const P=ke.current;if(!P)return;const E=new ResizeObserver(([R])=>{if(!R)return;const q=R.contentRect.width;if(M(q),!t){const H=q-I.width-le.width;dt(H<400)}});return E.observe(P),()=>E.disconnect()},[b,t,I.width,le.width]);const Lt=Y&&!Ce&&!ht,zs=D?0:I.width+Pe+(Lt?le.width+Pe:0),vs=Math.max(0,X-zs-Pe-8),bs=Math.min(ne,Math.floor(vs*.4)),si=Math.max(0,vs-bs),Zs=Math.min(Math.round(vs/2),si),xt=Math.max(0,Math.min(K==="auto"?Zs:K,si)),$i=C.useRef(!1);C.useEffect(()=>{const P=(B?.rightPanel??null)!==null;P&&!$i.current&&($(!0),ie("auto")),$i.current=P},[B?.rightPanel]);const ji=C.useRef(xt);ji.current=xt;const Ga=C.useRef(si);Ga.current=si;const gh=C.useCallback(P=>{P.preventDefault();const E=P.clientX,R=ji.current,q=fe=>{const me=R+(E-fe.clientX),be=Ga.current,te=Math.min(Se,be);ie(Math.max(te,Math.min(be,me)))},H=()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",H),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",q),document.addEventListener("mouseup",H),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);C.useEffect(()=>{if(!ht)return;const P=E=>{E.target.closest("[data-l2-floating]")||yt(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[ht]);const[Hr,Ji]=C.useState(null),[Ka,Po]=C.useState(),[To,Gr]=C.useState(),[ii,xi]=C.useState(!1),[Ja,Qo]=C.useState(""),[An,$o]=C.useState(!1),[Ei,Kr]=C.useState(""),Mn=C.useRef(null),ri=C.useRef(null),Tr=C.useCallback((P,E)=>{Po(P),Gr(E),b?(S("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):S(P??"overview")},[b]),Jr=[{id:"chat"},{id:"profile"}],jo=C.useCallback(P=>{P==="profile"?Tr():cr(Q.current)?history.back():S("chat")},[Tr]),ni=mx(Jr,w,jo),Ts=C.useCallback((P,E)=>{ut("direct"),is(P),b&&_(),Tr(E?.tab,E?.highlightMailboxId),Ji(null)},[b,_,Tr]),vi=C.useCallback((P,E)=>{const R=l.find(q=>q.name.toLowerCase()===P.toLowerCase());if(R){const q=E.target.getBoundingClientRect();Ji({agentId:R.id,top:q.bottom,left:q.left})}},[l]),Eo=C.useMemo(()=>l.map(P=>P.name),[l]),[ce,ut]=C.useState(()=>i?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,is]=C.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[lt,As]=C.useState(()=>i?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Nt,en]=C.useState(""),Ms=500,tn=C.useRef(new Set),Ln=P=>{if(tn.current.add(P),tn.current.size>Ms){const E=Math.floor(Ms*.2),R=tn.current.values();for(let q=0;q<E;q++){const H=R.next().value;H&&tn.current.delete(H)}}},Oh=C.useMemo(()=>{if(i?.channelMessages){const P=i.activeChannel??"custom:general";return i.channelMessages.filter(E=>E.channel===P).map(E=>xn(E))}},[]),{manager:el,messages:At,setMessages:Qs,sending:Vs,setSending:rs,activities:xh,setActivities:bi,msgBuffers:hs,sessionMsgCache:sn,activeSessionBuffer:ds,actBuffers:oi,sessionTabsBuffer:tl,currentConvKeyRef:Ve,updateConvMsgs:rt,updateConvMsgsRaf:er,appendConvActivity:rn,beginLoad:sl,beginStream:nn,endStream:ai,resetConv:Ri,loadAndDisplay:W,incrementSending:he,decrementSending:ue,resetSending:Re,isSendingFor:Fe,setStreamSession:tt,clearStreamSession:vt,getStreamSession:mt,saveSessionToCache:Ye,restoreSessionFromCache:Yt}=pM(Oh),[Dt,Ut]=C.useState(""),[Ls,Zt]=C.useState(null),[us,Ai]=C.useState([]),[Nn,Rt]=C.useState([]),ns=C.useRef(null),[vh,il]=C.useState(!!i?.streamLastMessage),on=C.useRef(null),H1=400;C.useEffect(()=>(Vs?(on.current&&(clearTimeout(on.current),on.current=null),il(!0)):vh&&(on.current=setTimeout(()=>{il(!1),on.current=null},H1)),()=>{on.current&&clearTimeout(on.current)}),[Vs]);const Mp=Vs||vh||(()=>{for(let P=At.length-1;P>=Math.max(0,At.length-8);P--){const E=At[P];if(E.isStreaming&&!E.isStopped)return!0}return!1})(),bh=C.useRef({fullText:"",timers:[]});C.useEffect(()=>{if(!t||!i?.streamLastMessage||At.length===0)return;const P=At[At.length-1];if(!P||P.sender!=="agent")return;const E=P.text;bh.current.fullText=E;const R=bh.current.timers;function q(){let fe=0;Qs(be=>be.map((te,de)=>de===be.length-1?{...te,text:""}:te)),il(!0);const me=setInterval(()=>{if(fe+=1+Math.floor(Math.random()*2),fe>=E.length){clearInterval(me),Qs(de=>de.map((st,Ue)=>Ue===de.length-1?{...st,text:E}:st));const be=setTimeout(()=>il(!1),800);R.push(be);const te=setTimeout(q,6e3);R.push(te)}else Qs(be=>be.map((te,de)=>de===be.length-1?{...te,text:E.slice(0,fe)}:te))},30);R.push(me)}const H=setTimeout(q,1500);return R.push(H),()=>{R.forEach(fe=>clearTimeout(fe)),bh.current.timers=[]}},[]);const Qr=C.useRef(0),[Lp,Mi]=C.useState(!1),[yh,Np]=C.useState(!1),[Dp,tr]=C.useState(!1),[Fs,Sh]=C.useState([]),[Ip,Bp]=C.useState(null),_h=C.useRef(null),sr=C.useRef(null),[rl,nl]=C.useState(null),$r=C.useRef(null),wh=C.useRef(!1),Ro=C.useCallback(()=>{const P=sr.current;if(!P)return;const E=wh.current,R=E?36:52,q=E?160:120;P.style.height="auto";const H=Math.max(R,Math.min(P.scrollHeight,q));P.style.height=`${H}px`,P.style.overflowY=H>=q?"auto":"hidden"},[]);C.useEffect(()=>{const P=requestAnimationFrame(()=>Ro());return()=>cancelAnimationFrame(P)},[Dt,Fs.length,Ro]);const kh=P=>{try{const E=localStorage.getItem(`markus_closed_tabs_${P}`);return E?new Set(JSON.parse(E)):new Set}catch{return new Set}},G1=(P,E)=>{const R=kh(P);R.add(E);try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...R]))}catch{}},K1=(P,E)=>{const R=kh(P);if(R.delete(E))try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...R]))}catch{}},J1=P=>{try{return localStorage.getItem(`markus_active_session_${P}`)}catch{return null}},ol=(P,E)=>{if(P)try{E&&E!==St?localStorage.setItem(`markus_active_session_${P}`,E):localStorage.removeItem(`markus_active_session_${P}`)}catch{}},[Ch,an]=C.useState([]),[it,Li]=C.useState(null),[ln,cn]=C.useState(!1),[Wp,Ph]=C.useState([]),[Ao,Th]=C.useState(null),[eS,Xp]=C.useState(null),[al,Qh]=C.useState([]),[Dn,$h]=C.useState(null),[tS,qp]=C.useState(null),[zp,jh]=C.useState([]),[Mo,sS]=C.useState([]),Ns=P=>{sS(E=>{const R=typeof P=="function"?P(E):P,q=new Set;return R.filter(H=>q.has(H.id)?!1:(q.add(H.id),!0))})},ll=C.useRef(null),Eh=C.useRef(null),yi=C.useRef(null),[ys,Lo]=C.useState(i?.groupChats??[]),Rh=C.useRef(ys);Rh.current=ys;const Zp=C.useRef(null),[No,fs]=C.useState(!1),[hn,Do]=C.useState(!1),[Vp,In]=C.useState(""),[Ah,jr]=C.useState([]),[Fp,Yp]=C.useState(!1),Mh=C.useRef(void 0),[Si,Up]=C.useState(i?.teams??[]),[iS,rS]=C.useState([]),[cl,Hp]=C.useState([]),[nS,oS]=C.useState(null),[wM,kM]=C.useState(!1),[CM,PM]=C.useState(""),[Gp,Io]=C.useState(!1),[Kp,aS]=C.useState(""),[Bo,Bn]=C.useState(0),[lS,cS]=C.useState([]),Jp=C.useRef(!1),hS=C.useCallback(()=>{Jp.current||(Jp.current=!0,(async()=>{const P=[];try{const[E,R,q,H,fe]=await Promise.all([J.projects.list().catch(()=>({projects:[]})),J.requirements.list().catch(()=>({requirements:[]})),J.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),J.deliverables.search({limit:100}).catch(()=>({results:[]})),J.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const me of E.projects)P.push({id:me.id,name:me.name,entityType:"project",role:me.status});for(const me of R.requirements)P.push({id:me.id,name:me.title,entityType:"requirement",role:me.priority});for(const me of q.tasks)P.push({id:me.id,name:me.title,entityType:"task",role:me.status});for(const me of H.results)P.push({id:me.id,name:me.title,entityType:"deliverable",role:me.type});for(const me of fe.teams)try{const be=await J.workflows.list(me.id);for(const te of be.workflows)P.push({id:te.name,name:te.displayName||te.name,entityType:"workflow",role:`v${te.version}`})}catch{}}catch{}cS(P)})())},[]),Vt=ce==="channel"?ys.find(P=>P.channelKey===lt)?.teamId:void 0,dS=C.useRef(null),Wn=C.useRef(null),Ss=C.useRef(null),em=C.useRef(void 0),hl=C.useRef(!1),ir=C.useRef(!0),tm=C.useRef(void 0);C.useEffect(()=>{if(!ln)return;const P=E=>{Eh.current&&!Eh.current.contains(E.target)&&ll.current&&!ll.current.contains(E.target)&&cn(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[ln]);const dl=(P,E)=>{if(!E||P===E)return`notes:${P}`;const[R,q]=[P,E].sort();return`dm:${R}:${q}`};C.useEffect(()=>{localStorage.setItem("markus_chat_mode",ce)},[ce]),C.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),C.useEffect(()=>{localStorage.setItem("markus_chat_channel",lt)},[lt]);const{counts:Lh,sessionAgentMap:Wo,markRead:Xo,setActiveKey:uS,clearActiveKey:fS}=a_({enabled:!t}),ul=C.useMemo(()=>{const P={};for(const[E,R]of Object.entries(Lh))E.startsWith("channel:")&&(P[E.slice(8)]=R);return P},[Lh]),Nh=l_(Wo,Lh);C.useEffect(()=>{let P=0;for(const E of Nh.values())P+=E;for(const E of Object.values(ul))P+=E;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:P}}))},[Nh,ul]);const fl=Nh,pS=C.useCallback(async P=>{for(const[E,R]of Object.entries(Wo))R===P&&Xo(`session:${E}`)},[Wo,Xo]);C.useEffect(()=>{if(t||!((!b||p==="chat")&&w==="chat"))return;if(ce==="direct"&&ge&&pS(ge),ce==="channel"&<)Xo(`channel:${lt}`);else if(ce==="direct"&&it)Xo(`session:${it}`);else if(ce==="dm"&&Nt){const R=`dm:${[e?.id,Nt].sort().join(":")}`;Xo(`channel:${R}`)}const E=[];if(ce==="direct"&&it){E.push(`session:${it}`);for(const[R,q]of Object.entries(Wo))q===ge&&E.push(`session:${R}`)}else ce==="channel"&<?E.push(`channel:${lt}`):ce==="dm"&&Nt&&e?.id&&E.push(`channel:dm:${[e.id,Nt].sort().join(":")}`);for(const R of E)uS(R);return()=>{for(const R of E)fS(R)}},[t,ce,lt,it,Nt,ge,p,w,Wo]);const li=C.useCallback(()=>J.agents.list().then(P=>c(P.agents)).catch(()=>{}),[]),Ys=C.useCallback(()=>J.teams.list().then(P=>Up(P.teams)).catch(()=>{}),[]),Xn=C.useCallback(()=>J.groupChats.list().then(P=>Lo(P.chats)).catch(()=>{}),[]),mS=C.useMemo(()=>ed(li,3e3),[li]),pl=C.useMemo(()=>ed(Ys,5e3),[Ys]),Dh=C.useMemo(()=>ed(Xn,3e3),[Xn]),qo=C.useCallback(()=>{J.users.list(e?.orgId).then(P=>u(P.users)).catch(()=>{})},[e?.orgId]);C.useEffect(()=>{t||(Promise.all([li(),Ys()]).finally(()=>g(!1)),qo(),J.tasks.list().then(P=>Hp(P.tasks)).catch(()=>{}),J.externalAgents.list().then(P=>rS(P.agents)).catch(()=>{}),Xn())},[t,qo]),C.useEffect(()=>{if(!(!t||!i)&&(c(i.agents??[]),u(i.humans??[]),Up(i.teams??[]),Lo(i.groupChats??[]),i.channelMessages)){const P=i.activeChannel??"custom:general";Qs(i.channelMessages.filter(E=>E.channel===P).map(E=>xn(E)))}},[t,i]),C.useEffect(()=>{if(t||!o)return;li(),Ys();const P=setInterval(li,3e4),E=setInterval(Ys,6e4),R=gt.on("agent:update",()=>{mS(),pl()}),q=gt.on("team:update",()=>{pl(),Dh()}),H=gt.on("agent:removed",pl),fe=gt.on("chat:group_created",()=>{Xn(),Ys(),li()}),me=gt.on("chat:group_updated",Dh),be=gt.on("chat:group_deleted",()=>{Dh(),pl()}),te=gt.on("task:update",st=>{const Ue=st?.payload;Ue?.taskId&&Hp(Xe=>Xe.map(Qe=>Qe.id===Ue.taskId?{...Qe,status:Ue.status??Qe.status}:Qe))}),de=()=>{li(),Ys(),qo()};return window.addEventListener("markus:data-changed",de),()=>{clearInterval(P),clearInterval(E),R(),q(),H(),fe(),me(),be(),te(),window.removeEventListener("markus:data-changed",de)}},[t,o,qo]),C.useEffect(()=>{if(t)return;const P=be=>{const te=be.detail;if(S_(te.page)===Ht.TEAM){if(te.params?.agentId){if(te.params.profileTab)Ts(te.params.agentId,{tab:te.params.profileTab});else if(ut("direct"),is(te.params.agentId),S("chat"),b&&_(),te.params.sessionId){const de=te.params.sessionId;setTimeout(async()=>{try{const{sessions:st}=await J.sessions.listByAgent(te.params.agentId,20),Ue=st.find(Xe=>Xe.id===de);Ue&&bl(Ue)}catch{}},300)}}if(te.params?.selectAgent&&(ut("direct"),is(te.params.selectAgent),S("chat"),b&&_()),te.params?.prefillMessage){const de=te.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),te.params?.autoSend==="true"?setTimeout(()=>em.current?.(de),300):(Ut(de),setTimeout(()=>{const st=sr.current;st&&(st.focus(),st.setSelectionRange(st.value.length,st.value.length))},100))}if(te.params?.dm&&(ut("dm"),en(te.params.dm),S("chat"),b&&_()),te.params?.channel&&(ut("channel"),As(te.params.channel),S("chat"),b&&_()),te.params?.selectTeam){const de=te.params.selectTeam;if(b)k(de);else{const st=Rh.current.find(Ue=>Ue.type==="team"&&Ue.teamId===de);ut("channel"),As(st?.channelKey??`group:${de}`),S("chat"),fs(!1),ee(!0)}}te.params?.openHire}},E=localStorage.getItem("markus_nav_agentId");if(E){localStorage.removeItem("markus_nav_agentId");const be=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),ut("direct"),is(E),be?Ts(E,{tab:be}):(S("chat"),b&&_())}const R=localStorage.getItem("markus_nav_dm");R&&(localStorage.removeItem("markus_nav_dm"),ut("dm"),en(R),S("chat"),b&&_());const q=localStorage.getItem("markus_nav_channel");q&&(localStorage.removeItem("markus_nav_channel"),ut("channel"),As(q),S("chat"),b&&_());const H=localStorage.getItem("markus_nav_prefillMessage");H&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),Ut(H),setTimeout(()=>{const be=sr.current;be&&(be.focus(),be.setSelectionRange(be.value.length,be.value.length))},150));const fe=localStorage.getItem("markus_nav_selectAgent");fe&&(localStorage.removeItem("markus_nav_selectAgent"),ut("direct"),is(fe),S("chat"),b&&_());const me=localStorage.getItem("markus_nav_selectTeam");if(me)if(localStorage.removeItem("markus_nav_selectTeam"),b)k(me);else{const be=Rh.current.find(te=>te.type==="team"&&te.teamId===me);ut("channel"),As(be?.channelKey??`group:${me}`),S("chat"),fs(!1),ee(!0)}return window.addEventListener("markus:navigate",P),()=>window.removeEventListener("markus:navigate",P)},[t]),C.useEffect(()=>{const P=Zp.current;if(!P)return;const E=ys.find(R=>R.type==="team"&&R.teamId===P);Zp.current=null,ut("channel"),As(E?.channelKey??`group:${P}`),S("chat"),fs(!1),ee(!0)},[ys,Si]),C.useEffect(()=>{if(t&&i?.chatMode==="channel"||l.length===0||ge&&l.some(E=>E.id===ge))return;const P=l.find(E=>!E.teamId&&E.role?.toLowerCase()==="secretary")??l.find(E=>E.role?.toLowerCase()==="secretary")??l.find(E=>E.name?.toLowerCase().includes("secretary"));P?(ut("direct"),is(P.id),S("chat")):l.length>0&&(ut("direct"),is(l[0].id),S("chat"))},[l,ge]);const qn=C.useRef(!1),Ni=C.useRef(!1),ml=C.useRef(!1),gl=C.useRef(0),zn=C.useRef(0),[gS,rr]=C.useState(!1),Er=C.useRef(0),[sm,dn]=C.useState(0),nr=C.useCallback(()=>{Ni.current=!1,ml.current=!1,ir.current=!0},[]),Ih=C.useCallback(()=>{Ni.current=!0,ir.current=!1,zn.current+=1,qn.current=!1,rr(!0)},[]),un=C.useCallback(P=>{const E=Wn.current;if(!E)return;const R=E.scrollHeight-E.scrollTop-E.clientHeight,q=R<160,H=R<48,fe=gl.current,me=E.scrollTop<fe-2;if(gl.current=E.scrollTop,me&&R>20){ml.current=!0,Ih();return}if(ml.current){H?(nr(),rr(!1),Er.current=0,dn(0)):Ih();return}if(q&&!Ni.current){nr(),rr(!1),Er.current=0,dn(0);return}P?.fromProgrammatic||qn.current||!Ni.current&&ir.current||Ni.current&&(ir.current=!1,rr(!0))},[Ih,nr]);C.useEffect(()=>{const P=Wn.current;if(!P)return;const E=()=>{ml.current=!0},R=()=>{un({fromProgrammatic:qn.current})};P.addEventListener("wheel",E,{passive:!0}),P.addEventListener("touchmove",E,{passive:!0}),P.addEventListener("scroll",R,{passive:!0});const q=typeof ResizeObserver<"u"?new ResizeObserver(()=>un()):null;return q?.observe(P),gl.current=P.scrollTop,un(),()=>{P.removeEventListener("wheel",E),P.removeEventListener("touchmove",E),P.removeEventListener("scroll",R),q?.disconnect()}},[p,un]);const Bh=C.useMemo(()=>new Set(zp),[zp]),os=C.useMemo(()=>{const P=ce==="channel"?At:At.filter(E=>!E.isActivityLog);return Bh.size===0?P:P.filter(E=>!(E.isNotification&&Bh.has(E.id)))},[At,ce,Bh]);C.useEffect(()=>{wh.current=w==="chat"&&os.length>0,Ro()},[w,os.length,Ro]);const or=N_({count:os.length,getScrollElement:()=>Wn.current,getItemKey:P=>os[P]?.id??P,estimateSize:P=>{const E=os[P];return E?E.segments&&E.segments.length>0?300:E.text.length>500?200:120:120},overscan:8});or.shouldAdjustScrollPositionOnItemSizeChange=(P,E,R)=>wm()?!1:P.start<(R.scrollOffset??0);const Zn=C.useCallback((P="instant")=>{if(!ir.current||Ni.current)return;const E=++zn.current;qn.current=!0;const R=()=>E===zn.current&&ir.current&&!Ni.current,q=()=>{if(E!==zn.current)return;if(qn.current=!1,!R()){un();return}const H=Wn.current;H&&(gl.current=H.scrollTop,H.scrollHeight-H.scrollTop-H.clientHeight<160&&!Ni.current&&(nr(),rr(!1),Er.current=0,dn(0))),requestAnimationFrame(()=>{E===zn.current&&un({fromProgrammatic:!0})})};if(os.length>0)or.scrollToIndex(os.length-1,{align:"end",behavior:P}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R()){E===zn.current&&(qn.current=!1);return}or.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(q)})});else{const H=Wn.current;H&&H.scrollTo({top:H.scrollHeight,behavior:P}),requestAnimationFrame(q)}},[os.length,or,un,nr]),im=C.useRef(o);C.useEffect(()=>{im.current=o},[o]),C.useLayoutEffect(()=>{if(hl.current){hl.current=!1;const P=xl.current;P>0&&(xl.current=0,or.scrollToIndex(P,{align:"start",behavior:"instant"}));return}im.current&&(!ir.current||Ni.current||wm()||Zn())},[At,Zn,or]);const rm=C.useRef(w);C.useEffect(()=>{const P=rm.current!=="chat";if(rm.current=w,w==="chat"&&P&&ir.current&&!Ni.current){const E=[],R=requestAnimationFrame(()=>Zn("instant"));for(const q of[60,160,320])E.push(setTimeout(()=>Zn("instant"),q));return()=>{cancelAnimationFrame(R);for(const q of E)clearTimeout(q)}}},[w,Vs,Zn]);const nm=C.useCallback(async(P,E)=>{const R=E??`ch:${P}`;Ve.current===R&&tr(!0);try{const q=await J.channels.getMessages(P,50),H=q.messages.map(fe=>xn(fe,e?.id));hs.set(R,H),Ve.current===R&&(Qs(H),Mi(q.hasMore),yi.current=q.messages[0]?new Date(q.messages[0].createdAt).toISOString():null)}catch{Ve.current===R&&(Qs([]),Mi(!1))}finally{Ve.current===R&&tr(!1)}},[]),Wh=C.useCallback(async(P,E)=>{const R=Ve.current===E&&(hs.get(E)?.length??0)===0;R&&tr(!0);try{const{count:q,hasMore:H,oldestCursor:fe}=await W(P,E,async()=>{const me=await J.sessions.getMessages(P,50);return{messages:c_(me.messages.map(td).filter(te=>te.sender!=="agent"||te.text||te.segments&&te.segments.length>0||te.isStreaming)),hasMore:me.hasMore,oldestCursor:me.messages[0]?new Date(me.messages[0].createdAt).toISOString():null}});return Mi(H),yi.current=fe,q}finally{R&&Ve.current===E&&tr(!1)}},[W,hs]),om=C.useRef(new Map),fn=C.useCallback(async(P,E,R)=>{if(!P||!E||E===St)return;let q=null;try{if(Ss.current&&!Ss.current.signal.aborted&&mt(R)?.has(E)){nn(R),Ve.current===R&&rs(!0);return}const H=`${P}:${E}`,fe=om.current.get(H)??0;if(Date.now()-fe<1500)return;const me=await J.sessions.streamStatus(P,E),te=[...hs.get(R)??[]].reverse().find(Oe=>Oe.sender==="agent"),de=me.status==="streaming",st=!!me.active&&(me.status==="done"||me.status==="error")&&!!te?.isStreaming;if(!de&&!st)return;om.current.set(H,Date.now()),$r.current?.abort(),q=new AbortController,$r.current=q,nn(R),rs(!0),tt(R,E);let Ue=te?.id;if(!te||te.isError)Ue=`reattach_${Date.now()}`,rt(R,Oe=>[...Oe,{id:Ue,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],E);else{const Oe=(te.segments??[]).filter(Be=>Be.type==="tool").map(Be=>Be.status==="stopped"||Be.status==="running"?{...Be,status:"running"}:Be);rt(R,Be=>Be.map(we=>we.id===te.id?{...we,text:"",isStreaming:!0,isStopped:!1,segments:Oe,committedSegments:void 0}:we),E)}let Xe=!1;const Qe=Oe=>{Ve.current===R&&(Qr.current=Date.now(),er(R,Be=>{const we=[...Be],Le=Ue?we.findIndex(pe=>pe.id===Ue):-1,Me=Le>=0?Le:we.map((pe,xe)=>({m:pe,j:xe})).reverse().find(pe=>pe.m.sender==="agent")?.j??-1;if(Me<0)return Be;const De=we[Me].segments??[],et=De[De.length-1],Ct=et?.type==="text"?et.thinking??"":"";let Xt="",$s="",ae=Oe;for(;ae.length>0;)if(Xe){const pe=ae.indexOf("</think>");pe>=0?(Xt+=ae.slice(0,pe),ae=ae.slice(pe+8),Xe=!1):(Xt+=ae,ae="")}else{const pe=ae.indexOf("<think>");pe>=0?($s+=ae.slice(0,pe),ae=ae.slice(pe+7),Xe=!0):($s+=ae,ae="")}const Ze=Ct+Xt||void 0,ye=et?.type==="text"?[...De.slice(0,-1),{type:"text",content:et.content+$s,thinking:Ze,createdAt:et.createdAt}]:[...De,{type:"text",content:$s,thinking:Ze,createdAt:new Date().toISOString()}];return we[Me]={...we[Me],text:(we[Me].text??"")+$s,segments:ye,isStreaming:!0},we},E))},ct=Oe=>{if(Ve.current===R&&(Qr.current=Date.now(),Oe.phase!=="heartbeat")){if((Oe.phase==="start"||Oe.phase==="end")&&rn(R,{...Oe,phase:Oe.phase,ts:Date.now()},E),Oe.phase==="start"){const Be=`${Oe.tool}_${Date.now()}`,we=new Date().toISOString(),Le=Me=>{const De=[...Me];for(let et=De.length-1;et>=0;et--){const Ct=De[et];if(Ct.type==="tool"&&Ct.tool===Oe.tool&&(Ct.status==="running"||Ct.status==="stopped"))return De[et]={...Ct,status:"running",args:Oe.arguments??Ct.args},De}return De.push({type:"tool",key:Be,tool:Oe.tool,status:"running",args:Oe.arguments,createdAt:we}),De};rt(R,Me=>{const De=[...Me],et=Ue?De.findIndex(ae=>ae.id===Ue):-1;if(et<0)return Me;const Ct=Le(De[et].segments??[]),Xt=De[et].committedSegments,$s=Xt&&Le(Xt);return De[et]={...De[et],segments:Ct,committedSegments:$s,isStreaming:!0},De},E)}else if(Oe.phase==="end"){const Be=new Date().toISOString(),we=Le=>{const Me=[...Le];for(let De=Me.length-1;De>=0;De--){const et=Me[De];if(et.type==="tool"&&et.tool===Oe.tool&&(et.status==="running"||et.status==="stopped")){Me[De]={...et,status:Oe.success===!1?"error":"done",args:Oe.arguments??et.args,result:Oe.result,error:Oe.error,durationMs:Oe.durationMs,liveOutput:void 0,createdAt:Be};break}}return Me};rt(R,Le=>{const Me=[...Le],De=Ue?Me.findIndex($s=>$s.id===Ue):-1;if(De<0)return Le;const et=we(Me[De].segments??[]),Ct=Me[De].committedSegments,Xt=Ct&&we(Ct);return Me[De]={...Me[De],segments:et,committedSegments:Xt,isStreaming:!0},Me},E)}else if(Oe.phase==="subagent_progress"&&Oe.subagentEvent){const Be=we=>{const Le=[...we];for(let Me=Le.length-1;Me>=0;Me--){const De=Le[Me];if(De.type==="tool"&&(De.tool==="spawn_subagent"||De.tool==="spawn_subagents")&&(De.status==="running"||De.status==="stopped")){Le[Me]={...De,status:"running",subagentLogs:km(De.subagentLogs,Oe.subagentEvent)};break}}return Le};er(R,we=>{const Le=[...we],Me=Ue?Le.findIndex(Xt=>Xt.id===Ue):-1;if(Me<0)return we;const De=Be(Le[Me].segments??[]),et=Le[Me].committedSegments,Ct=et&&Be(et);return Le[Me]={...Le[Me],segments:De,committedSegments:Ct,isStreaming:!0},Le},E)}}},Ne=Oe=>{Ve.current===R&&(Qr.current=Date.now(),rt(R,Be=>{const we=[...Be],Le=Ue?we.findIndex(De=>De.id===Ue):-1;if(Le<0)return Be;const Me=[...we[Le].committedSegments??[]];if(Oe.type==="thinking_commit")Me.push({type:"text",content:"",thinking:Oe.content,createdAt:Oe.createdAt});else if(Oe.type==="text_commit")Me.push({type:"text",content:Oe.content,createdAt:Oe.createdAt});else return Be;return we[Le]={...we[Le],committedSegments:Me,isStreaming:!0},we},E))},Ke=Oe=>{if(Ve.current!==R)return;Qr.current=Date.now();const Be=(Oe.segments??[]).map((we,Le)=>we.type==="tool"?{type:"tool",key:`${we.tool}_${Le}`,tool:we.tool??"tool",status:we.status==="error"?"error":we.status==="running"||we.status==="stopped"?"running":"done",args:we.arguments,result:we.result,error:we.error,durationMs:we.durationMs,createdAt:we.createdAt,...we.subagentLogs?.length?{subagentLogs:we.subagentLogs}:{}}:{type:"text",content:we.content??"",thinking:we.thinking,createdAt:we.createdAt});rt(R,we=>{const Le=[...we],Me=Ue?Le.findIndex(De=>De.id===Ue):-1;return Me<0?we:(Le[Me]={...Le[Me],text:Oe.content||Le[Me].text,segments:Be,committedSegments:Be,isStreaming:!0,isStopped:!1},Le)},E);for(const we of Be)we.type==="tool"&&rn(R,{tool:we.tool,phase:we.status==="running"||we.status==="stopped"?"start":"end",success:we.status!=="error",arguments:we.args,result:we.result,error:we.error,durationMs:we.durationMs,ts:Date.now()},E)},Je=await J.sessions.reattachStream(P,E,{onChunk:Qe,onActivity:ct,onCommit:Ne,onSnapshot:Ke},q.signal,0);if(!Je.attached){ai(R),Ve.current===R&&(rt(R,Oe=>{const Be=[...Oe],we=Ue?Be.findIndex(De=>De.id===Ue):-1,Le=we>=0?we:Be.map((De,et)=>({m:De,j:et})).reverse().find(De=>De.m.sender==="agent"&&De.m.isStreaming)?.j??-1;if(Le<0)return Oe;const Me=Be[Le];return Me.isStreaming?(Be[Le]={...Me,isStreaming:!1,isStopped:Me.isError?Me.isStopped:!0},Be):Oe},E),rs(!1));return}Ve.current===R&&(rt(R,Oe=>{const Be=[...Oe],we=Ue?Be.findIndex(et=>et.id===Ue):-1,Le=we>=0?we:Be.map((et,Ct)=>({m:et,j:Ct})).reverse().find(et=>et.m.sender==="agent")?.j??-1;if(Le<0)return Oe;const Me=Be[Le],De=Je.segments?.length?Cm(Je.segments,Me.segments):void 0;return Be[Le]={...Me,text:Je.content||Me.text,isStreaming:!1,isStopped:!1,...De?{segments:De,committedSegments:De}:{}},Be},E),rs(!1)),ai(R),$r.current===q&&($r.current=null)}catch(H){if($r.current===q&&($r.current=null),ai(R),Ve.current===R&&rs(!1),H instanceof Error&&H.name==="AbortError")return}},[rn,nn,ai,mt,hs,tt,rt,er]);C.useEffect(()=>{if(!o||t||ce!=="direct"||!ge)return;const P=it;!P||P===St||fn(ge,P,Ve.current)},[o,t,ce,ge,it,fn]);const Ol=C.useCallback(async P=>{if(!P)return an([]),[];try{const{sessions:E}=await J.sessions.listByAgent(P,10);return an(E),E}catch{return an([]),[]}},[]),xl=C.useRef(0),OS=C.useCallback(async()=>{if(!(yh||!Lp||!yi.current)){Np(!0);try{const P=Ve.current;if(ce==="channel"||ce==="dm"){const E=ce==="dm"?dl(e?.id??"",Nt):lt,R=await J.channels.getMessages(E,50,yi.current),q=R.messages.map(H=>xn(H,e?.id));xl.current=q.length,hl.current=!0,Qs(H=>{let fe=[...q,...H];return fe.length>500&&(fe=fe.slice(-500)),hs.set(P,fe),fe}),Mi(R.hasMore),R.messages[0]&&(yi.current=new Date(R.messages[0].createdAt).toISOString())}else if(it){const E=await J.sessions.getMessages(it,50,yi.current),R=E.messages.map(td);xl.current=R.length,hl.current=!0,Qs(q=>{let H=[...R,...q];return H.length>500&&(H=H.slice(-500)),hs.set(P,H),H}),Mi(E.hasMore),E.messages[0]&&(yi.current=new Date(E.messages[0].createdAt).toISOString())}}catch{}finally{Np(!1)}}},[yh,Lp,ce,lt,it,e?.id,Nt]);tm.current=OS;const Xh=C.useRef(!1),xS=C.useCallback(P=>{Xh.current||(Xh.current=!0,requestAnimationFrame(()=>{Xh.current=!1,P.target.scrollTop<100&&tm.current?.()}))},[]);C.useEffect(()=>{if(t)return;const P=Kl(ce,ge,lt,Nt),E=Ve.current;Ve.current=P,E&&E!==P&&(tl.set(E,Mo),it&&ds.set(E,it)),E!==P&&(nr(),rr(!1),Er.current=0,dn(0));const R=hs.get(P),q=tl.get(P),H=ds.get(P),fe=mt(P),me=H??it,be=Fe(P)&&(ce!=="direct"||!fe||!me||fe.has(me)),te=me??P,de=oi.get(te)??[];if(bi(be?de:[]),rs(be),ce==="direct"&&ge&&Ol(ge),q&&q.length>0&&Ns(q),cn(!1),R!==void 0&&R.length>0)if(be||el.completeLoad(P),tr(!1),Qs(R),Mi(!1),H!==void 0&&Li(H),(!q||q.length===0)&&Ns([]),ce==="channel"||ce==="dm"){const Ue=ce==="dm"?dl(e?.id??"",Nt):lt;nm(Ue,P)}else ce==="direct"&&ge&&H&&H!==St&&(be?fn(ge,H,P):Wh(H,P).then(()=>{Ve.current===P&&ge&&fn(ge,H,P)}));else if(sl(P),tr(!0),Qs([]),Mi(!1),yi.current=null,hs.delete(P),ce==="channel"||ce==="dm"){const Ue=ce==="dm"?dl(e?.id??"",Nt):lt;nm(Ue,P),(!q||q.length===0)&&Ns([])}else ce==="direct"&&ge?Ol(ge).then(Ue=>{if(Ve.current===P)if(Ue.length>0){const Xe=Ue.find(Le=>Le.isMain),Qe=kh(ge),ct=Xe?[Xe,...Ue.filter(Le=>!Le.isMain&&!Qe.has(Le.id)).slice(0,4)]:Ue.filter(Le=>!Qe.has(Le.id)).slice(0,5);let Ne=q&&q.length>0?q:ct;const Ke=J1(ge),Je=H!==void 0?H:Ke??Xe?.id??Ne[0].id;if(Je&&Je!==St&&!Ne.some(Le=>Le.id===Je)){const Le=Ue.find(Me=>Me.id===Je);Le&&(Ne=[...Ne,Le])}const Oe=Je&&Ne.some(Le=>Le.id===Je)?Je:Ne[0].id;Li(Oe),ds.set(P,Oe),ol(ge,Oe),Ns(Ne);const we=Ue.find(Le=>Le.id===Oe)?.metadata?.modelOverride;nl(we?.provider&&we?.model?{provider:we.provider,model:we.model}:null),Wh(Oe,P).then(()=>{Ve.current===P&&ge&&fn(ge,Oe,P)})}else Li(null),nl(null),tr(!1),(!q||q.length===0)&&Ns([])}).catch(()=>{Ve.current===P&&tr(!1)}):tr(!1)},[t,ce,ge,lt,Nt,n.language,r]),C.useEffect(()=>t?void 0:gt.on("chat:message",E=>{const R=E.payload,q=R.channel??"";if(!q)return;const H=R.senderType??"agent",fe=R.text??R.message??"",me=R.senderId??R.agentId??"",be=R.senderName??R.agentId??r("page.fallbackAgent"),te=R.metadata,de=R.messageId??R.id??"";if(de&&tn.current.has(de))return;const st=H==="human"&&me===(e?.id??""),Ue={id:de||`ws_${Date.now()}_${me}`,sender:st?"user":"agent",text:fe,time:new Date().toLocaleTimeString(),agentName:st?void 0:be,agentId:st?void 0:me,replyToId:R.replyToId??void 0,replyToSender:R.replyToSender??void 0,replyToText:R.replyToText??void 0};if(te&&H==="agent"){const Qe=[];if(te.thinking?.length&&Qe.push({type:"text",content:"",thinking:te.thinking.join(`
|
|
72
|
+
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Or.navigate(Ht.TEAM,{agentId:s,prefillMessage:T})},D=async V=>{if(y?.file===V){_(null);return}try{const Z=await J.agents.roleDiff(s,V);Z.agentContent!=null&&Z.templateContent!=null&&_({file:V,agent:Z.agentContent,template:Z.templateContent})}catch{}};if(r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},j=V=>{const Z=$[V];return Z?e(`agent:profilePage.filesTab.fileLabels.${Z}`):V},B=p?.hasTemplate&&!p.isUpToDate,F=a?Q.some(V=>V.file===a):!1;return h.jsxs("div",{className:"space-y-4",children:[B&&h.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[h.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),h.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:Q.length,templateId:p.templateId})," ",Q.map(V=>V.file).join(", ")]})]}),h.jsx("button",{onClick:()=>I(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),h.jsxs(Gt,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",h.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[h.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(V=>{const Z=Q.some(se=>se.file===V.name);return h.jsxs("button",{onClick:()=>w(V.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===V.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[V.name,Z&&h.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},V.name)})}),a&&h.jsxs("div",{children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("div",{className:"text-xs text-fg-secondary",children:j(a)}),h.jsxs("div",{className:"flex gap-2 items-center",children:[F&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>D(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),h.jsx("button",{onClick:()=>I(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),b&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&h.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[h.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),g(!0),setTimeout(()=>g(!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:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),h.jsx("button",{onClick:()=>{J.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&h.jsx(GA,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),h.jsx(JA,{content:t.find(V=>V.name===a)?.content??"",editContent:l,setEditContent:V=>{c(V),O(!0)},dirty:m,onSave:S}),a==="ROLE.md"&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&h.jsx(Gc,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function JA({content:s,editContent:e,setEditContent:t,dirty:i,onSave:r}){const[n,a]=C.useState(!1),o=C.useRef(null);return C.useEffect(()=>{n&&o.current?.focus()},[n]),C.useEffect(()=>{a(!1)},[s]),n||i?h.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&r(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):h.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[h.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(UA,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const eM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{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 tM(s,e){const t=new Map,i=new Set;for(const{id:a,prefixes:o}of eM){const l=e(`agent:toolCategories.${a}`),c=s.filter(d=>!i.has(d.name)&&o.some(u=>d.name.startsWith(u)));c.length>0&&(t.set(l,c),c.forEach(d=>i.add(d.name)))}const r=s.filter(a=>!i.has(a.name));for(const a of r){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),c=e("agent:toolCategories.mcp",{server:l});t.has(c)||t.set(c,[]),t.get(c).push(a),i.add(a.name)}}const n=s.filter(a=>!i.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function sM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function iM({tools:s}){const{t:e}=Pt(["agent","common"]),t=tM(s,e);return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(i=>h.jsx(Gt,{title:`${i.category} (${i.tools.length})`,children:h.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:i.tools.map(r=>{const n=n_(r.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=r.name.includes("__"),l=o?r.name.split("__").pop():r.name,c=sM(r.description||"");return h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[h.jsx(o_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&h.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&h.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),c&&h.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:c,children:c})]})]},r.name)})})},i.category)),s.length===0&&h.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function rM({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[i,r]=C.useState(null),[n,a]=C.useState(null),[o,l]=C.useState(!1),c=s.availableSkills??[],d=new Map;for(const m of c){const O=m.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(m)}const u=async m=>{if(i===m){r(null),a(null);return}r(m),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(m)}`);if(O.ok){const p=await O.json();a(p.skill)}else a(null)}catch{a(null)}l(!1)},f={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"},g=m=>{const O=t[m.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:O.uses,successes:O.successes}),O.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(O.lastUsed).toLocaleDateString()})]}),y=i===m.name;return h.jsxs("div",{children:[h.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(m.name),children:[h.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:m.name}),m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),m.builtIn&&!m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!m.builtIn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:m.description}),x]}),p!==null&&h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:h.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&h.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(_=>h.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:_},_))]}),n.description&&h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&h.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(_=>h.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",_]},_))}),(n.toolDetails??n.tools??[]).length>0&&h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),h.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(_=>h.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:_.name}),_.description&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:_.description})]},_.name))})]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},m.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],v=[...d.entries()].sort((m,O)=>{const p=b.indexOf(m[0]),x=b.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:c.length})})}),v.map(([m,O])=>h.jsx(Gt,{title:h.jsxs("span",{className:"capitalize",children:[m," ",h.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:h.jsx("div",{className:"space-y-2",children:O.map(p=>g(p))})},m)),c.length===0&&h.jsx(Gc,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function H0({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[i,r]=C.useState("tools");return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>h.jsx("button",{onClick:()=>r(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${i===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),i==="tools"?h.jsx(iM,{tools:s}):h.jsx(rM,{agent:e})]})}function G0({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,i]=C.useState(null),[r,n]=C.useState(!0),[a,o]=C.useState("longterm"),[l,c]=C.useState(""),[d,u]=C.useState(""),[f,g]=C.useState(!1),[b,v]=C.useState(null),[m,O]=C.useState(null),[p,x]=C.useState([]),[y,_]=C.useState(!1),k=C.useCallback(()=>{n(!0),J.agents.getMemory(s).then($=>{i($),c($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);C.useEffect(()=>{k()},[k]);const w=async()=>{g(!0),await J.agents.updateDailyMemory(s,l).catch(()=>{}),g(!1),k()},S=async()=>{g(!0),await J.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),g(!1),k()},Q=l!==(t?.recentDailyLogs??""),I=d!==(t?.longTermMemory??"");if(r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const D=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex gap-2",children:D.map($=>h.jsx("button",{onClick:()=>o($.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===$.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:$.label},$.key))}),a==="entries"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?h.jsx(Gc,{text:e("agent:profilePage.memoryTab.noEntries")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,j)=>{const B=b===j;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>v(B?null:j),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:[h.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.type==="fact"?"bg-blue-500/15 text-blue-600":$.type==="task"?"bg-green-500/15 text-green-600":$.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:$.type}),h.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:$.content}),h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&h.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${$.importance>=7?"bg-red-500/15 text-red-500":$.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",$.importance]}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&h.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[h.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),h.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[h.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&h.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),h.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},j)})})}),a==="sessions"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?h.jsx(Gc,{text:e("agent:profilePage.memoryTab.noSessions")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const j=m===$.id,B=async()=>{if(j){O(null),x([]);return}O($.id),_(!0);try{const F=await J.agents.getMemorySession(s,$.id);x(F.messages)}catch{x([])}_(!1)};return h.jsxs("div",{children:[h.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[h.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:j?"▲":"▼"})]}),j&&h.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const F=new Map;for(const V of p)V.role==="tool"&&V.toolCallId&&F.set(V.toolCallId,V.content);return h.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(V=>V.role!=="tool").map((V,Z)=>h.jsxs("div",{className:"px-3 py-2",children:[(V.role==="user"||V.role==="system")&&h.jsxs("div",{children:[h.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${V.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${V.role}`,{defaultValue:V.role})}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(ma,{content:V.content,className:"text-xs text-fg-secondary"})})]}),V.role==="assistant"&&h.jsxs("div",{className:"space-y-1",children:[V.content&&h.jsxs("div",{children:[h.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(ma,{content:V.content,className:"text-xs text-fg-secondary"})})]}),V.toolCalls&&V.toolCalls.length>0&&h.jsx("div",{className:"space-y-0.5",children:V.toolCalls.map(se=>{let T;try{T=JSON.parse(se.arguments)}catch{}const A={tool:se.name,status:"done",args:T,result:F.get(se.id)};return h.jsx(e_,{entry:{type:"tool",info:A}},se.id)})})]})]},Z))})})()})]},$.id)})})}),a==="daily"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:Q?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>c(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:w,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:l,onChange:$=>c($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&h.jsx(Gt,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:I?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:S,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:d,onChange:$=>u($.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function K0({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[i,r]=C.useState(e??null),[n,a]=C.useState(!e),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(!1),[g,b]=C.useState(null),v=C.useCallback(()=>Promise.all([J.agents.getHeartbeat(s).then(r).catch(()=>{}),J.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);C.useEffect(()=>{a(!0),v().finally(()=>a(!1))},[v]),C.useEffect(()=>gt.on("agent:update",_=>{_.payload?.agentId===s&&v()}),[s,v]);const m=async()=>{f(!0),b(null);try{const y=await J.agents.triggerHeartbeat(s);b(y.message),setTimeout(()=>b(null),4e3),setTimeout(v,2e3)}catch(y){b(String(y).replace("Error: ",""))}f(!1)},O=async y=>{try{await J.agents.cancelWakeup(s,y),v()}catch{}};if(n)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=y=>y?y<1e3?`${y}ms`:y<6e4?`${(y/1e3).toFixed(1)}s`:`${(y/6e4).toFixed(1)}m`:null,x=y=>{if(!y)return null;const _=Date.now()-new Date(y).getTime();if(_<0){const k=Math.abs(_);return k<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(k/1e3)}):k<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(k/6e4)}):t("agent:profilePage.relative.inHours",{hours:(k/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return h.jsxs("div",{className:"space-y-4",children:[h.jsxs(Gt,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:v,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),h.jsx("button",{onClick:m,disabled:u||!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:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[h.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[h.jsx(as,{label:t("agent:profilePage.overview.labels.status"),value:i.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:i.running?"green":"gray"}),h.jsx(oM,{agentId:s,intervalMs:i.intervalMs,onChanged:v}),h.jsx(as,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:i.lastHeartbeat?x(i.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),h.jsx(as,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:i.nextWakeAt?x(i.nextWakeAt)??t("agent:profilePage.emDash"):i.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),h.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),g&&h.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:g})]}),i.wakeups&&i.wakeups.length>0&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:i.wakeups.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.wakeups.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[x(y.wakeAt)??new Date(y.wakeAt).toLocaleString(),y.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${y.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),h.jsx("button",{onClick:()=>O(y.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},y.id))})}),i.pendingCallbacks&&i.pendingCallbacks.length>0&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:i.pendingCallbacks.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.pendingCallbacks.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${y.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${x(y.timeoutAt)??new Date(y.timeoutAt).toLocaleString()}`]})]})]},y.id))})}),i.lastSummary&&h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:i.lastSummaryAt?h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(i.lastSummaryAt).toLocaleString()}):void 0,children:h.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:h.jsx(ma,{content:i.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const _=c===y.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(_?null:y.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:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),h.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:h.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Ba,{agentId:s,activityId:y.id})})]},y.id)})})}):i.lastHeartbeat?null:h.jsx(Gt,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:h.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[h.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),h.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),h.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:i.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(i.intervalMs-i.uptimeMs%i.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),i.running&&h.jsx("button",{onClick:m,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function nM({taskId:s,isLive:e}){const{t}=Pt("agent"),[i,r]=C.useState([]),[n,a]=C.useState(""),[o,l]=C.useState(!0),[c,d]=C.useState("compact");if(C.useEffect(()=>{l(!0),a(""),J.tasks.getLogs(s).then(g=>{r(g.logs),l(!1)}).catch(()=>l(!1))},[s]),C.useEffect(()=>{if(!e)return;const g=gt.on("task:log",v=>{const m=v.payload;if(m.taskId!==s)return;const O={id:m.id,taskId:m.taskId,agentId:m.agentId,seq:m.seq,type:m.logType,content:m.content,metadata:m.metadata,createdAt:m.createdAt};r(p=>O.id&&p.some(x=>x.id===O.id)?p:[...p,O]),O.type==="text"&&a("")}),b=gt.on("task:log:delta",v=>{const m=v.payload;m.taskId===s&&a(O=>O+m.text)});return()=>{g(),b()}},[s,e]),o)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(i.length===0&&!n)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=i.map(g=>r_(g)),f=new Set(u.filter(g=>g.executionRound!=null).map(g=>g.executionRound)).size>1;return h.jsx("div",{className:"px-3 py-2",children:c==="compact"?h.jsx(xx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):h.jsx(vx,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Ba({agentId:s,activityId:e,isLive:t=!1}){const{t:i}=Pt("agent"),[r,n]=C.useState([]),[a,o]=C.useState(!0),[l,c]=C.useState("compact");if(C.useEffect(()=>{o(!0),J.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),C.useEffect(()=>t?gt.on("agent:activity_log",f=>{const g=f.payload;if(g.agentId!==s||g.activityId!==e)return;const b={seq:g.seq,type:g.type,content:g.content,metadata:g.metadata,createdAt:g.createdAt};n(v=>v.some(m=>m.seq===b.seq)?v:[...v,b])}):void 0,[s,e,t]),a)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.loading")});if(r.length===0)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.noLogs")});const d=r.map(u=>i_(u,e,s)).filter(u=>u!==null);return h.jsx("div",{className:"px-3 py-2",children:l==="compact"?h.jsx(xx,{entries:d,isActive:t,onExpand:()=>c("full")}):h.jsx(vx,{entries:d,isActive:t,onCollapse:()=>c("compact")})})}function Gt({title:s,action:e,children:t}){return h.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[h.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Ds({label:s,mono:e,children:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),h.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function as({label:s,value:e,color:t}){const i=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return h.jsxs("div",{className:"flex items-baseline gap-1.5",children:[h.jsx("span",{className:`text-sm font-semibold ${i}`,children:e}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const J0=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],ex=5,tx=1440;function oM({agentId:s,intervalMs:e,onChanged:t}){const{t:i}=Pt(["agent","common"]),[r,n]=C.useState(!1),[a,o]=C.useState(null),[l,c]=C.useState(!1),[d,u]=C.useState(String(Math.round(e/6e4))),f=p=>p%(3600*1e3)===0?i("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):i("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),g=async p=>{n(!0),o(null);try{await J.agents.updateConfig(s,{heartbeatIntervalMs:p}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},b=p=>{if(p.target.value==="custom"){c(!0);return}c(!1),g(Number(p.target.value))},v=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<ex||p>tx){o(i("agent:profilePage.heartbeatTab.intervalRangeHint"));return}g(p*60*1e3)},m=J0.includes(e),O=l||!m?"custom":String(e);return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.heartbeatTab.safetyNetInterval")}),h.jsxs("select",{value:O,onChange:b,disabled:r,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:[!m&&h.jsx("option",{value:String(e),children:f(e)}),J0.map(p=>h.jsx("option",{value:String(p),children:f(p)},p)),h.jsx("option",{value:"custom",children:i("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!m)&&h.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[h.jsx("input",{type:"number",min:ex,max:tx,value:d,onChange:p=>u(p.target.value),disabled:r,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"}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.heartbeatTab.intervalCustomUnit")}),h.jsx("button",{onClick:v,disabled:r,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(r?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&h.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Gc({text:s}){return h.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function sx(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),i=s/Math.pow(1024,t);return`${i<10?i.toFixed(1):Math.round(i)} ${e[t]}`}const ix={0:"0",1:"1",2:"2",3:"3",4:"4"},rx={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},aM={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"},lM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Hl={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:"🧠"},cM=["all","interaction","task","notification","system"],hM={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"]},dM={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"},uM={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 hu(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function nx(s,e){const t=s.payload,i=t?.summary??"",r=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=i.match(/^Task "(.+?)" status:/),o=i.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??i;if(o){const d=o[1],u=o[2],f=bf(d,e),g=bf(u,e),b=uM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:g}),badge:{label:g,color:b}}}const c=i.match(/^Task:\s*(.+)/);return c?{title:c[1]}:{title:l}}case"task_comment":{const a=i.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=hu(r);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:i}}case"requirement_update":{const a=i.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:i}}case"requirement_comment":{const a=i.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=hu(r);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:i}}case"human_chat":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(r.length>120?"…":"")}}case"a2a_message":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(r.length>120?"…":"")}}case"mention":{const a=i.match(/from (.+)$/),o=hu(r);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(r.length>120?"…":"")}}case"session_reply":{const a=r.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(r.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=i.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:i||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:i||s.sourceType}}}function ox({agentId:s,highlightId:e,agentStatus:t,canManageAgents:i,onAgentStateChange:r}){const{t:n}=Pt(["agent","common","team"]),[a,o]=C.useState(null),[l,c]=C.useState(null),[d,u]=C.useState(!0),[f,g]=C.useState("all"),[b,v]=C.useState("all"),[m,O]=C.useState(e??null),[p,x]=C.useState(e??null),[y,_]=C.useState(!1),[k,w]=C.useState(!0),[S,Q]=C.useState(null),I=50,D=3,$=C.useCallback(async(T=!0)=>{T&&u(!0);try{const A=f==="all"?void 0:f,N=b==="all"?void 0:b,[z,U]=await Promise.all([J.agents.getMindState(s),J.agents.getMailbox(s,{limit:I,category:A,status:N})]);o(z),c(U),w((U.history?.length??0)>=I)}catch{}u(!1)},[s,f,b]),j=C.useCallback(async()=>{if(!l)return;const T=f==="all"?void 0:f,A=b==="all"?void 0:b;try{const N=await J.agents.getMailbox(s,{limit:I,offset:l.history.length,category:T,status:A});c(z=>z?{...z,history:[...z.history,...N.history]}:N),w((N.history?.length??0)>=I)}catch{}},[s,l,f,b]);C.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const B=C.useRef(!1);if(C.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){B.current=!1;const A=document.getElementById(`mbx-${p}`);if(A){setTimeout(()=>A.scrollIntoView({behavior:"smooth",block:"center"}),100);const N=setTimeout(()=>x(null),3e3);return()=>clearTimeout(N)}}else k&&!B.current&&(B.current=!0,(async()=>{let A=l?.history??[],N=k;for(;N;)try{const z=await J.agents.getMailbox(s,{limit:I,offset:A.length}),U=[...A,...z.history];A=U,N=(z.history?.length??0)>=I;const ne=z.history.some(Se=>Se.id===p);if(c(Se=>Se?{...Se,history:U}:z),w(N),ne||!N)break}catch{break}B.current=!1})())},[p,d,l,k,s]),C.useEffect(()=>{let T=null;const A=z=>{z.payload?.agentId===s&&(T&&clearTimeout(T),T=setTimeout(()=>{T=null,$(!1)},500))},N=[gt.on("agent:mailbox",A),gt.on("agent:decision",A),gt.on("agent:attention",A),gt.on("agent:focus",A),gt.on("agent:update",A),gt.on("agent:triage",A)];return()=>{T&&clearTimeout(T),N.forEach(z=>z())}},[s,$]),d&&!a)return h.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:n("agent:profilePage.mind.loading")});const F=a?.mailboxDepth??a?.queuedItems?.length??0,V=(()=>{const T=a?.attentionState??"idle";return T==="deciding"||T==="idle"&&F>0?"deciding":T!=="idle"&&!a?.currentFocus?"idle":T})(),Z=V==="idle"&&l?.history?.some(T=>T.status==="processing"),se=(a?.attentionState??"idle")==="idle"&&F>0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[h.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${lM[V]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${V}`)}),a?.currentFocus?(()=>{const T=nx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return h.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[h.jsxs("span",{children:[Hl[a.currentFocus.type]??"●"," ",h.jsx("span",{className:"text-fg-primary font-medium",children:T.title}),T.subtitle&&h.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:T.subtitle}),h.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),i&&h.jsxs("button",{onClick:()=>Q(a.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:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]})})():se?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.queuedButIdle",{count:F,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:F})}):h.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[i&&t==="offline"&&h.jsxs("button",{onClick:()=>{J.agents.start(s).then(()=>{r?.(),$()})},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:["▶ ",n("agent:profilePage.mind.continueBtn")]}),i&&(t==="working"||t==="idle")&&h.jsxs("button",{onClick:()=>{J.agents.stop(s).then(()=>{r?.(),$()})},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:["■ ",n("team:contextMenu.stop")]}),h.jsx("button",{onClick:()=>{$()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:n("agent:profilePage.mind.refresh")})]})]}),Z&&h.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:[h.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),h.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const T=a.queuedItems,A=T.length>D,N=A&&!y?T.slice(0,D):T,z=T.reduce((U,ne)=>(U[ne.sourceType]=(U[ne.sourceType]??0)+1,U),{});return h.jsxs("div",{className:"mb-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:T.length})}),h.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(z).map(([U,ne])=>h.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Hl[U]??"●"," ",ne]},U))})]}),h.jsxs("div",{className:"space-y-1",children:[N.map((U,ne)=>h.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:[h.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:ne+1}),h.jsx("span",{className:"text-sm",children:Hl[U.sourceType]??"●"}),h.jsx("span",{className:`text-[10px] ${rx[U.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${ix[U.priority]??U.priority}`,{defaultValue:`P${U.priority}`})}),h.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:U.summary}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(U.queuedAt).toLocaleTimeString()})]},U.id)),A&&h.jsx("button",{onClick:()=>_(!y),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:y?n("agent:profilePage.mind.collapseQueue"):n("agent:profilePage.mind.expandQueue",{count:T.length-D})})]})]})})()]}),(a?.notebook?.length??0)>0&&h.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:h.jsxs("details",{open:!0,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"📓"}),h.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),h.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),h.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(T=>{const A=Date.now()-T.updatedAt,N=A<6e4?`${Math.round(A/1e3)}s ago`:A<36e5?`${Math.round(A/6e4)}min ago`:`${(A/36e5).toFixed(1)}h ago`,z=T.managed==="system"?"text-blue-400":T.managed==="cpp"?"text-purple-400":"text-emerald-400";return h.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary",children:T.key}),h.jsxs("span",{className:`text-[10px] ${z}`,children:["[",T.managed,"]"]}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:N})]}),h.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:T.text.length>500?T.text.slice(0,500)+"…":T.text})]},T.key)})})]})}),a?.deliberationActivity&&h.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),h.jsx(Ba,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return h.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:h.jsxs("details",{open:!A,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),h.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:n("agent:profilePage.mind.deferred",{count:a.lastTriage.deferredItemIds.length})}),a.lastTriage.droppedItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:n("agent:profilePage.mind.dropped",{count:a.lastTriage.droppedItemIds.length})}),(a.lastTriage.inlineCompletedIds?.length??0)>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:n("agent:profilePage.mind.inlineCompleted",{count:a.lastTriage.inlineCompletedIds.length})})]})]})})})(),h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),h.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:cM.map(T=>{const A=l?.sourceTypeCounts,N=T==="all"?A?Object.values(A).reduce((z,U)=>z+U,0):void 0:A?(hM[T]??[]).reduce((z,U)=>z+(A[U]??0),0):void 0;return h.jsxs("button",{onClick:()=>g(T),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===T?"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:[n(`agent:profilePage.mind.categoryFilters.${T}`),N!=null&&N>0&&h.jsx("span",{className:"ml-1 opacity-60",children:N})]},T)})})]}),h.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(T=>{const A=l?.statusCounts,N=T.key==="all"?A?Object.values(A).reduce((z,U)=>z+U,0):void 0:A?.[T.key];return h.jsxs("button",{onClick:()=>v(T.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${b===T.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:[T.dot&&h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T.dot}`}),n(`agent:profilePage.mind.statusFilters.${T.key}`),N!=null&&N>0&&h.jsx("span",{className:"ml-1 opacity-60",children:N})]},T.key)})}),(!l?.history||l.history.length===0)&&!d&&h.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),h.jsx("div",{className:"space-y-1",children:l?.history?.map(T=>{const A=m===T.id,N=Hl[T.sourceType]??"●",z=nx(T,n),U=T.metadata?.senderName,ne=T.metadata?.senderRole,Se=p===T.id;return h.jsxs("div",{id:`mbx-${T.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${Se?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[h.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:()=>O(A?null:T.id),children:[h.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),h.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${dM[T.status]??"bg-gray-400"}`}),h.jsx("span",{className:"text-sm",children:N}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:z.title}),z.badge&&h.jsx("span",{className:`text-[10px] font-medium shrink-0 ${z.badge.color}`,children:z.badge.label}),h.jsx("span",{className:`text-[10px] shrink-0 ${rx[T.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${ix[T.priority]??T.priority}`,{defaultValue:""})})]}),z.subtitle&&h.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:z.subtitle}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[h.jsx("span",{children:new Date(T.queuedAt).toLocaleString()}),T.completedAt&&h.jsxs("span",{children:["→ ",new Date(T.completedAt).toLocaleTimeString()]}),T.activity&&h.jsxs(h.Fragment,{children:[T.activity.totalTokens>0&&h.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:Gn(T.activity.totalTokens)})}),T.activity.totalTools>0&&h.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:T.activity.totalTools})})]})]})]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:T.sourceType}),i&&T.status==="processing"&&h.jsxs("button",{onClick:Pe=>{Pe.stopPropagation(),Q(T.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:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]}),A&&h.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[U&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",h.jsx("span",{className:"text-fg-secondary",children:U}),ne&&h.jsxs("span",{className:"text-fg-tertiary",children:[" (",ne,")"]})]}),T.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(T.sourceType)&&h.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:T.payload.content}),T.decisions&&T.decisions.length>0&&h.jsxs("div",{children:[h.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),h.jsx("div",{className:"space-y-1",children:T.decisions.map(Pe=>h.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${aM[Pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:Pe.decisionType}),h.jsx("span",{className:"text-fg-secondary flex-1",children:Pe.reasoning}),h.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(Pe.createdAt).toLocaleTimeString()})]},Pe.id))})]}),T.activity?h.jsxs("div",{children:[h.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:T.activity.label}),h.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${T.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:T.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),T.activity.type==="task"&&T.payload?.taskId?h.jsx(nM,{taskId:T.payload.taskId,isLive:!T.activity.endedAt}):h.jsx(Ba,{agentId:s,activityId:T.activity.id,isLive:!T.activity.endedAt})]}):T.status==="processing"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):T.status==="completed"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},T.id)})}),k&&(l?.history?.length??0)>0&&h.jsx("div",{className:"text-center mt-3",children:h.jsx("button",{onClick:j,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),S&&h.jsx(Wa,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{Q(null),J.agents.cancelProcessing(s).then(()=>{let T=0;const A=()=>{T+=1,$(),T<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>Q(null)})]})}function ax({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,i]=C.useState([]),[r,n]=C.useState(!0),[a,o]=C.useState(null),l=C.useCallback(async()=>{n(!0);try{const{results:c}=await J.deliverables.search({agentId:s,limit:200});i(c)}catch{i([])}n(!1)},[s]);return C.useEffect(()=>{l()},[l]),C.useEffect(()=>{const c=gt.on("deliverable:created",()=>l()),d=gt.on("deliverable:updated",()=>l()),u=gt.on("deliverable:removed",()=>l());return()=>{c(),d(),u()}},[l]),r?h.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(c=>h.jsxs("div",{className:"animate-pulse space-y-2",children:[h.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),h.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},c))}):t.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[h.jsx("span",{className:"text-3xl mb-3",children:"📦"}),h.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),h.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:t.length})}),t.map(c=>{const d=t_[c.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=Sm[c.status]??Sm.active;return h.jsxs("button",{onClick:()=>o(c),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:[h.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:c.title}),h.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:c.status})]}),c.summary&&h.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:c.summary}),h.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[h.jsx("span",{children:new Date(c.createdAt).toLocaleDateString()}),c.tags.length>0&&h.jsx("span",{children:c.tags.slice(0,3).join(", ")})]})]}),h.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:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},c.id)})]}),a&&h.jsx(s_,{item:a,onClose:()=>o(null),onOpenInPage:c=>{o(null),Or.navigate(Ht.DELIVERABLES,{openDeliverable:c})}})]})}const fM=C.lazy(()=>bx(()=>import("./index-BMzsi3-i.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Ap=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],lx={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function cx({teamId:s,onBack:e,inline:t,headless:i,activeTab:r,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=C.useState(null),[c,d]=C.useState(null),[u,f]=C.useState("overview"),g=i&&r?r:u,[b,v]=C.useState(""),[m,O]=C.useState(""),[p,x]=C.useState(!1),[y,_]=C.useState(!1),[k,w]=C.useState(""),[S,Q]=C.useState(""),I=C.useRef(null),D=C.useRef(null),$=C.useRef(null),j=C.useRef(null),[B,F]=C.useState(!1),[V,Z]=C.useState(!1),[se,T]=C.useState(""),[A,N]=C.useState(""),[z,U]=C.useState(!1),[ne,Se]=C.useState([]),Pe=C.useRef(null),X=C.useCallback(async()=>{try{const ee=(await J.teams.list()).teams.find(ke=>ke.id===s);ee&&l(ee);const le=await J.teams.status(s);Se(le.agents)}catch{}},[s]),M=C.useCallback(async()=>{try{const Y=await J.teams.getFile(s,"ANNOUNCEMENT.md");v(Y.content)}catch{v("")}try{const Y=await J.teams.getFile(s,"NORMS.md");O(Y.content)}catch{O("")}},[s]);C.useEffect(()=>{f("overview"),X(),M()},[s,X,M]),C.useEffect(()=>{p&&D.current&&D.current.focus()},[p]),C.useEffect(()=>{y&&j.current&&j.current.focus()},[y]);const K=async(Y,ee)=>{F(!0);try{await J.teams.updateFile(s,Y,ee),Y==="ANNOUNCEMENT.md"?(v(ee),x(!1)):(O(ee),_(!1))}catch{}F(!1)},ie=async()=>{se.trim()&&(await J.teams.update(s,{name:se.trim()}),Z(!1),X())},oe=async()=>{await J.teams.update(s,{description:A}),U(!1),X()};if(!o)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const G=o.members.find(Y=>Y.agentRole==="manager"),$e=ne.filter(Y=>Y.status!=="offline").length,Ie=g==="announcements"&&p||g==="norms"&&y;if(i)return h.jsx("div",{className:`flex-1 bg-surface-primary ${Ie?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:h.jsxs("div",{className:`${Ie?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:G?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Y=>{const ee=ne.find(Ce=>Ce.id===Y.id),le=lx[ee?.status??"offline"]??"bg-gray-500",ke=Y.type==="agent";return h.jsxs("div",{onClick:()=>ke&&n?.(Y.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ke&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(_s,{name:Y.name,avatarUrl:Y.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:Y.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${le}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ee?.status??"offline"}),Y.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Y.role," · ",Y.type]})]}),ke&&n&&h.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:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Y.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),g==="announcements"&&h.jsx(Gl,{content:b,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:D,contentRef:I,saving:B,onSave:()=>K("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),g==="norms"&&h.jsx(Gl,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:B,onSave:()=>K("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),g==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),V?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:Pe,value:se,onChange:Y=>T(Y.target.value),onKeyDown:Y=>Y.key==="Enter"&&ie(),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}),h.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),z?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:Y=>N(Y.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}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:oe,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{N(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(hx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const We=u==="announcements"&&p||u==="norms"&&y;return h.jsxs("div",{className:`flex-1 bg-surface-primary ${We?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.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:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:o.name}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[$e," online"]})]}),h.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),h.jsxs("button",{onClick:async()=>{if(o)try{const{files:Y}=await J.teams.getFilesMap(o.id),ee=o.members.filter(ke=>ke.type==="agent"),le={type:"team",name:gx(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:ee.map(ke=>({name:ke.name,roleName:ke.role,role:ke.agentRole??"worker",count:1,skills:[]}))}};await Ox.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:le,files:Y}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Y){d({title:"Hub",message:`Failed to publish: ${Y}`,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:[h.jsx("span",{children:"↑"})," Hub"]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),h.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Ap.map(Y=>h.jsxs("button",{onClick:()=>f(Y.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===Y.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Y.icon," ",a(Y.labelKey)]},Y.key))})]}),h.jsxs("div",{className:`${We?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:G?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Y=>{const ee=ne.find(Ce=>Ce.id===Y.id),le=lx[ee?.status??"offline"]??"bg-gray-500",ke=Y.type==="agent";return h.jsxs("div",{onClick:()=>ke&&n?.(Y.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ke&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(_s,{name:Y.name,avatarUrl:Y.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:Y.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${le}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ee?.status??"offline"}),Y.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Y.role," · ",Y.type]})]}),ke&&n&&h.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:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Y.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&h.jsx(Gl,{content:b,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:D,contentRef:I,saving:B,onSave:()=>K("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&h.jsx(Gl,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:B,onSave:()=>K("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),V?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:Pe,value:se,onChange:Y=>T(Y.target.value),onKeyDown:Y=>Y.key==="Enter"&&ie(),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}),h.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),z?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:Y=>N(Y.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}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:oe,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{N(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(hx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),c&&h.jsx(Wa,{alertOnly:!0,variant:c.variant??"primary",title:c.title,message:c.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function Gl({content:s,draft:e,setDraft:t,editing:i,setEditing:r,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:c,emptyText:d}){return i?h.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[h.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():r(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),r(!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:c}),o&&h.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):h.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),r(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),r(!0))},children:s.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(fM,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function hx({teamId:s,teamName:e,onDeleted:t}){const[i,r]=C.useState(!1),[n,a]=C.useState(!1),[o,l]=C.useState(!1),[c,d]=C.useState(!1);return h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[h.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),i?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{disabled:c,onClick:async()=>{d(!0);try{await J.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:c?"Deleting...":"Confirm Delete"}),h.jsx("button",{onClick:()=>r(!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"})]})]}):h.jsx("button",{onClick:()=>r(!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 Kl(s,e,t,i){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${i??""}`:e||"_direct"}class mr{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(e){return this.phase.get(e)??"idle"}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e){this.phase.set(e,"idle"),this.activeSession.delete(e)}updateMessages(e,t,i){const r=this.activeSession.get(e),n=!i||r===i||r===void 0,a=n?this.msgBuffers.get(e)??[]:this.sessionMsgCache.get(i)??[];let o=t(a);o.length>mr.MAX_MESSAGES&&(o=o.slice(-500));let l=!1;return n&&(this.msgBuffers.set(e,o),this.evictIfNeeded(e),l=this.currentConvKey===e),i&&i!==mr.NEW_CHAT_ID&&(this.sessionMsgCache.set(i,o),this.touchSessionCache(i)),{displayChanged:l,newMessages:l?o:void 0}}applyLoadResult(e,t,i){const r=this.isCacheFresher(t,i);r||(this.sessionMsgCache.set(t,i),this.touchSessionCache(t));const n=this.getPhase(e),a=this.activeSession.get(e);if(this.currentConvKey===e&&(this.loadingSession===t||a===t)&&n!=="streaming"){const l=r?this.sessionMsgCache.get(t):i;return this.msgBuffers.set(e,l),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:l}}return{displayChanged:!1}}appendActivity(e,t,i){const r=i??e,n=[...this.actBuffers.get(r)??[],t];if(this.actBuffers.set(r,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.activeSession.get(e);return!i||!a||a===i?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.activeSession.get(e)}setActiveSession(e,t){this.activeSession.set(e,t)}saveToCache(e,t){if(!t||t===mr.NEW_CHAT_ID)return;const i=this.msgBuffers.get(e);i&&i.length>0&&(this.sessionMsgCache.set(t,i),this.touchSessionCache(t))}restoreFromCache(e,t){const i=this.sessionMsgCache.get(t);if(i&&i.length>0)return this.msgBuffers.set(e,i),i;this.msgBuffers.delete(e)}isCacheFresher(e,t){const i=this.sessionMsgCache.get(e);if(!i||i.length===0)return!1;if(i.length>t.length)return!0;const r=i.reduce((l,c)=>l+c.text.length,0),n=t.reduce((l,c)=>l+c.text.length,0);if(r>n)return!0;const a=i.reduce((l,c)=>l+(c.segments?.length??0),0),o=t.reduce((l,c)=>l+(c.segments?.length??0),0);return a>o}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const i=this.streamingSessions.get(e)??new Set;i.add(t),this.streamingSessions.set(e,i)}removeStreamSession(e,t){if(t){const i=this.streamingSessions.get(e);i&&(i.delete(t),i.size===0&&this.streamingSessions.delete(e))}else this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}getMessages(e){return this.msgBuffers.get(e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.msgBuffers.delete(e)}evictIfNeeded(e){if(this.msgBuffers.size<=mr.MAX_CONVERSATIONS)return;const t=[...this.msgBuffers.keys()],i=t.filter(r=>r!==e&&r!==this.currentConvKey).slice(0,t.length-mr.MAX_CONVERSATIONS);for(const r of i)this.msgBuffers.delete(r),this.actBuffers.delete(r),this.sessionTabs.delete(r),this.activeSession.delete(r)}touchSessionCache(e){const t=this.sessionCacheOrder.indexOf(e);for(t!==-1&&this.sessionCacheOrder.splice(t,1),this.sessionCacheOrder.push(e);this.sessionCacheOrder.length>mr.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 St=mr.NEW_CHAT_ID;function pM(s){const e=C.useRef(new mr),[t,i]=C.useState(s??[]),[r,n]=C.useState(!1),[a,o]=C.useState([]),l=C.useRef(null);C.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const c=C.useCallback((p,x,y)=>{const _=e.current.updateMessages(p,x,y);_.displayChanged&&_.newMessages&&i(_.newMessages)},[]),d=C.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const k=e.current.getMessages(p);k&&e.current.currentConvKey===p&&i([...k])}))},[]),u=C.useCallback((p,x,y)=>{const _=e.current.appendActivity(p,x,y);_.displayChanged&&_.newActivities&&o(_.newActivities)},[]),f=C.useCallback(p=>e.current.getPhase(p),[]),g=C.useCallback(p=>e.current.beginLoad(p),[]),b=C.useCallback(p=>e.current.beginStream(p),[]),v=C.useCallback(p=>e.current.endStream(p),[]),m=C.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=C.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const _=await y(),k=e.current.applyLoadResult(x,p,_.messages);return k.displayChanged&&k.newMessages&&i(k.newMessages),{count:_.messages.length,hasMore:_.hasMore,oldestCursor:_.oldestCursor}}catch{return e.current.currentConvKey===x&&e.current.getPhase(x)!=="streaming"&&(i([]),e.current.completeLoad(x)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:i,sending:r,setSending:n,activities:a,setActivities:o,get msgBuffers(){return e.current.msgBuffers},get sessionMsgCache(){return e.current.sessionMsgCache},get activeSessionBuffer(){return e.current.activeSession},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(p){e.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(p){e.current.loadingSession=p}}},updateConvMsgs:c,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:g,beginStream:b,endStream:v,resetConv:m,loadAndDisplay:O,incrementSending:p=>e.current.incrementSend(p),decrementSending:p=>e.current.decrementSend(p),resetSending:p=>e.current.resetSend(p),isSendingFor:p=>e.current.isSending(p),setStreamSession:(p,x)=>e.current.addStreamSession(p,x),clearStreamSession:(p,x)=>e.current.removeStreamSession(p,x),getStreamSession:p=>e.current.getStreamSessions(p),saveSessionToCache:(p,x)=>e.current.saveToCache(p,x),restoreSessionFromCache:(p,x)=>{const y=e.current.restoreFromCache(p,x);return i(y??[]),y},isSessionCacheFresherThanDb:(p,x)=>e.current.isCacheFresher(p,x)}}function mM({value:s,onSelect:e,disabled:t}){const{t:i}=Pt("team"),[r,n]=C.useState(!1),[a,o]=C.useState(!0),[l,c]=C.useState(""),[d,u]=C.useState(!1),[f,g]=C.useState([]),[b,v]=C.useState(null),m=C.useRef(null),O=C.useCallback(async()=>{u(!0);try{const w=await fetch("/api/settings/llm",{credentials:"include"});if(!w.ok)throw new Error(`HTTP ${w.status}`);const S=await w.json(),Q=S.providers?.markus;if(Q?.configured&&Q.enabled!==!1&&(!Q.models||Q.models.length===0))try{const j=await fetch("/api/models/live/markus",{credentials:"include"});if(j.ok){const B=await j.json();B.models?.length&&(Q.models=B.models)}}catch{}const I=[];for(const[j,B]of Object.entries(S.providers??{})){if(!B.configured||B.enabled===!1)continue;const F=(B.models??[]).map(V=>({id:V.id,name:V.name}));F.length!==0&&I.push({provider:j,displayName:B.displayName??j,models:F})}I.sort((j,B)=>j.displayName.localeCompare(B.displayName)),g(I);const D=j=>!j?.provider||!j.model?!1:!!I.find(F=>F.provider===j.provider)?.models.some(F=>F.id===j.model);let $=null;if(S.routingDefaultModel?.provider&&S.routingDefaultModel?.model)$={provider:S.routingDefaultModel.provider,model:S.routingDefaultModel.model};else if(S.defaultProvider){const j=S.providers?.[S.defaultProvider];j?.model&&($={provider:S.defaultProvider,model:j.model})}if($&&!D($)){const j=I.find(F=>F.provider==="markus"),B=j?.models[0]?{provider:"markus",model:j.models[0].id}:I[0]?.models[0]?{provider:I[0].provider,model:I[0].models[0].id}:null;B?($=B,J.settings.updateRouting({defaultProvider:B.provider,routingDefaultModel:B}).catch(()=>{})):$=null}v($)}catch{g([])}finally{u(!1)}},[]);C.useEffect(()=>{O()},[O]),C.useEffect(()=>{r&&(o(!0),c(""),O())},[r,O]),C.useEffect(()=>{if(!r)return;const w=S=>{m.current?.contains(S.target)||n(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[r]);const p=C.useMemo(()=>{const w=l.trim().toLowerCase();return f.map(S=>({...S,models:w?S.models.filter(Q=>Q.id.toLowerCase().includes(w)||(Q.name?.toLowerCase().includes(w)??!1)||S.displayName.toLowerCase().includes(w)||S.provider.toLowerCase().includes(w)):S.models})).filter(S=>S.models.length>0)},[f,l]),x=C.useCallback(w=>!w?.provider||!w.model?!1:f.length===0?!0:!!f.find(Q=>Q.provider===w.provider)?.models.some(Q=>Q.id===w.model),[f]);C.useEffect(()=>{if(!s||f.length===0||x(s))return;const w=b&&x(b)?b:(()=>{const S=f.find(Q=>Q.provider==="markus");return S?.models[0]?{provider:"markus",model:S.models[0].id}:f[0]?.models[0]?{provider:f[0].provider,model:f[0].models[0].id}:null})();w&&e(w,!1)},[s,f,b,x,e]);const y=s&&x(s)?s:b,k=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||i("chatModel.title",{defaultValue:"Model"});return h.jsxs("div",{ref:m,className:"relative shrink-0",children:[h.jsxs("button",{type:"button",disabled:t,onClick:()=>n(w=>!w),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:y?`${y.provider}: ${y.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[h.jsx("span",{className:"truncate",children:k}),h.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r&&h.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:[h.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[h.jsx("input",{autoFocus:!0,value:l,onChange:w=>c(w.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"}),h.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[h.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),h.jsx("button",{type:"button",role:"switch","aria-checked":a,onClick:()=>o(w=>!w),className:`relative w-9 h-5 rounded-full transition-colors ${a?"bg-brand-600":"bg-fg-tertiary/30"}`,children:h.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${a?"translate-x-4":""}`})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[d&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!d&&p.length===0&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!d&&p.map(w=>h.jsxs("div",{className:"mb-1",children:[h.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:w.displayName}),w.models.slice(0,80).map(S=>{const Q=y?.provider===w.provider&&y?.model===S.id;return h.jsxs("button",{type:"button",onClick:()=>{e({provider:w.provider,model:S.id},a),a&&v({provider:w.provider,model:S.id}),n(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[h.jsx("span",{className:"truncate flex-1",children:S.id}),Q&&h.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:h.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${w.provider}:${S.id}`)})]},w.provider))]})]})]})}async function gM(s,e,t){s&&!s.startsWith("new_")&&await J.sessions.setModelOverride(s,e),t&&await J.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const dx="markus_team_sidebars_c";function OM(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}const xM=["chat","overview","files","tools","memory","deliverables"],vM=["chat","overview","announcements","norms","settings"];function bM(s,e){if(s==="chat")return e("page.chatTitle");if(Rp.find(r=>r.key===s))return e(`agent:tabs.${s}`);const i=Ap.find(r=>r.key===s);return i?e(i.labelKey):s}function yM(s){if(s==="chat")return"💬";const e=Rp.find(i=>i.key===s);if(e)return e.icon;const t=Ap.find(i=>i.key===s);return t?t.icon:""}function cr(s){return s!=="chat"}const yf=new Set;function SM(){return window.location.hash}function _M(s){return yf.add(s),()=>{yf.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>yf.forEach(s=>s()));function NM({initialAgentId:s,authUser:e,previewMode:t,previewData:i}={}){const{t:r,i18n:n}=Pt(["team","common"]),a=C.useMemo(()=>({today:r("page.dateToday"),yesterday:r("page.dateYesterday")}),[r]),o=_f(Ht.TEAM),[l,c]=C.useState(i?.agents??[]),[d,u]=C.useState(i?.humans??[]),[f,g]=C.useState(!i),b=Sf(),v=C.useSyncExternalStore(_M,SM),m=b&&(v.startsWith(`#${Ht.TEAM}/`)||v.startsWith("#chat/")),O=b&&v.match(/^#team\/t\/(.+)$/),p=b?O?"team":m?"chat":"roster":"roster",x=O?O[1]:null,y=C.useRef(Ht.TEAM),_=C.useCallback(()=>{y.current=window.location.hash.slice(1)||Ht.TEAM,window.location.hash=`${Ht.TEAM}/d`},[]),k=C.useCallback(P=>{window.location.hash=`${Ht.TEAM}/t/${P}`},[]);C.useEffect(()=>{if(!b)return;const P=()=>{cr(Q.current)&&S("chat")};return window.addEventListener("popstate",P),()=>window.removeEventListener("popstate",P)},[b]);const[w,S]=C.useState("chat"),Q=C.useRef("chat");Q.current=w;const I=_m({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[D,$]=C.useState(()=>{try{return localStorage.getItem(dx)==="1"}catch{return!1}}),j=C.useCallback(P=>{$(P);try{localStorage.setItem(dx,P?"1":"0")}catch{}},[]),B=wf(),F=B?.leftCollapsed??!1,V=B?.rightPanel??null,Z=B?.rightPanelTabs??[],se=B?.activeRightPanelTabId??null,T=B?.rightPanelFullscreen??!1,A=V?"2xl:pr-8":"2xl:pr-[280px]",N=B?.setHostAvailable,z=B?.collapseRightPanelOnly??B?.toggleRightPanel,U=B?.openRightPanel,ne=400,Se=320,Pe=6,[X,M]=C.useState(typeof window<"u"?window.innerWidth:1440),[K,ie]=C.useState("auto"),oe=C.useRef(F);C.useEffect(()=>{oe.current!==F&&(oe.current=F,$(F))},[F]);const G=B?.keyboardPane??"content",$e=C.useRef(!1),Ie=C.useRef(G);C.useEffect(()=>{if(t||b||!o)return;const P=Ie.current;Ie.current=G,(G==="l1"||G==="l2")&&P!==G&&D&&($(!1),B?.setLeftCollapsed(!1))},[G,t,b,o,D,B]),C.useEffect(()=>{if(t||b||!o)return;const P=E=>{const R=B?.keyboardPane??"content";if(R==="l0"||R==="l1"||R==="l2"||E.metaKey||E.ctrlKey||E.altKey)return;if(E.target instanceof HTMLElement){const H=E.target.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||E.target.isContentEditable||E.target.closest(".xterm"))return}const q=E.key.length===1?E.key.toLowerCase():E.key;q!=="h"&&q!=="ArrowLeft"||(E.preventDefault(),D&&(j(!1),B?.setLeftCollapsed(!1)),B?.setKeyboardPane($e.current?"l2":"l1"))};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[t,b,o,B,D,j]),C.useEffect(()=>{if(N)return N(o&&!b),()=>N(!1)},[o,b,N]),C.useEffect(()=>t||b||!o?void 0:gt.on("ui:right_panel",E=>{const R=E.payload;if(R.action==="collapse"){z?.();return}if(R.action!=="open"||!R.panel||!U)return;const q=R.panel;if(q.kind==="url"&&q.url){const H=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;U({kind:"url",url:q.url,title:q.title||q.url,browserId:H});return}if(q.kind==="file"&&q.path){U({kind:"file",path:q.path,title:q.title});return}if(q.kind==="terminal"){const H=q.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;U({kind:"terminal",terminalId:H,title:q.title||"Terminal",cwd:q.cwd});return}q.kind==="deliverable"&&q.deliverableId&&J.deliverables.get(q.deliverableId).then(H=>{H.deliverable&&U({kind:"deliverable",deliverable:H.deliverable})}).catch(()=>{})}),[t,b,o,z,U]);const We=C.useCallback(P=>{const E=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Ai(R=>[...R,{id:E,...P}]),requestAnimationFrame(()=>sr.current?.focus())},[]),[Y,ee]=C.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),le=_m({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),ke=C.useRef(null),[Ce,dt]=C.useState(!1),[ht,yt]=C.useState(!1),ss=C.useCallback(()=>{Ce?yt(P=>!P):ee(P=>{const E=!P;try{localStorage.setItem("markus_team_panel_visible",String(E))}catch{}return E})},[Ce]);C.useEffect(()=>{if(b)return;const P=ke.current;if(!P)return;const E=new ResizeObserver(([R])=>{if(!R)return;const q=R.contentRect.width;if(M(q),!t){const H=q-I.width-le.width;dt(H<400)}});return E.observe(P),()=>E.disconnect()},[b,t,I.width,le.width]);const Lt=Y&&!Ce&&!ht,zs=D?0:I.width+Pe+(Lt?le.width+Pe:0),vs=Math.max(0,X-zs-Pe-8),bs=Math.min(ne,Math.floor(vs*.4)),si=Math.max(0,vs-bs),Zs=Math.min(Math.round(vs/2),si),xt=Math.max(0,Math.min(K==="auto"?Zs:K,si)),$i=C.useRef(!1);C.useEffect(()=>{const P=(B?.rightPanel??null)!==null;P&&!$i.current&&($(!0),ie("auto")),$i.current=P},[B?.rightPanel]);const ji=C.useRef(xt);ji.current=xt;const Ga=C.useRef(si);Ga.current=si;const gh=C.useCallback(P=>{P.preventDefault();const E=P.clientX,R=ji.current,q=fe=>{const me=R+(E-fe.clientX),be=Ga.current,te=Math.min(Se,be);ie(Math.max(te,Math.min(be,me)))},H=()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",H),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",q),document.addEventListener("mouseup",H),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);C.useEffect(()=>{if(!ht)return;const P=E=>{E.target.closest("[data-l2-floating]")||yt(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[ht]);const[Hr,Ji]=C.useState(null),[Ka,Po]=C.useState(),[To,Gr]=C.useState(),[ii,xi]=C.useState(!1),[Ja,Qo]=C.useState(""),[An,$o]=C.useState(!1),[Ei,Kr]=C.useState(""),Mn=C.useRef(null),ri=C.useRef(null),Tr=C.useCallback((P,E)=>{Po(P),Gr(E),b?(S("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):S(P??"overview")},[b]),Jr=[{id:"chat"},{id:"profile"}],jo=C.useCallback(P=>{P==="profile"?Tr():cr(Q.current)?history.back():S("chat")},[Tr]),ni=mx(Jr,w,jo),Ts=C.useCallback((P,E)=>{ut("direct"),is(P),b&&_(),Tr(E?.tab,E?.highlightMailboxId),Ji(null)},[b,_,Tr]),vi=C.useCallback((P,E)=>{const R=l.find(q=>q.name.toLowerCase()===P.toLowerCase());if(R){const q=E.target.getBoundingClientRect();Ji({agentId:R.id,top:q.bottom,left:q.left})}},[l]),Eo=C.useMemo(()=>l.map(P=>P.name),[l]),[ce,ut]=C.useState(()=>i?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,is]=C.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[lt,As]=C.useState(()=>i?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Nt,en]=C.useState(""),Ms=500,tn=C.useRef(new Set),Ln=P=>{if(tn.current.add(P),tn.current.size>Ms){const E=Math.floor(Ms*.2),R=tn.current.values();for(let q=0;q<E;q++){const H=R.next().value;H&&tn.current.delete(H)}}},Oh=C.useMemo(()=>{if(i?.channelMessages){const P=i.activeChannel??"custom:general";return i.channelMessages.filter(E=>E.channel===P).map(E=>xn(E))}},[]),{manager:el,messages:At,setMessages:Qs,sending:Vs,setSending:rs,activities:xh,setActivities:bi,msgBuffers:hs,sessionMsgCache:sn,activeSessionBuffer:ds,actBuffers:oi,sessionTabsBuffer:tl,currentConvKeyRef:Ve,updateConvMsgs:rt,updateConvMsgsRaf:er,appendConvActivity:rn,beginLoad:sl,beginStream:nn,endStream:ai,resetConv:Ri,loadAndDisplay:W,incrementSending:he,decrementSending:ue,resetSending:Re,isSendingFor:Fe,setStreamSession:tt,clearStreamSession:vt,getStreamSession:mt,saveSessionToCache:Ye,restoreSessionFromCache:Yt}=pM(Oh),[Dt,Ut]=C.useState(""),[Ls,Zt]=C.useState(null),[us,Ai]=C.useState([]),[Nn,Rt]=C.useState([]),ns=C.useRef(null),[vh,il]=C.useState(!!i?.streamLastMessage),on=C.useRef(null),H1=400;C.useEffect(()=>(Vs?(on.current&&(clearTimeout(on.current),on.current=null),il(!0)):vh&&(on.current=setTimeout(()=>{il(!1),on.current=null},H1)),()=>{on.current&&clearTimeout(on.current)}),[Vs]);const Mp=Vs||vh||(()=>{for(let P=At.length-1;P>=Math.max(0,At.length-8);P--){const E=At[P];if(E.isStreaming&&!E.isStopped)return!0}return!1})(),bh=C.useRef({fullText:"",timers:[]});C.useEffect(()=>{if(!t||!i?.streamLastMessage||At.length===0)return;const P=At[At.length-1];if(!P||P.sender!=="agent")return;const E=P.text;bh.current.fullText=E;const R=bh.current.timers;function q(){let fe=0;Qs(be=>be.map((te,de)=>de===be.length-1?{...te,text:""}:te)),il(!0);const me=setInterval(()=>{if(fe+=1+Math.floor(Math.random()*2),fe>=E.length){clearInterval(me),Qs(de=>de.map((st,Ue)=>Ue===de.length-1?{...st,text:E}:st));const be=setTimeout(()=>il(!1),800);R.push(be);const te=setTimeout(q,6e3);R.push(te)}else Qs(be=>be.map((te,de)=>de===be.length-1?{...te,text:E.slice(0,fe)}:te))},30);R.push(me)}const H=setTimeout(q,1500);return R.push(H),()=>{R.forEach(fe=>clearTimeout(fe)),bh.current.timers=[]}},[]);const Qr=C.useRef(0),[Lp,Mi]=C.useState(!1),[yh,Np]=C.useState(!1),[Dp,tr]=C.useState(!1),[Fs,Sh]=C.useState([]),[Ip,Bp]=C.useState(null),_h=C.useRef(null),sr=C.useRef(null),[rl,nl]=C.useState(null),$r=C.useRef(null),wh=C.useRef(!1),Ro=C.useCallback(()=>{const P=sr.current;if(!P)return;const E=wh.current,R=E?36:52,q=E?160:120;P.style.height="auto";const H=Math.max(R,Math.min(P.scrollHeight,q));P.style.height=`${H}px`,P.style.overflowY=H>=q?"auto":"hidden"},[]);C.useEffect(()=>{const P=requestAnimationFrame(()=>Ro());return()=>cancelAnimationFrame(P)},[Dt,Fs.length,Ro]);const kh=P=>{try{const E=localStorage.getItem(`markus_closed_tabs_${P}`);return E?new Set(JSON.parse(E)):new Set}catch{return new Set}},G1=(P,E)=>{const R=kh(P);R.add(E);try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...R]))}catch{}},K1=(P,E)=>{const R=kh(P);if(R.delete(E))try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...R]))}catch{}},J1=P=>{try{return localStorage.getItem(`markus_active_session_${P}`)}catch{return null}},ol=(P,E)=>{if(P)try{E&&E!==St?localStorage.setItem(`markus_active_session_${P}`,E):localStorage.removeItem(`markus_active_session_${P}`)}catch{}},[Ch,an]=C.useState([]),[it,Li]=C.useState(null),[ln,cn]=C.useState(!1),[Wp,Ph]=C.useState([]),[Ao,Th]=C.useState(null),[eS,Xp]=C.useState(null),[al,Qh]=C.useState([]),[Dn,$h]=C.useState(null),[tS,qp]=C.useState(null),[zp,jh]=C.useState([]),[Mo,sS]=C.useState([]),Ns=P=>{sS(E=>{const R=typeof P=="function"?P(E):P,q=new Set;return R.filter(H=>q.has(H.id)?!1:(q.add(H.id),!0))})},ll=C.useRef(null),Eh=C.useRef(null),yi=C.useRef(null),[ys,Lo]=C.useState(i?.groupChats??[]),Rh=C.useRef(ys);Rh.current=ys;const Zp=C.useRef(null),[No,fs]=C.useState(!1),[hn,Do]=C.useState(!1),[Vp,In]=C.useState(""),[Ah,jr]=C.useState([]),[Fp,Yp]=C.useState(!1),Mh=C.useRef(void 0),[Si,Up]=C.useState(i?.teams??[]),[iS,rS]=C.useState([]),[cl,Hp]=C.useState([]),[nS,oS]=C.useState(null),[wM,kM]=C.useState(!1),[CM,PM]=C.useState(""),[Gp,Io]=C.useState(!1),[Kp,aS]=C.useState(""),[Bo,Bn]=C.useState(0),[lS,cS]=C.useState([]),Jp=C.useRef(!1),hS=C.useCallback(()=>{Jp.current||(Jp.current=!0,(async()=>{const P=[];try{const[E,R,q,H,fe]=await Promise.all([J.projects.list().catch(()=>({projects:[]})),J.requirements.list().catch(()=>({requirements:[]})),J.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),J.deliverables.search({limit:100}).catch(()=>({results:[]})),J.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const me of E.projects)P.push({id:me.id,name:me.name,entityType:"project",role:me.status});for(const me of R.requirements)P.push({id:me.id,name:me.title,entityType:"requirement",role:me.priority});for(const me of q.tasks)P.push({id:me.id,name:me.title,entityType:"task",role:me.status});for(const me of H.results)P.push({id:me.id,name:me.title,entityType:"deliverable",role:me.type});for(const me of fe.teams)try{const be=await J.workflows.list(me.id);for(const te of be.workflows)P.push({id:te.name,name:te.displayName||te.name,entityType:"workflow",role:`v${te.version}`})}catch{}}catch{}cS(P)})())},[]),Vt=ce==="channel"?ys.find(P=>P.channelKey===lt)?.teamId:void 0,dS=C.useRef(null),Wn=C.useRef(null),Ss=C.useRef(null),em=C.useRef(void 0),hl=C.useRef(!1),ir=C.useRef(!0),tm=C.useRef(void 0);C.useEffect(()=>{if(!ln)return;const P=E=>{Eh.current&&!Eh.current.contains(E.target)&&ll.current&&!ll.current.contains(E.target)&&cn(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[ln]);const dl=(P,E)=>{if(!E||P===E)return`notes:${P}`;const[R,q]=[P,E].sort();return`dm:${R}:${q}`};C.useEffect(()=>{localStorage.setItem("markus_chat_mode",ce)},[ce]),C.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),C.useEffect(()=>{localStorage.setItem("markus_chat_channel",lt)},[lt]);const{counts:Lh,sessionAgentMap:Wo,markRead:Xo,setActiveKey:uS,clearActiveKey:fS}=a_({enabled:!t}),ul=C.useMemo(()=>{const P={};for(const[E,R]of Object.entries(Lh))E.startsWith("channel:")&&(P[E.slice(8)]=R);return P},[Lh]),Nh=l_(Wo,Lh);C.useEffect(()=>{let P=0;for(const E of Nh.values())P+=E;for(const E of Object.values(ul))P+=E;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:P}}))},[Nh,ul]);const fl=Nh,pS=C.useCallback(async P=>{for(const[E,R]of Object.entries(Wo))R===P&&Xo(`session:${E}`)},[Wo,Xo]);C.useEffect(()=>{if(t||!((!b||p==="chat")&&w==="chat"))return;if(ce==="direct"&&ge&&pS(ge),ce==="channel"&<)Xo(`channel:${lt}`);else if(ce==="direct"&&it)Xo(`session:${it}`);else if(ce==="dm"&&Nt){const R=`dm:${[e?.id,Nt].sort().join(":")}`;Xo(`channel:${R}`)}const E=[];if(ce==="direct"&&it){E.push(`session:${it}`);for(const[R,q]of Object.entries(Wo))q===ge&&E.push(`session:${R}`)}else ce==="channel"&<?E.push(`channel:${lt}`):ce==="dm"&&Nt&&e?.id&&E.push(`channel:dm:${[e.id,Nt].sort().join(":")}`);for(const R of E)uS(R);return()=>{for(const R of E)fS(R)}},[t,ce,lt,it,Nt,ge,p,w,Wo]);const li=C.useCallback(()=>J.agents.list().then(P=>c(P.agents)).catch(()=>{}),[]),Ys=C.useCallback(()=>J.teams.list().then(P=>Up(P.teams)).catch(()=>{}),[]),Xn=C.useCallback(()=>J.groupChats.list().then(P=>Lo(P.chats)).catch(()=>{}),[]),mS=C.useMemo(()=>ed(li,3e3),[li]),pl=C.useMemo(()=>ed(Ys,5e3),[Ys]),Dh=C.useMemo(()=>ed(Xn,3e3),[Xn]),qo=C.useCallback(()=>{J.users.list(e?.orgId).then(P=>u(P.users)).catch(()=>{})},[e?.orgId]);C.useEffect(()=>{t||(Promise.all([li(),Ys()]).finally(()=>g(!1)),qo(),J.tasks.list().then(P=>Hp(P.tasks)).catch(()=>{}),J.externalAgents.list().then(P=>rS(P.agents)).catch(()=>{}),Xn())},[t,qo]),C.useEffect(()=>{if(!(!t||!i)&&(c(i.agents??[]),u(i.humans??[]),Up(i.teams??[]),Lo(i.groupChats??[]),i.channelMessages)){const P=i.activeChannel??"custom:general";Qs(i.channelMessages.filter(E=>E.channel===P).map(E=>xn(E)))}},[t,i]),C.useEffect(()=>{if(t||!o)return;li(),Ys();const P=setInterval(li,3e4),E=setInterval(Ys,6e4),R=gt.on("agent:update",()=>{mS(),pl()}),q=gt.on("team:update",()=>{pl(),Dh()}),H=gt.on("agent:removed",pl),fe=gt.on("chat:group_created",()=>{Xn(),Ys(),li()}),me=gt.on("chat:group_updated",Dh),be=gt.on("chat:group_deleted",()=>{Dh(),pl()}),te=gt.on("task:update",st=>{const Ue=st?.payload;Ue?.taskId&&Hp(Xe=>Xe.map(Qe=>Qe.id===Ue.taskId?{...Qe,status:Ue.status??Qe.status}:Qe))}),de=()=>{li(),Ys(),qo()};return window.addEventListener("markus:data-changed",de),()=>{clearInterval(P),clearInterval(E),R(),q(),H(),fe(),me(),be(),te(),window.removeEventListener("markus:data-changed",de)}},[t,o,qo]),C.useEffect(()=>{if(t)return;const P=be=>{const te=be.detail;if(S_(te.page)===Ht.TEAM){if(te.params?.agentId){if(te.params.profileTab)Ts(te.params.agentId,{tab:te.params.profileTab});else if(ut("direct"),is(te.params.agentId),S("chat"),b&&_(),te.params.sessionId){const de=te.params.sessionId;setTimeout(async()=>{try{const{sessions:st}=await J.sessions.listByAgent(te.params.agentId,20),Ue=st.find(Xe=>Xe.id===de);Ue&&bl(Ue)}catch{}},300)}}if(te.params?.selectAgent&&(ut("direct"),is(te.params.selectAgent),S("chat"),b&&_()),te.params?.prefillMessage){const de=te.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),te.params?.autoSend==="true"?setTimeout(()=>em.current?.(de),300):(Ut(de),setTimeout(()=>{const st=sr.current;st&&(st.focus(),st.setSelectionRange(st.value.length,st.value.length))},100))}if(te.params?.dm&&(ut("dm"),en(te.params.dm),S("chat"),b&&_()),te.params?.channel&&(ut("channel"),As(te.params.channel),S("chat"),b&&_()),te.params?.selectTeam){const de=te.params.selectTeam;if(b)k(de);else{const st=Rh.current.find(Ue=>Ue.type==="team"&&Ue.teamId===de);ut("channel"),As(st?.channelKey??`group:${de}`),S("chat"),fs(!1),ee(!0)}}te.params?.openHire}},E=localStorage.getItem("markus_nav_agentId");if(E){localStorage.removeItem("markus_nav_agentId");const be=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),ut("direct"),is(E),be?Ts(E,{tab:be}):(S("chat"),b&&_())}const R=localStorage.getItem("markus_nav_dm");R&&(localStorage.removeItem("markus_nav_dm"),ut("dm"),en(R),S("chat"),b&&_());const q=localStorage.getItem("markus_nav_channel");q&&(localStorage.removeItem("markus_nav_channel"),ut("channel"),As(q),S("chat"),b&&_());const H=localStorage.getItem("markus_nav_prefillMessage");H&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),Ut(H),setTimeout(()=>{const be=sr.current;be&&(be.focus(),be.setSelectionRange(be.value.length,be.value.length))},150));const fe=localStorage.getItem("markus_nav_selectAgent");fe&&(localStorage.removeItem("markus_nav_selectAgent"),ut("direct"),is(fe),S("chat"),b&&_());const me=localStorage.getItem("markus_nav_selectTeam");if(me)if(localStorage.removeItem("markus_nav_selectTeam"),b)k(me);else{const be=Rh.current.find(te=>te.type==="team"&&te.teamId===me);ut("channel"),As(be?.channelKey??`group:${me}`),S("chat"),fs(!1),ee(!0)}return window.addEventListener("markus:navigate",P),()=>window.removeEventListener("markus:navigate",P)},[t]),C.useEffect(()=>{const P=Zp.current;if(!P)return;const E=ys.find(R=>R.type==="team"&&R.teamId===P);Zp.current=null,ut("channel"),As(E?.channelKey??`group:${P}`),S("chat"),fs(!1),ee(!0)},[ys,Si]),C.useEffect(()=>{if(t&&i?.chatMode==="channel"||l.length===0||ge&&l.some(E=>E.id===ge))return;const P=l.find(E=>!E.teamId&&E.role?.toLowerCase()==="secretary")??l.find(E=>E.role?.toLowerCase()==="secretary")??l.find(E=>E.name?.toLowerCase().includes("secretary"));P?(ut("direct"),is(P.id),S("chat")):l.length>0&&(ut("direct"),is(l[0].id),S("chat"))},[l,ge]);const qn=C.useRef(!1),Ni=C.useRef(!1),ml=C.useRef(!1),gl=C.useRef(0),zn=C.useRef(0),[gS,rr]=C.useState(!1),Er=C.useRef(0),[sm,dn]=C.useState(0),nr=C.useCallback(()=>{Ni.current=!1,ml.current=!1,ir.current=!0},[]),Ih=C.useCallback(()=>{Ni.current=!0,ir.current=!1,zn.current+=1,qn.current=!1,rr(!0)},[]),un=C.useCallback(P=>{const E=Wn.current;if(!E)return;const R=E.scrollHeight-E.scrollTop-E.clientHeight,q=R<160,H=R<48,fe=gl.current,me=E.scrollTop<fe-2;if(gl.current=E.scrollTop,me&&R>20){ml.current=!0,Ih();return}if(ml.current){H?(nr(),rr(!1),Er.current=0,dn(0)):Ih();return}if(q&&!Ni.current){nr(),rr(!1),Er.current=0,dn(0);return}P?.fromProgrammatic||qn.current||!Ni.current&&ir.current||Ni.current&&(ir.current=!1,rr(!0))},[Ih,nr]);C.useEffect(()=>{const P=Wn.current;if(!P)return;const E=()=>{ml.current=!0},R=()=>{un({fromProgrammatic:qn.current})};P.addEventListener("wheel",E,{passive:!0}),P.addEventListener("touchmove",E,{passive:!0}),P.addEventListener("scroll",R,{passive:!0});const q=typeof ResizeObserver<"u"?new ResizeObserver(()=>un()):null;return q?.observe(P),gl.current=P.scrollTop,un(),()=>{P.removeEventListener("wheel",E),P.removeEventListener("touchmove",E),P.removeEventListener("scroll",R),q?.disconnect()}},[p,un]);const Bh=C.useMemo(()=>new Set(zp),[zp]),os=C.useMemo(()=>{const P=ce==="channel"?At:At.filter(E=>!E.isActivityLog);return Bh.size===0?P:P.filter(E=>!(E.isNotification&&Bh.has(E.id)))},[At,ce,Bh]);C.useEffect(()=>{wh.current=w==="chat"&&os.length>0,Ro()},[w,os.length,Ro]);const or=N_({count:os.length,getScrollElement:()=>Wn.current,getItemKey:P=>os[P]?.id??P,estimateSize:P=>{const E=os[P];return E?E.segments&&E.segments.length>0?300:E.text.length>500?200:120:120},overscan:8});or.shouldAdjustScrollPositionOnItemSizeChange=(P,E,R)=>wm()?!1:P.start<(R.scrollOffset??0);const Zn=C.useCallback((P="instant")=>{if(!ir.current||Ni.current)return;const E=++zn.current;qn.current=!0;const R=()=>E===zn.current&&ir.current&&!Ni.current,q=()=>{if(E!==zn.current)return;if(qn.current=!1,!R()){un();return}const H=Wn.current;H&&(gl.current=H.scrollTop,H.scrollHeight-H.scrollTop-H.clientHeight<160&&!Ni.current&&(nr(),rr(!1),Er.current=0,dn(0))),requestAnimationFrame(()=>{E===zn.current&&un({fromProgrammatic:!0})})};if(os.length>0)or.scrollToIndex(os.length-1,{align:"end",behavior:P}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R()){E===zn.current&&(qn.current=!1);return}or.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(q)})});else{const H=Wn.current;H&&H.scrollTo({top:H.scrollHeight,behavior:P}),requestAnimationFrame(q)}},[os.length,or,un,nr]),im=C.useRef(o);C.useEffect(()=>{im.current=o},[o]),C.useLayoutEffect(()=>{if(hl.current){hl.current=!1;const P=xl.current;P>0&&(xl.current=0,or.scrollToIndex(P,{align:"start",behavior:"instant"}));return}im.current&&(!ir.current||Ni.current||wm()||Zn())},[At,Zn,or]);const rm=C.useRef(w);C.useEffect(()=>{const P=rm.current!=="chat";if(rm.current=w,w==="chat"&&P&&ir.current&&!Ni.current){const E=[],R=requestAnimationFrame(()=>Zn("instant"));for(const q of[60,160,320])E.push(setTimeout(()=>Zn("instant"),q));return()=>{cancelAnimationFrame(R);for(const q of E)clearTimeout(q)}}},[w,Vs,Zn]);const nm=C.useCallback(async(P,E)=>{const R=E??`ch:${P}`;Ve.current===R&&tr(!0);try{const q=await J.channels.getMessages(P,50),H=q.messages.map(fe=>xn(fe,e?.id));hs.set(R,H),Ve.current===R&&(Qs(H),Mi(q.hasMore),yi.current=q.messages[0]?new Date(q.messages[0].createdAt).toISOString():null)}catch{Ve.current===R&&(Qs([]),Mi(!1))}finally{Ve.current===R&&tr(!1)}},[]),Wh=C.useCallback(async(P,E)=>{const R=Ve.current===E&&(hs.get(E)?.length??0)===0;R&&tr(!0);try{const{count:q,hasMore:H,oldestCursor:fe}=await W(P,E,async()=>{const me=await J.sessions.getMessages(P,50);return{messages:c_(me.messages.map(td).filter(te=>te.sender!=="agent"||te.text||te.segments&&te.segments.length>0||te.isStreaming)),hasMore:me.hasMore,oldestCursor:me.messages[0]?new Date(me.messages[0].createdAt).toISOString():null}});return Mi(H),yi.current=fe,q}finally{R&&Ve.current===E&&tr(!1)}},[W,hs]),om=C.useRef(new Map),fn=C.useCallback(async(P,E,R)=>{if(!P||!E||E===St)return;let q=null;try{if(Ss.current&&!Ss.current.signal.aborted&&mt(R)?.has(E)){nn(R),Ve.current===R&&rs(!0);return}const H=`${P}:${E}`,fe=om.current.get(H)??0;if(Date.now()-fe<1500)return;const me=await J.sessions.streamStatus(P,E),te=[...hs.get(R)??[]].reverse().find(Oe=>Oe.sender==="agent"),de=me.status==="streaming",st=!!me.active&&(me.status==="done"||me.status==="error")&&!!te?.isStreaming;if(!de&&!st)return;om.current.set(H,Date.now()),$r.current?.abort(),q=new AbortController,$r.current=q,nn(R),rs(!0),tt(R,E);let Ue=te?.id;if(!te||te.isError)Ue=`reattach_${Date.now()}`,rt(R,Oe=>[...Oe,{id:Ue,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],E);else{const Oe=(te.segments??[]).filter(Be=>Be.type==="tool").map(Be=>Be.status==="stopped"||Be.status==="running"?{...Be,status:"running"}:Be);rt(R,Be=>Be.map(we=>we.id===te.id?{...we,text:"",isStreaming:!0,isStopped:!1,segments:Oe,committedSegments:void 0}:we),E)}let Xe=!1;const Qe=Oe=>{Ve.current===R&&(Qr.current=Date.now(),er(R,Be=>{const we=[...Be],Le=Ue?we.findIndex(pe=>pe.id===Ue):-1,Me=Le>=0?Le:we.map((pe,xe)=>({m:pe,j:xe})).reverse().find(pe=>pe.m.sender==="agent")?.j??-1;if(Me<0)return Be;const De=we[Me].segments??[],et=De[De.length-1],Ct=et?.type==="text"?et.thinking??"":"";let Xt="",$s="",ae=Oe;for(;ae.length>0;)if(Xe){const pe=ae.indexOf("</think>");pe>=0?(Xt+=ae.slice(0,pe),ae=ae.slice(pe+8),Xe=!1):(Xt+=ae,ae="")}else{const pe=ae.indexOf("<think>");pe>=0?($s+=ae.slice(0,pe),ae=ae.slice(pe+7),Xe=!0):($s+=ae,ae="")}const Ze=Ct+Xt||void 0,ye=et?.type==="text"?[...De.slice(0,-1),{type:"text",content:et.content+$s,thinking:Ze,createdAt:et.createdAt}]:[...De,{type:"text",content:$s,thinking:Ze,createdAt:new Date().toISOString()}];return we[Me]={...we[Me],text:(we[Me].text??"")+$s,segments:ye,isStreaming:!0},we},E))},ct=Oe=>{if(Ve.current===R&&(Qr.current=Date.now(),Oe.phase!=="heartbeat")){if((Oe.phase==="start"||Oe.phase==="end")&&rn(R,{...Oe,phase:Oe.phase,ts:Date.now()},E),Oe.phase==="start"){const Be=`${Oe.tool}_${Date.now()}`,we=new Date().toISOString(),Le=Me=>{const De=[...Me];for(let et=De.length-1;et>=0;et--){const Ct=De[et];if(Ct.type==="tool"&&Ct.tool===Oe.tool&&(Ct.status==="running"||Ct.status==="stopped"))return De[et]={...Ct,status:"running",args:Oe.arguments??Ct.args},De}return De.push({type:"tool",key:Be,tool:Oe.tool,status:"running",args:Oe.arguments,createdAt:we}),De};rt(R,Me=>{const De=[...Me],et=Ue?De.findIndex(ae=>ae.id===Ue):-1;if(et<0)return Me;const Ct=Le(De[et].segments??[]),Xt=De[et].committedSegments,$s=Xt&&Le(Xt);return De[et]={...De[et],segments:Ct,committedSegments:$s,isStreaming:!0},De},E)}else if(Oe.phase==="end"){const Be=new Date().toISOString(),we=Le=>{const Me=[...Le];for(let De=Me.length-1;De>=0;De--){const et=Me[De];if(et.type==="tool"&&et.tool===Oe.tool&&(et.status==="running"||et.status==="stopped")){Me[De]={...et,status:Oe.success===!1?"error":"done",args:Oe.arguments??et.args,result:Oe.result,error:Oe.error,durationMs:Oe.durationMs,liveOutput:void 0,createdAt:Be};break}}return Me};rt(R,Le=>{const Me=[...Le],De=Ue?Me.findIndex($s=>$s.id===Ue):-1;if(De<0)return Le;const et=we(Me[De].segments??[]),Ct=Me[De].committedSegments,Xt=Ct&&we(Ct);return Me[De]={...Me[De],segments:et,committedSegments:Xt,isStreaming:!0},Me},E)}else if(Oe.phase==="subagent_progress"&&Oe.subagentEvent){const Be=we=>{const Le=[...we];for(let Me=Le.length-1;Me>=0;Me--){const De=Le[Me];if(De.type==="tool"&&(De.tool==="spawn_subagent"||De.tool==="spawn_subagents")&&(De.status==="running"||De.status==="stopped")){Le[Me]={...De,status:"running",subagentLogs:km(De.subagentLogs,Oe.subagentEvent)};break}}return Le};er(R,we=>{const Le=[...we],Me=Ue?Le.findIndex(Xt=>Xt.id===Ue):-1;if(Me<0)return we;const De=Be(Le[Me].segments??[]),et=Le[Me].committedSegments,Ct=et&&Be(et);return Le[Me]={...Le[Me],segments:De,committedSegments:Ct,isStreaming:!0},Le},E)}}},Ne=Oe=>{Ve.current===R&&(Qr.current=Date.now(),rt(R,Be=>{const we=[...Be],Le=Ue?we.findIndex(De=>De.id===Ue):-1;if(Le<0)return Be;const Me=[...we[Le].committedSegments??[]];if(Oe.type==="thinking_commit")Me.push({type:"text",content:"",thinking:Oe.content,createdAt:Oe.createdAt});else if(Oe.type==="text_commit")Me.push({type:"text",content:Oe.content,createdAt:Oe.createdAt});else return Be;return we[Le]={...we[Le],committedSegments:Me,isStreaming:!0},we},E))},Ke=Oe=>{if(Ve.current!==R)return;Qr.current=Date.now();const Be=(Oe.segments??[]).map((we,Le)=>we.type==="tool"?{type:"tool",key:`${we.tool}_${Le}`,tool:we.tool??"tool",status:we.status==="error"?"error":we.status==="running"||we.status==="stopped"?"running":"done",args:we.arguments,result:we.result,error:we.error,durationMs:we.durationMs,createdAt:we.createdAt,...we.subagentLogs?.length?{subagentLogs:we.subagentLogs}:{}}:{type:"text",content:we.content??"",thinking:we.thinking,createdAt:we.createdAt});rt(R,we=>{const Le=[...we],Me=Ue?Le.findIndex(De=>De.id===Ue):-1;return Me<0?we:(Le[Me]={...Le[Me],text:Oe.content||Le[Me].text,segments:Be,committedSegments:Be,isStreaming:!0,isStopped:!1},Le)},E);for(const we of Be)we.type==="tool"&&rn(R,{tool:we.tool,phase:we.status==="running"||we.status==="stopped"?"start":"end",success:we.status!=="error",arguments:we.args,result:we.result,error:we.error,durationMs:we.durationMs,ts:Date.now()},E)},Je=await J.sessions.reattachStream(P,E,{onChunk:Qe,onActivity:ct,onCommit:Ne,onSnapshot:Ke},q.signal,0);if(!Je.attached){ai(R),Ve.current===R&&(rt(R,Oe=>{const Be=[...Oe],we=Ue?Be.findIndex(De=>De.id===Ue):-1,Le=we>=0?we:Be.map((De,et)=>({m:De,j:et})).reverse().find(De=>De.m.sender==="agent"&&De.m.isStreaming)?.j??-1;if(Le<0)return Oe;const Me=Be[Le];return Me.isStreaming?(Be[Le]={...Me,isStreaming:!1,isStopped:Me.isError?Me.isStopped:!0},Be):Oe},E),rs(!1));return}Ve.current===R&&(rt(R,Oe=>{const Be=[...Oe],we=Ue?Be.findIndex(et=>et.id===Ue):-1,Le=we>=0?we:Be.map((et,Ct)=>({m:et,j:Ct})).reverse().find(et=>et.m.sender==="agent")?.j??-1;if(Le<0)return Oe;const Me=Be[Le],De=Je.segments?.length?Cm(Je.segments,Me.segments):void 0;return Be[Le]={...Me,text:Je.content||Me.text,isStreaming:!1,isStopped:!1,...De?{segments:De,committedSegments:De}:{}},Be},E),rs(!1)),ai(R),$r.current===q&&($r.current=null)}catch(H){if($r.current===q&&($r.current=null),ai(R),Ve.current===R&&rs(!1),H instanceof Error&&H.name==="AbortError")return}},[rn,nn,ai,mt,hs,tt,rt,er]);C.useEffect(()=>{if(!o||t||ce!=="direct"||!ge)return;const P=it;!P||P===St||fn(ge,P,Ve.current)},[o,t,ce,ge,it,fn]);const Ol=C.useCallback(async P=>{if(!P)return an([]),[];try{const{sessions:E}=await J.sessions.listByAgent(P,10);return an(E),E}catch{return an([]),[]}},[]),xl=C.useRef(0),OS=C.useCallback(async()=>{if(!(yh||!Lp||!yi.current)){Np(!0);try{const P=Ve.current;if(ce==="channel"||ce==="dm"){const E=ce==="dm"?dl(e?.id??"",Nt):lt,R=await J.channels.getMessages(E,50,yi.current),q=R.messages.map(H=>xn(H,e?.id));xl.current=q.length,hl.current=!0,Qs(H=>{let fe=[...q,...H];return fe.length>500&&(fe=fe.slice(-500)),hs.set(P,fe),fe}),Mi(R.hasMore),R.messages[0]&&(yi.current=new Date(R.messages[0].createdAt).toISOString())}else if(it){const E=await J.sessions.getMessages(it,50,yi.current),R=E.messages.map(td);xl.current=R.length,hl.current=!0,Qs(q=>{let H=[...R,...q];return H.length>500&&(H=H.slice(-500)),hs.set(P,H),H}),Mi(E.hasMore),E.messages[0]&&(yi.current=new Date(E.messages[0].createdAt).toISOString())}}catch{}finally{Np(!1)}}},[yh,Lp,ce,lt,it,e?.id,Nt]);tm.current=OS;const Xh=C.useRef(!1),xS=C.useCallback(P=>{Xh.current||(Xh.current=!0,requestAnimationFrame(()=>{Xh.current=!1,P.target.scrollTop<100&&tm.current?.()}))},[]);C.useEffect(()=>{if(t)return;const P=Kl(ce,ge,lt,Nt),E=Ve.current;Ve.current=P,E&&E!==P&&(tl.set(E,Mo),it&&ds.set(E,it)),E!==P&&(nr(),rr(!1),Er.current=0,dn(0));const R=hs.get(P),q=tl.get(P),H=ds.get(P),fe=mt(P),me=H??it,be=Fe(P)&&(ce!=="direct"||!fe||!me||fe.has(me)),te=me??P,de=oi.get(te)??[];if(bi(be?de:[]),rs(be),ce==="direct"&&ge&&Ol(ge),q&&q.length>0&&Ns(q),cn(!1),R!==void 0&&R.length>0)if(be||el.completeLoad(P),tr(!1),Qs(R),Mi(!1),H!==void 0&&Li(H),(!q||q.length===0)&&Ns([]),ce==="channel"||ce==="dm"){const Ue=ce==="dm"?dl(e?.id??"",Nt):lt;nm(Ue,P)}else ce==="direct"&&ge&&H&&H!==St&&(be?fn(ge,H,P):Wh(H,P).then(()=>{Ve.current===P&&ge&&fn(ge,H,P)}));else if(sl(P),tr(!0),Qs([]),Mi(!1),yi.current=null,hs.delete(P),ce==="channel"||ce==="dm"){const Ue=ce==="dm"?dl(e?.id??"",Nt):lt;nm(Ue,P),(!q||q.length===0)&&Ns([])}else ce==="direct"&&ge?Ol(ge).then(Ue=>{if(Ve.current===P)if(Ue.length>0){const Xe=Ue.find(Le=>Le.isMain),Qe=kh(ge),ct=Xe?[Xe,...Ue.filter(Le=>!Le.isMain&&!Qe.has(Le.id)).slice(0,4)]:Ue.filter(Le=>!Qe.has(Le.id)).slice(0,5);let Ne=q&&q.length>0?q:ct;const Ke=J1(ge),Je=H!==void 0?H:Ke??Xe?.id??Ne[0].id;if(Je&&Je!==St&&!Ne.some(Le=>Le.id===Je)){const Le=Ue.find(Me=>Me.id===Je);Le&&(Ne=[...Ne,Le])}const Oe=Je&&Ne.some(Le=>Le.id===Je)?Je:Ne[0].id;Li(Oe),ds.set(P,Oe),ol(ge,Oe),Ns(Ne);const we=Ue.find(Le=>Le.id===Oe)?.metadata?.modelOverride;nl(we?.provider&&we?.model?{provider:we.provider,model:we.model}:null),Wh(Oe,P).then(()=>{Ve.current===P&&ge&&fn(ge,Oe,P)})}else Li(null),nl(null),tr(!1),(!q||q.length===0)&&Ns([])}).catch(()=>{Ve.current===P&&tr(!1)}):tr(!1)},[t,ce,ge,lt,Nt,n.language,r]),C.useEffect(()=>t?void 0:gt.on("chat:message",E=>{const R=E.payload,q=R.channel??"";if(!q)return;const H=R.senderType??"agent",fe=R.text??R.message??"",me=R.senderId??R.agentId??"",be=R.senderName??R.agentId??r("page.fallbackAgent"),te=R.metadata,de=R.messageId??R.id??"";if(de&&tn.current.has(de))return;const st=H==="human"&&me===(e?.id??""),Ue={id:de||`ws_${Date.now()}_${me}`,sender:st?"user":"agent",text:fe,time:new Date().toLocaleTimeString(),agentName:st?void 0:be,agentId:st?void 0:me,replyToId:R.replyToId??void 0,replyToSender:R.replyToSender??void 0,replyToText:R.replyToText??void 0};if(te&&H==="agent"){const Qe=[];if(te.thinking?.length&&Qe.push({type:"text",content:"",thinking:te.thinking.join(`
|
|
73
73
|
|
|
74
74
|
`)}),te.toolCalls?.length)for(let ct=0;ct<te.toolCalls.length;ct++){const Ne=te.toolCalls[ct];Qe.push({type:"tool",key:`${Ne.tool}_${ct}`,tool:Ne.tool,status:Ne.status==="error"?"error":"done",args:Ne.arguments,result:Ne.result,durationMs:Ne.durationMs})}Qe.length>0&&(Qe.push({type:"text",content:fe}),Ue.segments=Qe)}let Xe;if(q.startsWith("notes:"))Xe=`dm:${q.slice(6)}`;else if(q.startsWith("dm:")){const Qe=q.slice(3).split(":");Xe=`dm:${Qe.find(Ne=>Ne!==(e?.id??""))??Qe[0]??""}`}else Xe=`ch:${q}`;rt(Xe,Qe=>[...Qe,Ue]),Xe===Ve.current&&!ir.current&&(Er.current+=1,dn(Er.current),rr(!0)),H==="agent"&&Xe===`ch:${lt}`&&Rt(Qe=>{const ct=Qe.filter(Ne=>Ne.id!==me);return ct.length===0&&ns.current&&(clearTimeout(ns.current),ns.current=null),ct})}),[t,rt,e?.id,lt]),C.useEffect(()=>t?void 0:gt.on("chat:agent_no_response",E=>{const R=E.payload,q=R.channel??"",H=R.agentId??"";q&&H&&`ch:${lt}`==`ch:${q}`&&Rt(fe=>{const me=fe.filter(be=>be.id!==H);return me.length===0&&ns.current&&(clearTimeout(ns.current),ns.current=null),me})}),[t,lt]),C.useEffect(()=>t?void 0:gt.on("chat:proactive_message",E=>{const R=E.payload,q=R.targetUserId;if(q&&q!==e?.id)return;const H=R.agentId??"",fe=R.agentName??r("page.fallbackAgent"),me=R.message??"",be=R.sessionId??"",te=R.messageId??"",de=R.metadata??{};if(!H||!me||me==="[cancelled]"||me==="[Stream cancelled]")return;const st=de.role==="user",Ue=!st&&(!!de.activityLog||me.startsWith("[ACTIVITY:")),{cleaned:Xe,priority:Qe}=h_(me),ct=!st&&(!!de.notifyUser||Xe!==me),Ne=Kl("direct",H,"","");if(be&&Ve.current===Ne){const De=it;if(De&&De!==St&&De!==be)return}const Ke=!!de.isMainSession&&!st,Je=be||it,Oe=typeof de.userText=="string"?de.userText:"",Be=typeof de.userMessageId=="string"?de.userMessageId:"",we=typeof de.createdAt=="string"&&de.createdAt||(typeof E.timestamp=="string"?E.timestamp:void 0)||new Date().toISOString(),Le=(()=>{try{return new Date(we).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Me={id:te||`proactive_${Date.now()}`,sender:st?"user":"agent",text:Xe,time:Le,rawCreatedAt:we,...st?{}:{agentName:fe,agentId:H,...ct?{isNotification:!0,notifyPriority:de.priority??Qe}:{},...Ue?{isActivityLog:!0,activityType:de.activityType,outcome:de.outcome,mailboxItemId:de.mailboxItemId,taskId:de.taskId,requirementId:de.requirementId}:{},...!Ue&&de.taskId?{taskId:de.taskId}:{},...!Ue&&de.requirementId?{requirementId:de.requirementId}:{}}};ct&&Me.id&&jh(De=>De.includes(Me.id)?De:[...De,Me.id]),rt(Ne,De=>{if(De.some(Ct=>Ct.id===Me.id))return De;let et=De;if(!st&&Oe&&(et.some(Xt=>Be&&Xt.id===Be||Xt.sender==="user"&&Xt.text===Oe)||(et=[...et,{id:Be||`feishu_user_${Me.id}`,sender:"user",text:Oe,time:new Date().toLocaleTimeString()}])),Ke)for(let Ct=et.length-1;Ct>=0;Ct--){const Xt=et[Ct];if(Xt.sender==="agent"&&Xt.agentId===H&&Xt.isStopped){const $s=[...et];return $s[Ct]={...Me,id:Xt.id},$s}}return d_(et,Me)},Je||void 0)}),[t,rt,r,it]),cl.find(P=>P.id===nS),C.useEffect(()=>{oS(null)},[ge]);const vS=P=>w_(P),bS=()=>{const P=ce==="direct"?ge:null;P&&J.agents.cancelProcessing(P).catch(()=>{}),Ss.current?.abort(),Ss.current=null,$r.current?.abort(),$r.current=null;const E=Ve.current;Re(E),oi.delete(it??E),it&&vt(E,it),ai(E),rs(!1),bi([])},[pn,qh]=C.useState(null),[am,lm]=C.useState(!1),cm=C.useRef(null),mn=async(P,E)=>{const R=!P&&us.length>0?us.map(Xe=>Xe.content).join(`
|
|
75
75
|
|