@markus-global/cli 0.11.3-rc.0 → 0.11.3
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-C-niUbUY.js → CommentInput-DN3Cichs.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-DxsnJJRX.js → ContentRenderer-CjHOyYgJ.js} +2 -2
- package/dist/web-ui/assets/{DeliverableShareModal-DV3TiZx0.js → DeliverableShareModal-CBSvxB-X.js} +1 -1
- package/dist/web-ui/assets/{Deliverables-tlLsJnxZ.js → Deliverables-BaAF4-w0.js} +1 -1
- package/dist/web-ui/assets/{Notifications-4KXYRdkr.js → Notifications-CCsdBfdg.js} +1 -1
- package/dist/web-ui/assets/{Search-CPFwZv1U.js → Search-BiBdevAU.js} +1 -1
- package/dist/web-ui/assets/{Settings-DIa-_qre.js → Settings-CawBnWuy.js} +1 -1
- package/dist/web-ui/assets/{Store-JWjwXfTU.js → Store-BWi97VP9.js} +1 -1
- package/dist/web-ui/assets/{Team-COBxn96h.js → Team-CfUDkdc3.js} +4 -4
- package/dist/web-ui/assets/{Work-BScJUqWL.js → Work-DrIXOW-P.js} +1 -1
- package/dist/web-ui/assets/{arc-DPZmpo1U.js → arc-Cg0-C295.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DlOs02JO.js → architectureDiagram-3BPJPVTR-BctEHNLp.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-C7qsXNUe.js → blockDiagram-GPEHLZMM-hxr2ZwOV.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-Drwp-rtM.js → c4Diagram-AAUBKEIU-CfIRo1GE.js} +1 -1
- package/dist/web-ui/assets/channel-DAQ2Rbxq.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-VgR09Mqk.js → chunk-2J33WTMH-T0bENsqX.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-CuwDpBRL.js → chunk-4BX2VUAB-ChLLkyYx.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-nC7YWJ_i.js → chunk-55IACEB6-BD3ENYp9.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-Dw6mBsRE.js → chunk-727SXJPM-BAes4atE.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-CPhNJbHl.js → chunk-AQP2D5EJ-FymM7gfT.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-AyhQakG8.js → chunk-FMBD7UC4-N5sRT0m9.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-DgYemv8I.js → chunk-ND2GUHAM-BSjS3JyS.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-CLdqxrFB.js → chunk-QZHKN3VN-Dkwitdbr.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DrOgwDIH.js → cose-bilkent-S5V4N54A-BLuYATCK.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-DhoJiA83.js → dagre-BM42HDAG-DGLiqiH2.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-BDILSgqK.js → diagram-2AECGRRQ-Cq_GnNKs.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-CeXywd1i.js → diagram-5GNKFQAL-CHNz-2dA.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-Bi4RlMT0.js → diagram-KO2AKTUF-D8eKa7jh.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-Cw1yxk8b.js → diagram-LMA3HP47-RkDgQcLr.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-Bl857da2.js → diagram-OG6HWLK6-LqxQrIwa.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-CjoUhrMq.js → docx-preview-Be-Qo_ag.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DEiaMhuV.js → erDiagram-TEJ5UH35-BX0zZgYQ.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BgKZhO0h.js → flowDiagram-I6XJVG4X-DKnfIFA4.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-Dkx-EaS8.js → ganttDiagram-6RSMTGT7-DjBURmY-.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DXaQwA0y.js → gitGraphDiagram-PVQCEYII-BvSi7SvS.js} +1 -1
- package/dist/web-ui/assets/{index-C_QhfMcC.js → index-D8vskks7.js} +5 -5
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-Dpx9IOkx.js → infoDiagram-5YYISTIA-CwtIgim2.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BWqWgitQ.js → ishikawaDiagram-YF4QCWOH-CWhXJfSa.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BBwIZ4k9.js → journeyDiagram-JHISSGLW-DN9rorlL.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-C_MRWV8R.js → kanban-definition-UN3LZRKU-Burf5FE8.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-BMAh3nnq.js → mermaid.core-Dx4rzlyC.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-B6vJQcat.js → mindmap-definition-RKZ34NQL-DqZ21Siw.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-BxdEttqt.js → pieDiagram-4H26LBE5-C_4ksu-T.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-gsNs2VfP.js → quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-BSC9KvC2.js → requirementDiagram-4Y6WPE33-CzmWi02d.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-DktAZfe_.js → sankeyDiagram-5OEKKPKP-D8K7e8we.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-BIPt8kGU.js → sequenceDiagram-3UESZ5HK-1z9rqtVx.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DiXmJWB0.js → stateDiagram-AJRCARHV-nneYkkHa.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-LRi7H35g.js → timeline-definition-PNZ67QCA-D6GmLlRi.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-DWQ1I022.js → vennDiagram-CIIHVFJN-TVefhiCa.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BUb6dYqN.js → wardley-L42UT6IY-BgUuAeiM.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-BYE1B3xT.js → wardleyDiagram-YWT4CUSO-CyJ_l94o.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-D-pS2-Sa.js → xychartDiagram-2RQKCTM6-kajbbx7a.js} +1 -1
- package/dist/web-ui/index.html +1 -1
- package/package.json +1 -1
- package/dist/web-ui/assets/channel-DCChB-1T.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-CrNiYfSI.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-CrNiYfSI.js +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-COOgTXIX.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 S,k as Dm,u as Mt,B as jv,j as c,q as Eo,a2 as Im,a3 as Bm,a4 as Ek,a as Wm,b as Xm,P as es,c as Ih,l as te,w as St,M as Ak,A as Ms,n as jr,F as qo,i as zm,a5 as Mk,a6 as Lk,a7 as Nk,a8 as Dk,a9 as Ik,aa as OO,ab as nc,o as xO,O as Bk,D as Wk,h as qm,d as Rv,ac as Ev,ad as sh,ae as Xk,af as bO,ag as zk,W as qk,Y as Av,X as Mv,H as Zk,ah as Vk,ai as Fk,_ as Lv,aj as Uk,ak as rh,al as Hk,am as ru,an as Yk,ao as vO,ap as yO,aq as SO,ar as ka,as as wO,at as Gk,au as _O,av as Nn,aw as Lc,ax as Nc,ay as kO,az as Kk,aA as Jk,aB as eC,aC as tC,m as CO,aD as PO,aE as sC,aF as rC,aG as iu,aH as TO,aI as nu,aJ as ou,aK as iC,C as au,aL as lu,aM as nC,aN as oc,aO as QO,aP as oC,aQ as aC,aR as lC,aS as $O,aT as cC,aU as hC,aV as dC,aW as uC,aX as fC,aY as mC,aZ as pC,a_ as gC,a$ as jO,b0 as OC,b1 as xC,p as bC,b2 as vC,b3 as yC,b4 as SC,b5 as wC}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D8vskks7.js","assets/index-DEN_qReg.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as S,k as Dm,u as Mt,B as jv,j as c,q as Eo,a2 as Im,a3 as Bm,a4 as Ek,a as Wm,b as Xm,P as es,c as Ih,l as te,w as St,M as Ak,A as Ms,n as jr,F as qo,i as zm,a5 as Mk,a6 as Lk,a7 as Nk,a8 as Dk,a9 as Ik,aa as OO,ab as nc,o as xO,O as Bk,D as Wk,h as qm,d as Rv,ac as Ev,ad as sh,ae as Xk,af as bO,ag as zk,W as qk,Y as Av,X as Mv,H as Zk,ah as Vk,ai as Fk,_ as Lv,aj as Uk,ak as rh,al as Hk,am as ru,an as Yk,ao as vO,ap as yO,aq as SO,ar as ka,as as wO,at as Gk,au as _O,av as Nn,aw as Lc,ax as Nc,ay as kO,az as Kk,aA as Jk,aB as eC,aC as tC,m as CO,aD as PO,aE as sC,aF as rC,aG as iu,aH as TO,aI as nu,aJ as ou,aK as iC,C as au,aL as lu,aM as nC,aN as oc,aO as QO,aP as oC,aQ as aC,aR as lC,aS as $O,aT as cC,aU as hC,aV as dC,aW as uC,aX as fC,aY as mC,aZ as pC,a_ as gC,a$ as jO,b0 as OC,b1 as xC,p as bC,b2 as vC,b3 as yC,b4 as SC,b5 as wC}from"./index-D8vskks7.js";import{p as _C,r as RO}from"./CommentInput-DN3Cichs.js";import{ContentRenderer as wf,resolveFormat as kC}from"./ContentRenderer-CjHOyYgJ.js";import{a as CC,c as PC,D as TC}from"./DeliverableShareModal-CBSvxB-X.js";import{i as QC}from"./modelCapabilities-DDtCBZ6o.js";function fo(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
|
|
3
3
|
font-size: .6rem;
|
|
4
4
|
font-weight: bold;
|
|
5
5
|
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function EO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const $C=(s,e)=>Math.abs(s-e)<1.01,jC=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},AO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},RC=s=>s,EC=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),r=[];for(let i=e;i<=t;i++)r.push(i);return r},AC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;const i=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(i(AO(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const h=l.borderBoxSize[0];if(h){i({width:h.inlineSize,height:h.blockSize});return}}i(AO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},MO={passive:!0},LO=typeof window>"u"?!0:"onscrollend"in window,MC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&LO?()=>{}:jC(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;i=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,MO);const h=s.options.useScrollendEvent&&LO;return h&&t.addEventListener("scrollend",l,MO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},LC=(s,e,t)=>{if(e?.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},NC=(s,{adjustments:e=0,behavior:t},r)=>{var i,n;const a=s+e;(n=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||n.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:t})};class DC{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,r,i;return((i=(r=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let t=null;const r=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),t=null},observe:i=>{var n;return(n=r())==null?void 0:n.observe(i,{box:"border-box"})},unobserve:i=>{var n;return(n=r())==null?void 0:n.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([r,i])=>{typeof i>"u"&&delete t[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:RC,rangeExtractor:EC,onChange:()=>{},measureElement:LC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,t)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,r)=>{const i=new Map,n=new Map;for(let a=r-1;a>=0;a--){const o=t[a];if(i.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&i.set(o.lane,!0),i.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,r,i,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const p of this.laneAssignments.keys())p>=t&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let p=0;p<d;p++){const v=u[p];v&&(f[v.lane]=p)}for(let p=d;p<t;p++){const v=n(p),b=this.laneAssignments.get(p);let g,O;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const C=f[g],P=C!==void 0?u[C]:void 0;O=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?u[p-1]:this.getFurthestMeasurement(u,p);O=C?C.end+this.options.gap:r+i,g=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),_=O+y;u[p]={index:p,start:O,size:y,end:_,key:v,lane:g},f[g]=p}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?IC({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let t=null,r=null;const i=this.calculateRange();return i&&(t=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,r]},(t,r,i,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const r=this.options.indexAttribute,i=t.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,i-n),o=Math.min(this.options.count-1,i+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const r=this.indexFromElement(t),i=this.options.getItemKey(r),n=this.elementsCache.get(i);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,r)=>{var i;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=r-a;o!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,r)),this.notify(!1))},this.getVirtualItems=fo(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,r)=>{const i=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=r[o];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const r=this.getMeasurements();if(r.length!==0)return EO(r[Nv(0,r.length-1,i=>EO(r[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,r,i=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=t>=a+n?"end":"start"),r==="center"?t+=(i-n)/2:r==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,r="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const i=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(r==="auto")if(a.end>=n+i-this.options.scrollPaddingEnd)r="end";else if(a.start<=n+this.options.scrollPaddingStart)r="start";else return[n,r];if(r==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),r];const o=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,r,a.size),r]},this.scrollToOffset=(t,{align:r="start",behavior:i="auto"}={})=>{const n=this.getOffsetForAlignment(t,r),a=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:r="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,r);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:i,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:n,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=r[r.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&n.some(o=>o===null);){const o=r[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}i=Math.max(...n.filter(o=>o!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:r,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,n=1,a=i!==this.scrollState.lastTargetOffset;if(!a&&$C(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Nv=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function IC({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=Nv(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(d=>d>=t);){const d=s[a];h[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const NO=typeof document<"u"?S.useLayoutEffect:S.useEffect;function BC({useFlushSync:s=!0,...e}){const t=S.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Dm.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=S.useState(()=>new DC(r));return i.setOptions(r),NO(()=>i._didMount(),[]),NO(()=>i._willUpdate()),i}function WC(s){return BC({observeElementRect:AC,observeElementOffset:MC,scrollToFn:NC,...s})}function XC({approval:s,submitting:e,readOnly:t,onClose:r,onDecision:i}){const{t:n}=Mt(["team","common"]);jv(!0);const[a,o]=S.useState(""),l=typeof s.details?.command=="string"?s.details.command:"",h=typeof s.details?.toolName=="string"?s.details.toolName:"",d=u=>{t||e||i(u,a.trim()||void 0)};return Dm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:u=>{u.target===u.currentTarget&&r()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/15 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug break-words",children:s.title||n("team:toolApproval.defaultTitle",{defaultValue:"Tool execution needs approval"})}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[c.jsxs("p",{className:"text-xs text-fg-tertiary",children:[s.agentName,h?` · ${h}`:""]}),t&&c.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/15 text-green-600",children:[c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})}),n("team:toolApproval.resolved",{defaultValue:"Resolved"})]})]})]}),c.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[c.jsx("p",{className:"text-sm text-fg-secondary leading-relaxed",children:n("team:toolApproval.lead",{defaultValue:"The agent is paused until you approve or reject this action."})}),s.description&&c.jsx("div",{className:"text-xs text-fg-secondary leading-relaxed [&_p]:my-0 [&_p]:text-xs",children:c.jsx(Eo,{content:s.description.replace(/\s*Command:[\s\S]*$/,""),className:"text-xs [&_p]:text-xs [&_li]:text-xs"})}),l&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("div",{className:"text-[11px] font-medium text-fg-tertiary uppercase tracking-wide",children:n("team:toolApproval.commandLabel",{defaultValue:"Command"})}),c.jsx("pre",{className:"text-xs text-fg-primary bg-surface-overlay border border-border-default rounded-xl px-3 py-2.5 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed",children:l})]}),!t&&c.jsx("textarea",{rows:2,value:a,onChange:u=>o(u.target.value),placeholder:n("team:toolApproval.commentPlaceholder",{defaultValue:"Optional note (e.g. why you reject)…"}),className:"w-full px-3.5 py-2.5 text-sm bg-surface-overlay border border-border-default rounded-xl text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50 resize-y"})]}),c.jsx("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:t?c.jsx("button",{onClick:r,className:"px-5 py-2 text-sm font-medium text-fg-secondary border border-border-default rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:close",{defaultValue:"Close"})}):c.jsxs(c.Fragment,{children:[c.jsxs("button",{disabled:e,onClick:()=>d(!1),className:"px-5 py-2 text-sm font-medium bg-red-600/85 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]}),n("common:reject",{defaultValue:"Reject"})]}),c.jsxs("button",{disabled:e,onClick:()=>d(!0),className:"px-5 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-2",children:[e&&c.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n("common:approve",{defaultValue:"Approve"})]})]})})]})}),document.body)}const DO={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 zC({notification:s,agentName:e,acknowledging:t,index:r=0,total:i=1,onClose:n,onAcknowledge:a}){const{t:o,i18n:l}=Mt(["team","common"]);jv(!0);const h=Im(s.createdAt,o),d=Bm(s.createdAt,l.language),u=s.priority||"normal",f=s.metadata??{},p=e||(typeof f.agentName=="string"?f.agentName:void 0),v=i>1,b=r>=i-1,g=Math.max(0,i-r-1);return Dm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:O=>{O.target===O.currentTarget&&n()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[p&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:p}),u!=="normal"&&c.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${DO[u]??DO.normal}`,children:u}),v&&c.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface-overlay text-fg-secondary tabular-nums",children:o("page.notifyReviewProgress",{ns:"team",defaultValue:"{{current}} / {{total}}",current:r+1,total:i})}),(h||d)&&c.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-fg-tertiary tabular-nums",title:d,children:[c.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("path",{d:"M12 7v5l3 2"})]}),h,h&&d&&c.jsx("span",{className:"text-fg-muted",children:"·"}),d]})]})]}),c.jsx("button",{onClick:n,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:o("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),v&&c.jsx("div",{className:"h-0.5 w-full bg-surface-overlay shrink-0",children:c.jsx("div",{className:"h-full bg-blue-500 transition-[width] duration-200",style:{width:`${(r+1)/i*100}%`}})}),c.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:c.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:c.jsx(Eo,{content:s.body||""})})}),c.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[c.jsx("button",{onClick:n,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:o("common:close")}),c.jsx("button",{onClick:()=>{a()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?o("common:loading"):b?o("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"}):o("page.notifyReviewNext",{ns:"team",defaultValue:"Next",count:g})})]})]})}),document.body)}const Dv=12,cu=400,qC=4,ZC=350;function Iv(s){return Math.max(0,s.scrollHeight-s.clientHeight)}function IO(s){return Iv(s)>1}function Dc(s){return Iv(s)-s.scrollTop}function VC(s){return Dc(s)<=Dv}function FC(s,e){return Math.abs(e)<=Math.abs(s)?"none":e<0?"up":e>0?"down":"none"}const UC=new Set(["ArrowUp","PageUp","Home"]),HC=new Set(["ArrowDown","PageDown","End"]);function YC(s){return UC.has(s)?"up":HC.has(s)?"down":"none"}function GC(s,e){return s==null?"none":e>s+1?"up":e<s-1?"down":"none"}function KC(s){return s.scrollable?s.takeover?s.gestureDirection==="up"||s.intentPending?"hold":s.distance<=Dv?"resume":"hold":s.gestureDirection==="up"&&s.gestureActive||!s.programmatic&&s.deltaScrollTop<-4?"handover":"follow":s.takeover?"resume":"follow"}function JC(s){return!s.takeover&&!s.gestureActive}function e2(s,e){return e&&s==="up"}function mo(s,e){return`${s||"_"}::${e??""}`}function t2(s,e){let t=null;for(const r of s)r.start>e+1||(!t||r.start>t.start)&&(t=r);return t??s[0]??null}function BO(s,e){if(VC(e))return{kind:"bottom"};const t=t2(s,e.scrollTop);return t?{kind:"row",id:t.id,delta:e.scrollTop-t.start}:{kind:"bottom"}}function s2(s,e){return s+e}const r2=12;function WO(s,e=r2){return{kind:"row",id:s,delta:-e}}function hu(s){const e=s.getBoundingClientRect().top,t=s.scrollTop,r=[];for(const i of Array.from(s.querySelectorAll("[data-index]"))){const a=i.querySelector('[id^="msg-"]')?.id?.slice(4);a&&r.push({id:a,start:t+(i.getBoundingClientRect().top-e)})}return r.sort((i,n)=>i.start-n.start),r}function i2(s,e,t,r){const i=s.find(n=>n.id===t);return i?s2(i.start-e.scrollTop,r):null}class n2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(e)for(this.entries.delete(e),this.entries.set(e,t);this.entries.size>this.capacity;){const r=this.entries.keys().next();if(r.done)break;this.entries.delete(r.value)}}get(e){if(!e)return null;const t=this.entries.get(e);return t?(this.entries.delete(e),this.entries.set(e,t),t):null}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const XO=new n2,zO={jump:3,prepend:2,restore:1};function o2(s,e){return!s||s.key!==e.key?!0:zO[e.priority]>=zO[s.priority]}const a2=1e4,qO=300;function l2(s,e){return e-s>a2}function ZO(s,e){return s&&e===!0}function c2(s){return s.rendered?s.stable?"apply":"refine":s.stale?s.priority==="restore"?"release-bottom":"release-hold":!s.absent||s.canLoadMore?"keep":s.priority==="restore"?"release-bottom":"release-hold"}function du(s){return s!=="prepend"}function h2(s,e){return!s||s.mode!=="direct"||e.chatMode!=="direct"||!s.sessionId&&!s.preferMain?!1:!!s.agentId&&s.agentId===e.agentId}function Ha({children:s,onClose:e,title:t,width:r="w-[440px]"}){return c.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:c.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[c.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function wo({label:s,children:e}){return c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function d2({onClose:s,onCreate:e}){const{t}=Mt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("");return c.jsx(Ha,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(wo,{label:t("team:modals.createTeam.teamName"),children:c.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),c.jsx(wo,{label:t("team:modals.createTeam.description"),children:c.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),c.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:c.jsx(Ek,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:c.jsx("span",{className:"text-brand-400 font-medium"}),1:c.jsx("span",{className:"text-brand-400"})}})}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function u2({onClose:s,onAdd:e}){const{t}=Mt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("member"),[o,l]=S.useState(""),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(!1),O=p?.inviteToken?`${window.location.origin}/#invite?token=${p.inviteToken}`:null,m=async()=>{if(d(""),!r.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(r.trim(),n,o.trim());v({...y,userName:r.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),g(!0),setTimeout(()=>g(!1),2e3))};return p?c.jsxs(Ha,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[c.jsxs("div",{className:"text-center py-4",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:p.userName})}),O?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),c.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),c.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),c.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${b?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(b?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):c.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),c.jsx("div",{className:"flex justify-end pt-3",children:c.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):c.jsx(Ha,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[c.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),c.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",c.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),c.jsx(wo,{label:t("team:modals.addHuman.name"),children:c.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),c.jsx(wo,{label:t("team:modals.addHuman.role"),children:c.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[c.jsx("option",{value:"owner",children:t("common:role.owner")}),c.jsx("option",{value:"admin",children:t("common:role.admin")}),c.jsx("option",{value:"member",children:t("common:role.member")}),c.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),c.jsx(wo,{label:t("team:modals.addHuman.emailRequired"),children:c.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),h&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:m,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function f2({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=Mt(["team","common"]);return c.jsx(Ha,{onClose:t,title:i("team:modals.addExisting.title"),children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?c.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):c.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>c.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[c.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),c.jsxs("div",{className:"flex-1",children:[c.jsx("div",{className:"font-medium text-sm",children:n.name}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&c.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),c.jsx("div",{className:"flex justify-end pt-2",children:c.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function m2({onClose:s,onConnected:e}){const{t}=Mt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState(""),[o,l]=S.useState(!1),[h,d]=S.useState(null),[u,f]=S.useState(null),p=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const g=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!g.ok){const m=await g.json().catch(()=>({}));throw new Error(m.error??`HTTP ${g.status}`)}const O=await g.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(g){a(String(g))}l(!1)},v=(b,g)=>{navigator.clipboard.writeText(b),f(g),setTimeout(()=>f(null),2e3)};return c.jsx(Ha,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:h?(()=>{const b=h.gatewayUrl??`${window.location.origin}/api/gateway`,g=h.token?t("team:modals.openClaw.bearerTokenLine",{token:h.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:h.externalAgentId,tokenSection:g});return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-center py-6",children:[c.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),c.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),c.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:c.jsx("strong",{children:r})})]}),c.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),c.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),c.jsx("div",{className:"flex justify-end pt-5",children:c.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),c.jsxs("div",{className:"space-y-4",children:[c.jsx(wo,{label:t("team:modals.openClaw.agentName"),children:c.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:p,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}function Bv(s){return`group:${s}`}function p2(s){const{chatMode:e,agentTeamId:t,channelTeamId:r,knownTeamIds:i}=s,n=e==="direct"?t:e==="channel"?r:null;return n&&(i instanceof Set?i.has(n):Array.from(i).includes(n))?`team/t/${n}`:"team"}class g2{listeners=new Set;streamingAgents=new Set;streamingVersion=0;markAgentStreaming(e,t){if(!e)return;const r=this.streamingAgents.has(e);t&&!r?(this.streamingAgents.add(e),this.streamingVersion++,this.emit()):!t&&r&&(this.streamingAgents.delete(e),this.streamingVersion++,this.emit())}clearAgentStreaming(e){e&&this.streamingAgents.delete(e)&&(this.streamingVersion++,this.emit())}getStreamingAgents(){return this.streamingAgents}isAgentStreaming(e){return!!e&&this.streamingAgents.has(e)}getStreamingVersion(){return this.streamingVersion}emit(){for(const e of this.listeners)e()}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}const Ks=new g2;function Zm(s){const e=s??(t=>t);return S.useSyncExternalStore(Ks.subscribe,()=>e(Ks.getStreamingVersion()))}function O2(s){return Zm(()=>Ks.isAgentStreaming(s))}function x2(s,e){return s&&typeof s.tokensUsedToday=="number"&&Number.isFinite(s.tokensUsedToday)?s.tokensUsedToday:typeof e=="number"&&Number.isFinite(e)?e:0}function b2(s){return s?s.filter(e=>e&&typeof e.size=="number"&&e.size>0).slice().sort((e,t)=>t.size-e.size||e.name.localeCompare(t.name)):[]}const v2=new Set(["workspace","sessions","tool-outputs","daily-logs","role","subagent-logs","worktrees"]);function y2(s){return v2.has(s)?`agent:profilePage.overview.storageBuckets.${s}`:null}const _f={idle:{tone:"ok",dotClass:"bg-green-400",running:!0,chipClass:"bg-green-500/10 border border-green-500/20",textClass:"text-green-600",labelKey:"common:status.idle"},working:{tone:"busy",dotClass:"bg-blue-400 animate-pulse",running:!0,chipClass:"bg-blue-500/10 border border-blue-500/20",textClass:"text-blue-500",labelKey:"common:status.working"},error:{tone:"danger",dotClass:"bg-red-400 animate-pulse",running:!0,chipClass:"bg-red-500/10 border border-red-500/20",textClass:"text-red-500",labelKey:"common:status.error"},paused:{tone:"warn",dotClass:"bg-amber-400",running:!1,chipClass:"bg-amber-500/10 border border-amber-500/20",textClass:"text-amber-600",labelKey:"common:status.paused"},offline:{tone:"muted",dotClass:"bg-gray-400",running:!1,chipClass:"bg-gray-500/10 border border-border-default",textClass:"text-fg-tertiary",labelKey:"common:status.offline"}};function Bh(s){const e=s?_f[s]:void 0;return e||{..._f.offline,labelKey:null}}const S2=_f.working;function Wh(s,e){const t=Bh(s);return!e||!t.running||t.tone==="danger"||t.tone==="busy"?t:S2}const w2=5;function VO(s,e=w2){const t=Array.isArray(s)?s:[];return{shown:t.slice().sort((i,n)=>Date.parse(n.startedAt)-Date.parse(i.startedAt)).slice(0,Math.max(0,e)),total:t.length}}const _2=100;function k2(s){const e=Array.isArray(s)?s:[];return{heartbeats:e.filter(t=>t.type==="heartbeat"),comms:e.filter(t=>t.type==="a2a")}}const Vm=["files","mind","recent","tools","memory","usage"],C2=Vm[0];function FO(s,e){return e?"mind":Vm.find(r=>r===s)??C2}function P2(s){return s?"right-panel":"page"}let ac=new Map;function T2({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=Mt(["team","common"]),[a,o]=S.useState(""),[l,h]=S.useState(new Set),[d,u]=S.useState(""),[f,p]=S.useState(!1),v=S.useMemo(()=>{const m=[];for(const x of s)m.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&m.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return m},[s,e,t]),b=S.useMemo(()=>{if(!d)return v;const m=d.toLowerCase();return v.filter(x=>x.name.toLowerCase().includes(m)||x.subtitle.toLowerCase().includes(m))},[v,d]),g=m=>{h(x=>{const y=new Set(x);return y.has(m)?y.delete(m):y.add(m),y})},O=async()=>{if(!a.trim()||l.size===0)return;p(!0);const m=[...l],x={},y={};for(const _ of m){const C=v.find(P=>P.id===_);C&&(x[_]=C.type,y[_]=C.name)}await i(a.trim(),m,x,y),p(!1)};return c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),c.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:c.jsx("input",{value:a,onChange:m=>o(m.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),c.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:c.jsx("input",{value:d,onChange:m=>u(m.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&c.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(m=>c.jsxs("button",{onClick:()=>g(m.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(m.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(m.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(m.id)&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx(Ms,{name:m.name,size:20,bgClass:m.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate text-[11px] font-medium block",children:m.name}),c.jsx("span",{className:"text-[9px] text-fg-tertiary",children:m.subtitle})]}),c.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${m.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:m.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},m.id))]}),c.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),c.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const Q2=S.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:h,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:p,onSelectDm:v,onSelectTeam:b,selectedTeamId:g,onRefreshTeams:O,onRefreshAgents:m,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:_,onManageGroupMembers:C,unreadByAgent:P,unreadByChannel:k,width:T,onResizeStart:N,hidden:R,onCollapse:A,initialLoading:E,previewMode:I,focused:H,l2Available:q}){const{t:D}=Mt(["team","common"]),ne=Wm(),j=Xm(es.TEAM),X=Ih(),z=e?.role==="owner"||e?.role==="admin",B=S.useMemo(()=>new Set(a.map(Z=>Z.markusAgentId).filter(Boolean)),[a]);Zm(()=>Ks.getStreamingVersion());const U=Ks.getStreamingAgents(),[se,G]=S.useState([]),[he,V]=S.useState(new Set),[M,re]=S.useState(!1),[Y,ee]=S.useState(!1),[K,Ce]=S.useState(null),[Re,Te]=S.useState(!1),[Oe,we]=S.useState(!1),[Ve,lt]=S.useState(null),[Xe,Qe]=S.useState(null),[oe,Ke]=S.useState(null),[nt,Ot]=S.useState(!1),[Wt,At]=S.useState(""),[vt,je]=S.useState(null),[Pt,Ps]=S.useState(null),[pt,_t]=S.useState(null),[Je,ht]=S.useState(!1),st=S.useRef(null),[bt,$t]=S.useState(null),Tt=S.useRef(null),xt=S.useRef(null),[le,ae]=S.useState(null),Me=(Z,pe="success")=>{ae({message:Z,type:pe}),setTimeout(()=>ae(null),3e3)},[fe,be]=S.useState(null),[_e,Ne]=S.useState(!1),Fe=S.useRef(!1);S.useEffect(()=>{if(I)return;te.governance.getSystemStatus().then(xe=>{Fe.current=!0,be(xe.globalPaused)}).catch(()=>{Fe.current=!0,be(!1)});const Z=St.on("system:pause-all",()=>{Fe.current&&be(!0)}),pe=St.on("system:resume-all",()=>{Fe.current&&be(!1)});return()=>{Z(),pe()}},[]),S.useEffect(()=>{if(!I)return;const Z=setTimeout(()=>{const pe=xt.current,xe=Tt.current;pe&&xe&&xe.scrollTo({top:pe.offsetTop-xe.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(Z)},[I]);const J=S.useCallback(()=>{fe!==null&&ye({title:D(fe?"modals.resumeAll.title":"modals.pauseAll.title"),message:D(fe?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:D(fe?"chat.resume":"chat.pause"),onConfirm:async()=>{Ne(!0);try{fe?(await te.governance.resumeAll(),be(!1)):(await te.governance.pauseAll(),be(!0))}catch{}Ne(!1)}})},[fe]),[ve,ye]=S.useState(null),ge=(Z,pe,xe,De,Ze)=>{ye({title:Z,message:pe,onConfirm:xe,confirmLabel:De,checkboxes:Ze})},[ke,ze]=S.useState(null),[Ge,kt]=S.useState(null),ot=S.useRef(null),ft=S.useRef(null),[mt,Un]=S.useState(!1),[od,ni]=S.useState(null),[sr,Yo]=S.useState(""),oi=S.useCallback((Z,pe=176,xe=220)=>{const De=window.innerWidth,Ze=window.innerHeight,He=8;let gt=Z.clientX,yt=Z.clientY;return gt+pe>De-He&&(gt=Math.max(He,De-pe-He)),yt+xe>Ze-He&&(yt=Math.max(He,Ze-xe-He)),gt=Math.max(He,Math.min(gt,De-pe-He)),yt=Math.max(He,Math.min(yt,Ze-xe-He)),{x:gt,y:yt}},[]),[de,jt]=S.useState(ac),Se=S.useMemo(()=>t.map(Z=>Z.id).sort().join(","),[t]);S.useEffect(()=>{if(!t.length||!j)return;let Z=!1;(async()=>{const yt=[];await Promise.allSettled(t.map(async rt=>{if(!ac.has(rt.id))try{const{sessions:Jt}=await te.sessions.listByAgent(rt.id,1);if(!Jt.length)return;const{messages:ps}=await te.sessions.getMessages(Jt[0].id,1);if(ps.length){const gs=ps[0],rr=gs.metadata?.segments;let Dr=gs.content;if(rr&&rr.length>0){const Qt=[...rr].reverse().find($s=>$s.type==="text");Qt&&Qt.type==="text"&&(Dr=Qt.content)}const kr=Dr.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);kr&&yt.push([rt.id,kr])}}catch{}})),!Z&&yt.length&&jt(rt=>{const Jt=new Map(rt);for(const[ps,gs]of yt)Jt.set(ps,gs);return ac=Jt,Jt})})();const xe=new Set(t.map(yt=>yt.id)),De=yt=>Mk(yt).replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ze=(yt,rt)=>{if(!yt||!rt||!xe.has(yt))return;const Jt=De(rt);Jt&&jt(ps=>{const gs=new Map(ps);return gs.set(yt,Jt),ac=gs,gs})},He=St.on("chat:proactive_message",yt=>{const rt=yt.payload;Ze(rt.agentId??"",rt.message??"")}),gt=St.on("chat:message",yt=>{const rt=yt.payload,Jt=rt.senderId??rt.agentId??"",ps=rt.text??rt.message??"";Ze(Jt,ps)});return()=>{Z=!0,He(),gt()}},[Se,j]);const Ht=S.useCallback(()=>{I||te.teams.list().then(Z=>G(Z.ungrouped)).catch(()=>{})},[I]);S.useEffect(()=>{Ht()},[Ht]),S.useEffect(()=>{if(!j)return;const Z=St.on("team:update",Ht),pe=St.on("agent:removed",Ht);return()=>{Z(),pe()}},[Ht,j]),S.useEffect(()=>{if(!Xe&&!oe&&!vt&&!Je&&!pt)return;const Z=()=>{Qe(null),Ke(null),je(null),_t(null),ht(!1)},pe=setTimeout(()=>document.addEventListener("click",Z),0);return()=>{clearTimeout(pe),document.removeEventListener("click",Z)}},[Xe,oe,vt,Je,pt]);const ct=(Z,pe)=>{ge(`${D("common:delete")} "${pe}"?`,D("modals.deleteTeam.message"),async xe=>{const De=xe?.deleteMembers??!0,Ze=xe?.purgeFiles??!1;await te.teams.delete(Z,De,{purgeFiles:Ze}),O(),Ht(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},D("contextMenu.deleteTeam"),[{id:"deleteMembers",label:D("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:D("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Ts=async(Z,pe)=>{try{const De=await(pe==="start"?te.teams.startAll:te.teams.stopAll)(Z),Ze=De.success?.length??0,He=De.failed?.length??0;He>0?Me(D("batchAction.failed",{action:D(`batchAction.operation.${pe}`),ok:Ze,fail:He}),"error"):Ze>0&&Me(D("batchAction.succeeded",{count:Ze,action:D(`batchAction.past.${pe}`)}),"success"),m()}catch(xe){Me(D("batchAction.failedToRun",{action:D(`batchAction.operation.${pe}`),error:xe instanceof Error?xe.message:String(xe)}),"error")}},zt=async(Z,pe,xe)=>{await te.teams.update(Z,{managerId:pe,managerType:xe}),O()},$i=async Z=>{if(!sr.trim()){ni(null);return}await te.teams.update(Z,{name:sr.trim()}),ni(null),O()},Go=async(Z,pe)=>{pe==="offline"?await te.agents.start(Z):await te.agents.stop(Z),m()},dn=(Z,pe)=>{ge(D("modals.removeFromTeam.title"),D("modals.removeFromTeam.message"),async()=>{await te.teams.removeMember(Z,pe),O(),Ht()},D("common:remove"))},Ql=(Z,pe,xe,De)=>{ge(`${D("common:remove")} "${pe}"?`,D(xe==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ze=>{if(xe==="agent"&&De){const He=o.find(gt=>gt.type==="team"&>.teamId===De);He?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+He.channelKey)}if(xe==="agent"){const He=Ze?.purgeFiles??!1;await te.agents.remove(Z,{purgeFiles:He})}else await te.users.remove(Z);m(),O(),x?.(),Ht(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},D("common:remove"),xe==="agent"?[{id:"purgeFiles",label:D("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},$l=Z=>{if(Z.isOrgSecretary||Z.protected)return!0;if(Z.teamId)return!1;const pe=(Z.role??"").toLowerCase().trim(),xe=(Z.name??"").trim();return xe==="Secretary"||xe==="秘书"||pe==="secretary"||pe.startsWith("secretary")},fs=(Z,pe,xe)=>{const De=t.find(Ze=>Ze.id===pe);De&&$l(De)||(ft.current={x:Z.clientX,y:Z.clientY},ot.current=setTimeout(()=>{ze({agentId:pe,fromTeamId:xe}),Un(!0)},200))},ss=Z=>{if(!ft.current||!ot.current)return;const pe=Math.abs(Z.clientX-ft.current.x),xe=Math.abs(Z.clientY-ft.current.y);(pe>5||xe>5)&&(mt||(clearTimeout(ot.current),ot.current=null))},Qs=async()=>{if(ot.current&&(clearTimeout(ot.current),ot.current=null),ft.current=null,mt&&ke&&Ge){const Z=Ge==="_ungrouped"?void 0:Ge;try{if(ke.fromTeamId&&ke.fromTeamId!==Z&&await te.teams.removeMember(ke.fromTeamId,ke.agentId),Z&&Z!==ke.fromTeamId){const pe=t.find(xe=>xe.id===ke.agentId);await te.teams.addMember(Z,ke.agentId,"agent")}O(),m(),Ht()}catch(pe){Me(D("batchAction.moveFailed",{error:pe instanceof Error?pe.message:String(pe)}),"error")}}ze(null),kt(null),Un(!1)},ms=S.useMemo(()=>new Map(r.map(Z=>[Z.id,Z])),[r]),bs=S.useMemo(()=>{const Z=new Map,pe=[];for(const xe of t)if(xe.teamId&&ms.has(xe.teamId)){const De=Z.get(xe.teamId)??[];De.push(xe),Z.set(xe.teamId,De)}else pe.push(xe);return{byTeam:Z,ungrouped:pe}},[t,ms]),Ko=(Z,pe)=>{const xe=l==="direct"&&h===Z.id,De=B.has(Z.id),Ze=Z.status==="offline",He=Wh(Z.status,!Ze&&U.has(Z.id)),gt=He.tone==="busy",yt=He.dotClass,Jt=(void 0)?.managerId===Z.id,ps=Z.role?.toLowerCase().replace(/[-_]/g," ").trim(),gs=Z.name.toLowerCase().trim(),rr=ps&&ps!==gs,Dr=de.get(Z.id)||Z.currentActivity?.label?.slice(0,60)||"",kr=gt?D("common:status.working"):Z.status==="error"?D("common:status.error"):D(Ze?"common:status.offline":"common:status.online");return c.jsx("div",{className:`relative mb-0.5 ${mt&&ke?.agentId===Z.id?"opacity-40":""}`,onPointerDown:Qt=>fs(Qt,Z.id,pe),onPointerMove:ss,onPointerUp:Qs,children:c.jsxs("button",{"data-l1-nav-id":`agent:${Z.id}`,onClick:()=>{mt||f(Z.id)},onContextMenu:Qt=>{if(!z)return;Qt.preventDefault();const $s=oi(Qt);Ot(!1),At(""),Ke({agentId:Z.id,teamId:pe,...$s})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ne?"":"touch-none"} ${Ze?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ri(xe)}`,children:[c.jsx(Ms,{name:Z.name,avatarUrl:Z.avatarUrl,size:28,bgClass:Ze?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:Z.name}),rr&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",Z.role,")"]}),Jt&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),De&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ze&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:D("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Dr||" "})]}),c.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(P?.get(Z.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:P.get(Z.id)}),Z.mailboxDepth!=null&&Z.mailboxDepth>0&&c.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:Z.mailboxDepth}),c.jsx("span",{title:kr,onClick:Qt=>{Qt.stopPropagation(),_(Z.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${yt}`}),ne&&z&&c.jsx("span",{role:"button",tabIndex:0,onClick:Qt=>{if(Qt.stopPropagation(),oe?.agentId===Z.id)Ke(null);else{const $s=oi(Qt);Ot(!1),At(""),Ke({agentId:Z.id,teamId:pe,...$s})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:D("chat.moreOptions"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},Z.id)},Hn=(Z,pe,xe,De)=>{const Ze=mt&&Ge===Z&&ke?.fromTeamId!==Z,He=bt===Z,gt=g===Z,yt=P?(bs.byTeam.get(Z)??[]).reduce((Vt,li)=>Vt+(P.get(li.id)??0),0):0,Jt=o.find(Vt=>Vt.type==="team"&&Vt.teamId===Z)?.channelKey??Bv(Z),ps=k?k[Jt]??0:0,gs=yt+ps,rr=bs.byTeam.get(Z)??[],Dr=rr.filter(Vt=>Vt.status==="offline").length,kr=rr.length,Qt=kr>0&&Dr===kr,$s=Dr>0&&!Qt,Yn=Qt?"bg-gray-500":$s?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":Z,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ze?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${He?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{mt&&kt(Z)},onPointerLeave:()=>{mt&&Ge===Z&&kt(null)},children:[c.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[c.jsxs("button",{"data-l1-nav-id":`team:${Z}`,onClick:()=>{b&&Z!=="_ungrouped"&&b(Z)},onContextMenu:Vt=>{if(!z||!pe)return;Vt.preventDefault();const li=oi(Vt);Qe({teamId:Z,...li})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${Qt?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ri(gt)}`,children:[c.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${Qt?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[pe?.avatarUrl?c.jsx("img",{src:pe.avatarUrl,alt:De,className:"w-full h-full rounded-full object-cover",onError:Vt=>{Vt.target.style.display="none",Vt.target.nextElementSibling?.classList.remove("hidden")}}):null,c.jsxs("svg",{className:`w-3 h-3 ${pe?.avatarUrl?"hidden":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),kr>0&&c.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${Yn}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[od===Z?c.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:sr,onChange:Vt=>Yo(Vt.target.value),onBlur:()=>$i(Z),onKeyDown:Vt=>{Vt.key==="Enter"&&$i(Z),Vt.key==="Escape"&&ni(null)},onClick:Vt=>Vt.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:De}),c.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[D("chat.members_other",{count:xe}),Qt&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:D("common:status.offline")}),$s&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Dr,"/",kr]})]})]}),gs>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:gs}),c.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),z&&pe&&c.jsx("button",{onClick:Vt=>{if(Vt.stopPropagation(),Xe?.teamId===Z)Qe(null);else{const li=oi(Vt);Qe({teamId:Z,...li})}},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:D("chat.moreOptions"),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ze&&mt&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:D("chat.dropHere")})]},Z)},zs=S.useMemo(()=>{const Z=new Map,pe=[],xe=[],De=[];for(const Ze of o)if(Ze.channelKey.startsWith("dm:a2a:"))De.push(Ze);else if(Ze.type==="custom")xe.push(Ze);else if(Ze.teamId){const He=Z.get(Ze.teamId)??[];He.push(Ze),Z.set(Ze.teamId,He)}else{const He=r.find(gt=>Ze.name.toLowerCase().includes(gt.name.toLowerCase())||gt.name.toLowerCase().includes(Ze.name.toLowerCase()));if(He){const gt=Z.get(He.id)??[];gt.push(Ze),Z.set(He.id,gt)}else pe.push(Ze)}return{byTeam:Z,unmatched:pe,custom:xe,dmChannels:De}},[o,r]),ji=S.useMemo(()=>{const Z=new Map;let pe=0;for(const Ze of bs.ungrouped)Z.set(Ze.id,pe++);for(const Ze of r)for(const He of bs.byTeam.get(Ze.id)??[])Z.set(He.id,pe++);const xe=Number.MAX_SAFE_INTEGER,De=Ze=>{const He=Ze.split(":");return He.length<4?[]:[He[2],He[3]].map(gt=>Z.get(gt)??xe).sort((gt,yt)=>gt-yt)};return[...zs.dmChannels].sort((Ze,He)=>{const gt=De(Ze.channelKey),yt=De(He.channelKey),rt=gt[0]??xe,Jt=gt[1]??xe,ps=yt[0]??xe,gs=yt[1]??xe;return rt!==ps?rt-ps:Jt!==gs?Jt-gs:Ze.channelKey.localeCompare(He.channelKey)})},[zs.dmChannels,bs,r]),[un,qs]=S.useState(!1),ai=l==="channel"&&zs.dmChannels.some(Z=>Z.channelKey===d);S.useEffect(()=>{ai&&qs(!0)},[ai]);const Jo=S.useMemo(()=>{const Z=[];e&&Z.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const xe of i)xe.id!==e?.id&&Z.push({kind:"dm",id:`dm:${xe.id}`,userId:xe.id});for(const xe of zs.custom)Z.push({kind:"channel",id:`channel:${xe.channelKey}`,channelKey:xe.channelKey});for(const xe of zs.unmatched)Z.push({kind:"channel",id:`channel:${xe.channelKey}`,channelKey:xe.channelKey});const pe=bs.ungrouped.length>0?bs.ungrouped:r.length===0?t:[];for(const xe of pe)Z.push({kind:"agent",id:`agent:${xe.id}`,agentId:xe.id});for(const xe of r)Z.push({kind:"team",id:`team:${xe.id}`,teamId:xe.id});if(un)for(const xe of ji)Z.push({kind:"channel",id:`channel:${xe.channelKey}`,channelKey:xe.channelKey});return Z},[e,i,zs,bs,r,t,un]),Rt=S.useRef(Jo);Rt.current=Jo;const pr=S.useCallback(Z=>{Z.kind==="dm"?v(Z.userId):Z.kind==="channel"?p(Z.channelKey):Z.kind==="agent"?f(Z.agentId):Z.kind==="team"&&b?.(Z.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${Z.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,p,f,b]);S.useEffect(()=>{if(I||ne||!j||R)return;const Z=pe=>{const xe=X?.keyboardPane??"content";if(xe==="l0"||xe==="l2"||pe.metaKey||pe.ctrlKey||pe.altKey||zm(pe.target))return;const De=pe.key.length===1?pe.key.toLowerCase():pe.key;if(De==="h"||De==="ArrowLeft"){if(xe!=="l1")return;pe.preventDefault(),pe.stopPropagation(),X?.setL0FocusPageId(es.TEAM),X?.setLeftCollapsed(!1),X?.setKeyboardPane("l0");return}if(De==="l"||De==="ArrowRight"){if(xe!=="l1")return;pe.preventDefault(),pe.stopPropagation(),q&&X?.setKeyboardPane("l2");return}if(xe!=="l1"&&!(H&&(De==="j"||De==="k"||De==="ArrowDown"||De==="ArrowUp")))return;const Ze=De==="j"||De==="ArrowDown"?1:De==="k"||De==="ArrowUp"?-1:0;if(!Ze)return;pe.preventDefault(),pe.stopPropagation(),X?.setKeyboardPane("l1");const He=Rt.current;if(He.length===0)return;let gt=-1;if(l==="dm"){const rt=u||e?.id;rt&&(gt=He.findIndex(Jt=>Jt.kind==="dm"&&Jt.userId===rt))}else l==="direct"?gt=He.findIndex(rt=>rt.kind==="agent"&&rt.agentId===h):l==="channel"&&(gt=He.findIndex(rt=>rt.kind==="channel"&&rt.channelKey===d),gt<0&&g&&(gt=He.findIndex(rt=>rt.kind==="team"&&rt.teamId===g)));gt<0&&(gt=Ze>0?-1:0);const yt=Math.max(0,Math.min(He.length-1,gt+Ze));pr(He[yt])};return document.addEventListener("keydown",Z,!0),()=>document.removeEventListener("keydown",Z,!0)},[I,ne,j,R,X,H,q,l,u,e?.id,h,d,g,pr]);const Ri=Z=>Z?H?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${T!=null?"shrink-0":"flex-1 min-w-0"} ${H?"ring-1 ring-inset ring-brand-500/30":""}`,style:R?{display:"none"}:T!=null?{width:T}:void 0,children:[c.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[ne&&c.jsx(Ak,{}),!ne&&A&&c.jsx("button",{onClick:A,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsx("h2",{className:"text-lg font-semibold",children:D("chat.title")}),z&&c.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:st,children:[c.jsxs("button",{onClick:()=>ht(!Je),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[c.jsx("span",{className:"text-brand-500",children:"+"})," ",D("chat.manage"),c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Je?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),Je&&c.jsxs("div",{ref:Z=>{if(!Z)return;const pe=Z.getBoundingClientRect(),xe=window.innerWidth,De=8;pe.right>xe-De&&(Z.style.left="auto",Z.style.right="0"),pe.left<De&&(Z.style.left="0",Z.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[c.jsxs("button",{onClick:()=>{ht(!1),lt("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),c.jsx("circle",{cx:"12",cy:"5",r:"2"}),c.jsx("path",{d:"M12 7v4"}),c.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),D("chat.addAgent")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:D("chat.addAgentDesc")})]}),c.jsxs("button",{onClick:()=>{ht(!1),lt("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),c.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),D("chat.newTeam")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:D("chat.newTeamDesc")})]}),c.jsxs("button",{onClick:()=>{ht(!1),ee(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M20 8v6"}),c.jsx("path",{d:"M23 11h-6"})]}),D("chat.addHuman")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:D("chat.addHumanDesc")})]}),c.jsxs("button",{onClick:()=>{ht(!1),we(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),c.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),D("chat.newGroupChat")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:D("chat.newGroupChatDesc")})]}),fe!==null&&c.jsxs("button",{onClick:()=>{ht(!1),J()},disabled:_e,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 ${fe?"text-green-600":"text-red-500"}`,children:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:fe?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",D("chat.resume")]}):c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",D("contextMenu.stopAll")]})}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:D(fe?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:Tt,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:D("chat.people")}),e&&c.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ri(l==="dm"&&(u===e.id||!u))}`,children:[c.jsx(Ms,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:D("chat.myNotes")})]}),c.jsx("span",{className:"text-fg-secondary shrink-0",children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(Z=>Z.id!==e?.id).map(Z=>{const pe=e?.id?`dm:${[e.id,Z.id].sort().join(":")}`:"",xe=pe&&k?k[pe]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${Z.id}`,onClick:()=>v(Z.id),onContextMenu:De=>{if(!z||Z.id===e?.id)return;De.preventDefault();const Ze=oi(De);je({userId:Z.id,...Ze})},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===Z.id?H?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[c.jsx(Ms,{name:Z.name,avatarUrl:Z.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:Z.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Z.email||Z.role})]}),xe>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:xe}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},Z.id)})]}),zs.custom.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:D("chat.groups")}),zs.custom.map(Z=>{const pe=l==="channel"&&d===Z.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${Z.channelKey}`,onClick:()=>p(Z.channelKey),onContextMenu:xe=>{xe.preventDefault();const De=oi(xe);_t({gcId:Z.id,...De})},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(pe)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Z.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:D("chat.members_other",{count:Z.memberCount??0})})]})]},Z.id)})]}),E?c.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((Z,pe)=>c.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[c.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),c.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),c.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},pe))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:D("chat.noAgentsYet")}):null,zs.unmatched.map(Z=>{const pe=k?.[Z.channelKey]??0;return c.jsxs("button",{"data-l1-nav-id":`channel:${Z.channelKey}`,onClick:()=>p(Z.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===Z.channelKey)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Z.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:D("chat.groupChat")})]}),pe>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:pe}):Z.memberCount!==void 0&&Z.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:Z.memberCount}):null]},Z.id)}),bs.ungrouped.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:D("chat.agents")}),bs.ungrouped.map(Z=>Ko(Z))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:xt,children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:D("chat.teams")}),r.map(Z=>{const pe=bs.byTeam.get(Z.id)??[],xe=Z.members?.length||pe.length;return Hn(Z.id,Z,xe,Z.name)})]}),r.length===0&&bs.ungrouped.length===0&&t.length>0&&t.map(Z=>Ko(Z)),ji.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>qs(Z=>!Z),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${un?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),D("chat.agentDMs"),c.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:ji.length})]}),un&&ji.map(Z=>{const pe=l==="channel"&&d===Z.channelKey,xe=k?.[Z.channelKey]??0,De=Z.name.replace(/^DM:\s*/,"");return c.jsxs("button",{"data-l1-nav-id":`channel:${Z.channelKey}`,onClick:()=>p(Z.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(pe)}`,children:[c.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:De}),xe>0&&c.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:xe})]},Z.id)})]})]})]}),N&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:N,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),Xe&&(()=>{const Z=bs.byTeam.get(Xe.teamId)??[],pe=Z.some(De=>De.status==="offline"),xe=Z.some(De=>De.status!=="offline");return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Xe.x,top:Xe.y},onClick:De=>De.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const De=ms.get(Xe.teamId);De&&(ni(Xe.teamId),Yo(De.name)),Qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),D("contextMenu.renameTeam")]}),pe&&c.jsxs("button",{onClick:()=>{Ts(Xe.teamId,"start"),Qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),D("contextMenu.startAll")]}),xe&&c.jsxs("button",{onClick:()=>{Ts(Xe.teamId,"stop"),Qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),D("contextMenu.stopAll")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{Qe(null),jr.navigate(es.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),D("chat.addAgent")]}),se.length>0&&c.jsxs("button",{onClick:()=>{Qe(null),Ce(Xe.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),c.jsx("polyline",{points:"17 11 19 13 23 9"})]}),D("contextMenu.addExisting")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{const De=ms.get(Xe.teamId);De&&ct(Xe.teamId,De.name),Qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),D("contextMenu.deleteTeam")]})]})})(),oe&&(()=>{const Z=t.find(He=>He.id===oe.agentId);if(!Z||!z)return null;const xe=(oe.teamId?ms.get(oe.teamId):void 0)?.managerId===Z.id,De=Z.id===e?.id,Ze=$l(Z);return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:oe.x,top:oe.y,maxHeight:Math.max(160,window.innerHeight-oe.y-8)},onClick:He=>He.stopPropagation(),children:[Ze&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:D("contextMenu.orgSecretaryProtected")}),c.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),c.jsxs("button",{onClick:()=>{Ke(null),_(Z.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),D("contextMenu.viewProfile")]}),Z.status==="offline"?c.jsxs("button",{onClick:()=>{Go(Z.id,"offline"),Ke(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),D("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{Go(Z.id,Z.status??"idle"),Ke(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),D("contextMenu.stop")]}),!Ze&&oe.teamId&&!xe&&c.jsxs("button",{onClick:()=>{zt(oe.teamId,Z.id,"agent"),Ke(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),D("contextMenu.setAsManager")]}),!Ze&&oe.teamId&&c.jsxs("button",{onClick:()=>{dn(oe.teamId,Z.id),Ke(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),D("contextMenu.removeFromTeam")]}),!Ze&&(()=>{const He=r.filter(rt=>rt.id!==oe.teamId);if(He.length===0)return null;const gt=Wt.trim().toLowerCase(),yt=gt?He.filter(rt=>rt.name.toLowerCase().includes(gt)):He;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>Ot(rt=>!rt),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:D("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${nt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),nt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:rt=>rt.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:Wt,onChange:rt=>At(rt.target.value),onKeyDown:rt=>rt.stopPropagation(),placeholder:D("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:yt.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:D("contextMenu.moveToEmpty")}):yt.map(rt=>c.jsx("button",{type:"button",onClick:async()=>{oe.teamId&&await te.teams.removeMember(oe.teamId,Z.id),await te.teams.addMember(rt.id,Z.id,"agent"),O(),m(),Ht(),Ke(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:rt.name,children:rt.name},rt.id))})]})]})})(),!Ze&&!De&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{Ql(Z.id,Z.name,"agent",oe.teamId),Ke(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),D("contextMenu.removeFromOrg")]})]})]})})(),vt&&(()=>{const Z=i.find(pe=>pe.id===vt.userId);return!Z||!z?null:c.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:vt.x,top:vt.y},onClick:pe=>pe.stopPropagation(),children:c.jsxs("button",{onClick:()=>{Ql(Z.id,Z.name,"human"),je(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),D("contextMenu.removeFromOrg")]})})})(),M&&c.jsx(d2,{onClose:()=>re(!1),onCreate:async(Z,pe)=>{try{const{team:xe}=await te.teams.create(Z,pe);re(!1),O(),$t(xe.id),setTimeout(()=>{document.querySelector(`[data-team-id="${xe.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>$t(null),3e3)}catch(xe){Me(D("chat.failedToCreateTeam",{message:xe instanceof Error?xe.message:String(xe)}),"error")}}}),Y&&c.jsx(u2,{onClose:()=>{ee(!1),x?.()},onAdd:async(Z,pe,xe)=>{const{inviteToken:De}=await te.users.create(Z,pe,void 0,xe);return x?.(),{inviteToken:De}}}),K!==null&&c.jsx(f2,{teamId:K,ungrouped:se,onClose:()=>Ce(null),onAdd:async(Z,pe)=>{await te.teams.addMember(K,Z,pe),Ce(null),O(),Ht()}}),Re&&c.jsx(m2,{onClose:()=>Te(!1),onConnected:()=>{Te(!1),m(),O()}}),pt&&(()=>{const Z=o.find(pe=>pe.id===pt.gcId);return Z?c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:pt.x,top:pt.y},onClick:pe=>pe.stopPropagation(),children:[Z.type==="custom"&&c.jsxs("button",{onClick:()=>{_t(null),C?C(Z.channelKey):p(Z.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),D("contextMenu.manageMembers")]}),c.jsxs("button",{onClick:async()=>{_t(null),ge(D("modals.deleteGroupChat.title"),D("modals.deleteGroupChat.message",{name:Z.name}),async()=>{await te.groupChats.delete(Z.id),y()},D("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),D("modals.deleteGroupChat.menuLabel")]})]}):null})(),Oe&&c.jsx(T2,{agents:t,humans:i,authUser:e,onClose:()=>we(!1),onCreate:async(Z,pe,xe,De)=>{await te.groupChats.create({name:Z,memberIds:pe,memberTypes:xe,memberNames:De,creatorId:e?.id,creatorName:e?.name}),we(!1),y()}}),Ve&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>lt(null),children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:Z=>Z.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:D(Ve==="agent"?"chat.addAgent":"chat.newTeam")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:D("chat.methodChoiceSubtitle")})]}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsxs("button",{onClick:()=>{const Z=Ve;lt(null);const pe=t.find(xe=>xe.role==="secretary")??t.find(xe=>xe.name?.toLowerCase().includes("secretary"));pe?(f(pe.id),jr.navigate(es.TEAM,{agentId:pe.id,prefillMessage:D(Z==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):Z==="agent"?jr.navigate(es.STORE):re(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),c.jsx("path",{d:"M20 3v4"}),c.jsx("path",{d:"M22 5h-4"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:D("chat.methodSecretary")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:D("chat.methodSecretaryDesc")})]}),c.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:D("chat.recommended")})]}),c.jsxs("button",{onClick:()=>{const Z=Ve;lt(null),Z==="agent"?jr.navigate(es.STORE):re(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:D("chat.methodManual")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:D(Ve==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),c.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:c.jsx("button",{onClick:()=>lt(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:D("common:cancel")})})]})}),ve&&c.jsx(qo,{title:ve.title,message:ve.message,confirmLabel:ve.confirmLabel,checkboxes:ve.checkboxes,onConfirm:Z=>{ve.onConfirm(Z),ye(null)},onCancel:()=>ye(null)}),le&&c.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${le.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:le.message})]})});function UO({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:h,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:p,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:g,unreadByAgent:O,width:m,onResizeStart:x,focused:y}){const{t:_}=Mt(["team","common"]),C=Ih(),P=Xm(es.TEAM),k=r?.role==="owner"||r?.role==="admin",T=S.useMemo(()=>e.filter(Y=>Y.teamId===s.id),[e,s.id]),N=S.useMemo(()=>{const Y=new Set((s.members??[]).filter(ee=>ee.type==="human").map(ee=>ee.id));return t.filter(ee=>Y.has(ee.id))},[s.members,t]),R=i&&n==="channel"&&o===i.channelKey,A=S.useMemo(()=>{const Y=[];i&&Y.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const ee of T)Y.push({kind:"agent",id:`agent:${ee.id}`,agentId:ee.id});for(const ee of N)Y.push({kind:"dm",id:`dm:${ee.id}`,userId:ee.id});return Y},[i,T,N]),E=S.useRef(A);E.current=A;const I=S.useCallback(Y=>{Y.kind==="channel"?u(Y.channelKey):Y.kind==="agent"?d(Y.agentId):f(Y.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${Y.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);S.useEffect(()=>{if(!P)return;const Y=ee=>{if((C?.keyboardPane??"content")!=="l2"||ee.metaKey||ee.ctrlKey||ee.altKey||zm(ee.target))return;const Ce=ee.key.length===1?ee.key.toLowerCase():ee.key;if(Ce==="h"||Ce==="ArrowLeft"){ee.preventDefault(),ee.stopPropagation(),C?.setKeyboardPane("l1");return}if(Ce==="l"||Ce==="ArrowRight"){ee.preventDefault(),ee.stopPropagation();return}const Re=Ce==="j"||Ce==="ArrowDown"?1:Ce==="k"||Ce==="ArrowUp"?-1:0;if(!Re)return;ee.preventDefault(),ee.stopPropagation();const Te=E.current;if(Te.length===0)return;let Oe=-1;n==="channel"?Oe=Te.findIndex(Ve=>Ve.kind==="channel"&&Ve.channelKey===o):n==="direct"?Oe=Te.findIndex(Ve=>Ve.kind==="agent"&&Ve.agentId===a):n==="dm"&&l&&(Oe=Te.findIndex(Ve=>Ve.kind==="dm"&&Ve.userId===l)),Oe<0&&(Oe=Re>0?-1:0);const we=Math.max(0,Math.min(Te.length-1,Oe+Re));I(Te[we])};return document.addEventListener("keydown",Y,!0),()=>document.removeEventListener("keydown",Y,!0)},[P,C,n,o,a,l,I]);const H=Y=>Y?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[q,D]=S.useState(null),[ne,j]=S.useState(!1),[X,z]=S.useState(""),[B,U]=S.useState(null),se=(Y,ee,K,Ce,Re)=>{U({title:Y,message:ee,onConfirm:K,confirmLabel:Ce,checkboxes:Re})},G=S.useCallback((Y,ee=176,K=220)=>{const Ce=window.innerWidth,Re=window.innerHeight,Te=8;let Oe=Y.clientX,we=Y.clientY;return Oe+ee>Ce-Te&&(Oe=Math.max(Te,Ce-ee-Te)),we+K>Re-Te&&(we=Math.max(Te,Re-K-Te)),Oe=Math.max(Te,Math.min(Oe,Ce-ee-Te)),we=Math.max(Te,Math.min(we,Re-K-Te)),{x:Oe,y:we}},[]);S.useEffect(()=>{if(!q)return;const Y=()=>D(null),ee=setTimeout(()=>document.addEventListener("click",Y),0);return()=>{clearTimeout(ee),document.removeEventListener("click",Y)}},[q]);const he=S.useCallback(async(Y,ee)=>{ee==="offline"?await te.agents.start(Y):await te.agents.stop(Y),b()},[b]),V=S.useCallback(async Y=>{await te.teams.update(s.id,{managerId:Y,managerType:"agent"}),g()},[s.id,g]),M=S.useCallback(async Y=>{await te.teams.removeMember(s.id,Y),g(),b()},[s.id,g,b]),re=S.useCallback(async(Y,ee)=>{await te.teams.removeMember(s.id,Y),await te.teams.addMember(ee,Y,"agent"),g(),b()},[s.id,g,b]);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:m!=null?{width:m}:{width:260},children:[c.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:p,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:_("common:back",{defaultValue:"Back"}),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&c.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&c.jsxs("div",{className:"mb-3",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:_("chat.groupChat",{defaultValue:"Group Chat"})}),c.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${H(!!R)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:_("chat.members_other",{count:i.memberCount||T.length+N.length})})]})]})]}),T.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.agents",{defaultValue:"Agents"}),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:T.length})]}),T.map(Y=>{const ee=n==="direct"&&a===Y.id,K=s.managerId===Y.id,Ce=Y.status==="offline",Re=Wh(Y.status,Ks.isAgentStreaming(Y.id)).dotClass;return c.jsxs("button",{"data-l2-nav-id":`agent:${Y.id}`,onClick:()=>d(Y.id),onContextMenu:Te=>{if(!k)return;Te.preventDefault();const Oe=G(Te);j(!1),z(""),D({agentId:Y.id,...Oe})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${Ce?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${H(ee)}`,children:[c.jsx(Ms,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:Ce?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:Y.name}),K&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Ce&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:_("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Y.role||" "})]}),(O?.get(Y.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(Y.id)}),c.jsx("span",{title:Y.status,onClick:Te=>{Te.stopPropagation(),v(Y.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${Re}`})]},Y.id)})]}),N.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.people"),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:N.length})]}),N.map(Y=>{const ee=Y.id===r?.id,K=n==="dm"&&l===Y.id;return c.jsxs("button",{"data-l2-nav-id":`dm:${Y.id}`,onClick:()=>f(Y.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${H(K)}`,children:[c.jsx(Ms,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[Y.name,ee?` (${_("chat.you",{defaultValue:"You"})})`:""]}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Y.email||Y.role})]}),c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},Y.id)})]}),T.length===0&&N.length===0&&c.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&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),q&&(()=>{const Y=T.find(K=>K.id===q.agentId);if(!Y||!k)return null;const ee=s.managerId===Y.id;return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:q.x,top:q.y,maxHeight:Math.max(160,window.innerHeight-q.y-8)},onClick:K=>K.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{D(null),v(Y.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),_("contextMenu.viewProfile")]}),Y.status==="offline"?c.jsxs("button",{onClick:()=>{he(Y.id,"offline"),D(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),_("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{he(Y.id,Y.status??"idle"),D(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),_("contextMenu.stop")]}),!ee&&c.jsxs("button",{onClick:()=>{V(Y.id),D(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),_("contextMenu.setAsManager")]}),c.jsxs("button",{onClick:()=>{M(Y.id),D(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),_("contextMenu.removeFromTeam")]}),(()=>{const K=h.filter(Te=>Te.id!==s.id);if(K.length===0)return null;const Ce=X.trim().toLowerCase(),Re=Ce?K.filter(Te=>Te.name.toLowerCase().includes(Ce)):K;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>j(Te=>!Te),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:_("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${ne?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ne&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:Te=>Te.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:X,onChange:Te=>z(Te.target.value),onKeyDown:Te=>Te.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"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Re.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:_("contextMenu.moveToEmpty")}):Re.map(Te=>c.jsx("button",{type:"button",onClick:()=>{re(Y.id,Te.id),D(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Te.name,children:Te.name},Te.id))})]})]})})(),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{se(`${_("common:remove")} "${Y.name}"?`,_("modals.removeAgent.message"),async K=>{const Ce=K?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await te.agents.remove(Y.id,{purgeFiles:Ce}),b(),D(null)},_("common:remove"),[{id:"purgeFiles",label:_("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),_("contextMenu.removeFromOrg")]})]})})(),B&&c.jsx(qo,{title:B.title,message:B.message,confirmLabel:B.confirmLabel,checkboxes:B.checkboxes,onConfirm:Y=>{B.onConfirm(Y),U(null)},onCancel:()=>U(null)})]})}function kf(){return kf=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},kf.apply(null,arguments)}function $2(s,e){if(s==null)return{};var t={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(e.indexOf(r)!==-1)continue;t[r]=s[r]}return t}let Cf=[],Wv=[];(()=>{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?Wv:Cf).push(t=t+s[e])})();function j2(s){if(s<768)return!1;for(let e=0,t=Cf.length;;){let r=e+t>>1;if(s<Cf[r])t=r;else if(s>=Wv[r])e=r+1;else return!0;if(e==t)return!1}}function HO(s){return s>=127462&&s<=127487}const YO=8205;function R2(s,e,t=!0,r=!0){return(t?Xv:E2)(s,e,r)}function Xv(s,e,t){if(e==s.length)return e;e&&zv(s.charCodeAt(e))&&qv(s.charCodeAt(e-1))&&e--;let r=uu(s,e);for(e+=GO(r);e<s.length;){let i=uu(s,e);if(r==YO||i==YO||t&&j2(i))e+=GO(i),r=i;else if(HO(i)){let n=0,a=e-2;for(;a>=0&&HO(uu(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function E2(s,e,t){for(;e>1;){let r=Xv(s,e-2,t);if(r<e)return r;e--}return 0}function uu(s,e){let t=s.charCodeAt(e);if(!qv(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return zv(r)?(t-55296<<10)+(r-56320)+65536:t}function zv(s){return s>=56320&&s<57344}function qv(s){return s>=55296&&s<56320}function GO(s){return s<65536?1:2}let Lt=class Zv{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,r){[e,t]=Ao(this,e,t);let i=[];return this.decompose(0,e,i,2),r.length&&r.decompose(0,r.length,i,3),this.decompose(t,this.length,i,1),Ur.from(i,this.length-(t-e)+r.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ao(this,e,t);let r=[];return this.decompose(e,t,r,0),Ur.from(r,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),r=this.length-this.scanIdentical(e,-1),i=new Ba(this),n=new Ba(e);for(let a=t,o=t;;){if(i.next(a),n.next(a),a=0,i.lineBreak!=n.lineBreak||i.done!=n.done||i.value!=n.value)return!1;if(o+=i.value.length,i.done||o>=r)return!0}}iter(e=1){return new Ba(this,e)}iterRange(e,t=this.length){return new Vv(this,e,t)}iterLines(e,t){let r;if(e==null)r=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;r=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Fv(r)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Zv.empty:e.length<=32?new as(e):Ur.from(as.split(e,[]))}};class as extends Lt{constructor(e,t=A2(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.text[n],o=i+a.length;if((t?r:o)>=e)return new M2(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new as(KO(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=Ic(n.text,a.text.slice(),0,n.length);if(o.length<=32)r.push(new as(o,a.length+n.length));else{let l=o.length>>1;r.push(new as(o.slice(0,l)),new as(o.slice(l)))}}else r.push(n)}replace(e,t,r){if(!(r instanceof as))return super.replace(e,t,r);[e,t]=Ao(this,e,t);let i=Ic(this.text,Ic(r.text,KO(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new as(i,n):Ur.from(as.split(i,[]),n)}sliceString(e,t=this.length,r=`
|
|
@@ -55,7 +55,7 @@ ${le}
|
|
|
55
55
|
`)})},[i,s]);S.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const le=navigator.platform.toUpperCase().includes("MAC"),ae=Me=>{if(!(le?Me.metaKey&&!Me.ctrlKey:Me.ctrlKey&&!Me.metaKey)||!Me.shiftKey||Me.altKey||Me.key.toLowerCase()!=="a")return;const be=re.current?.getSelection()?.trim();be&&(Me.preventDefault(),oe(be))};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[s.kind,i,oe]);const nt=S.useCallback(le=>{if(!le.text.trim()||!i)return;const ae=he.current?.querySelector("iframe")?.getBoundingClientRect(),Me=(ae?.left??0)+le.rect.x+le.rect.width/2,fe=(ae?.top??0)+le.rect.y;I({x:Me,y:fe,text:le.text,htmlMeta:{xpath:le.xpath,cssSelector:le.cssSelector}})},[i]);S.useEffect(()=>{const le=he.current;if(!le||!i)return;const ae=()=>{requestAnimationFrame(()=>{const fe=window.getSelection(),be=fe?.toString().trim();if(!be||!fe?.rangeCount){I(null);return}const _e=fe.getRangeAt(0);if(!le.contains(_e.commonAncestorContainer)){I(null);return}const Ne=_e.getBoundingClientRect();I({x:Ne.left+Ne.width/2,y:Ne.top,text:be})})},Me=fe=>{const be=document.getElementById("right-panel-selection-toolbar");be&&be.contains(fe.target)||I(null)};return le.addEventListener("mouseup",ae),document.addEventListener("mousedown",Me),()=>{le.removeEventListener("mouseup",ae),document.removeEventListener("mousedown",Me)}},[i,x.mode]);const Ot=()=>{te.files.reveal(Re||K).catch(()=>{})},Wt=()=>{navigator.clipboard?.writeText(Re||K).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},At=S.useMemo(()=>{if(!i)return null;const le=Re||K;if(s.kind==="deliverable"){const ae=s.deliverable;if(!ae.id&&!ae.reference)return null;const Me=Ce||ae.title||ae.reference||ae.id;return{label:`📄 ${Me.length>40?`${Me.slice(0,24)}…${Me.slice(-12)}`:Me}`,content:["[deliverable]",ae.id?`ID: ${ae.id}`:"",ae.title?`Title: ${ae.title}`:"",ae.reference?`Reference: ${ae.reference}`:"",ae.taskId?`Task: ${ae.taskId}`:"",ae.projectId?`Project: ${ae.projectId}`:""].filter(Boolean).join(`
|
|
56
56
|
`)}}if(s.kind==="file"){if(!le||po(le))return null;const ae=Ce||le.split(/[/\\]/).pop()||le;return{label:`📄 ${ae.length>40?`${ae.slice(0,24)}…${ae.slice(-12)}`:ae}`,content:["[file]",`Path: ${le}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
|
|
57
57
|
`)}}return null},[i,s,Re,K,Ce,x]),[vt,je]=S.useState(!1),Pt=S.useCallback(()=>{At&&(i?.(At),je(!0),setTimeout(()=>je(!1),1200))},[At,i]),Ps=S.useCallback(async()=>{if(s.kind==="deliverable"){jr.navigate(es.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ae=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const Me=await window.markusDesktop.browser.getState(s.browserId);if(Me.ok){if(Me.directoryPath){await te.system.openPath(Me.directoryPath).catch(()=>te.files.reveal(Me.directoryPath));return}Me.url&&Me.url!=="about:blank"&&(ae=Me.url)}}catch{}if(!ae||ae==="about:blank")return;if(/^https?:\/\//i.test(ae)||/^file:\/\//i.test(ae)){nc(ae);return}await te.system.openPath(ae).catch(()=>nc(iv(ae)));return}if(s.kind!=="file")return;const le=s.path;if(le){if(/^https?:\/\//i.test(le)||/^file:\/\//i.test(le)){nc(le);return}await te.system.openPath(le).catch(()=>nc(iv(le)))}},[s]),pt=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,_t=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),Je=!!K&&!po(K)&&(s.kind==="file"||s.kind==="deliverable"),ht=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!K&&!po(K)&&!s.deliverable.artifactType&&CC(s.deliverable.format),st=s.kind==="deliverable"?{...s.deliverable,hubShareId:R?.id??s.deliverable.hubShareId??null,shareStatus:R?.status??s.deliverable.shareStatus??null,shareUrl:R?.url??s.deliverable.shareUrl??null,shareVisibility:R?.visibility??s.deliverable.shareVisibility??null}:null,bt=S.useCallback(le=>{A(le)},[]),$t=S.useMemo(()=>PC(xO,qm.getUrl()),[]),Tt=s.kind==="deliverable"?s.deliverable.id:null;S.useEffect(()=>{if(!Tt||!xO())return;let le=!1;const ae=async()=>{try{const fe=await $t.listMine();if(le)return;const be=s.kind==="deliverable"?s.deliverable:null;if(!be)return;const _e=be.hubShareId&&fe.find(J=>J.id===be.hubShareId)||fe.find(J=>J.localId===be.id);if(!_e)return;A(J=>J&&J.id===_e.id&&J.status===_e.status?J:_e);const Ne={hubShareId:be.hubShareId??_e.id??null,shareStatus:_e.status??null,shareUrl:_e.url??null,shareVisibility:be.shareVisibility??_e.visibility??null};(be.shareStatus!==Ne.shareStatus||be.hubShareId!==Ne.hubShareId||be.shareUrl!==Ne.shareUrl||be.shareVisibility!==Ne.shareVisibility)&&be.id&&te.deliverables.update(be.id,Ne).catch(J=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",J)})}catch{}};ae();const Me=setInterval(ae,3e4);return()=>{le=!0,clearInterval(Me)}},[$t,Tt,s]);const xt=st?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:m("common:browserMode",{defaultValue:"Browser"}),"aria-label":m("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":p==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:m("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":m("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":p==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),Te||h?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0 self-stretch flex flex-col justify-end",children:[c.jsxs("div",{ref:V,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:le=>{const ae=le.currentTarget;ae.scrollWidth<=ae.clientWidth||Math.abs(le.deltaY)<=Math.abs(le.deltaX)||(ae.scrollLeft+=le.deltaY,le.preventDefault())},children:[n?.map(le=>{const ae=le.id===a,Me=le.payload.kind==="url"?le.payload.pageId:void 0,fe=le.payload.kind==="terminal"?le.payload.terminalId:void 0,be=Me!=null?H[Me]:fe?D[fe]:void 0,_e=be?`${le.title} — ${m("common:browserTabControlledBy",{name:be.agentName})}`:le.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ae?be?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":be?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":ae,ref:ae?M: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:_e,onPointerDown:Ne=>{Ne.button===0&&(le.id!==a&&!ee()||o?.(le.id))},onClick:()=>{le.id!==a&&!ee()||o?.(le.id)},children:[be&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:m("common:browserTabControlledBy",{name:be.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:be.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:le.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:Ne=>{Ne.button===0&&(Ne.preventDefault(),Ne.stopPropagation(),!(le.id===a&&!ee())&&l(le.id))},onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),!(le.id===a&&!ee())&&l(le.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ae?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:m("common:closeTab",{defaultValue:"Close tab"}),"aria-label":m("common:closeTab",{defaultValue:"Close tab"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},le.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:m("common:newTab",{defaultValue:"New Tab"}),"aria-label":m("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),c.jsx(U4,{scrollRef:V,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:K||Ce,children:Ce}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[we&&c.jsx("button",{type:"button",onClick:lt,title:m("common:refreshPreview",{defaultValue:"刷新"}),"aria-label":m("common:refreshPreview",{defaultValue:"刷新"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{className:x.mode==="loading"?"animate-spin":"",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),we&&c.jsx("button",{type:"button",onClick:()=>se(le=>!le),"aria-pressed":U,title:U?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),"aria-label":U?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${U?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{Ke()},title:m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),At&&c.jsx("button",{type:"button",onClick:Pt,title:vt?m("common:addedToChat",{defaultValue:"Added to chat"}):s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),"aria-label":s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${vt?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:vt?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h6"}),c.jsx("line",{x1:"17",y1:"3",x2:"17",y2:"9"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"})]})}),ht&&c.jsxs("button",{type:"button",onClick:()=>N(!0),title:m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${xt==="published"?"text-green-500 hover:text-green-400":xt==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"18",cy:"5",r:"3"}),c.jsx("circle",{cx:"6",cy:"12",r:"3"}),c.jsx("circle",{cx:"18",cy:"19",r:"3"}),c.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),c.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(xt==="published"||xt==="pending_review"||xt==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${xt==="published"?"bg-green-500":xt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),pt&&c.jsx("button",{type:"button",onClick:()=>{Ps()},title:_t,"aria-label":_t,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),Je&&c.jsx("button",{onClick:Wt,title:P?m("common:copied",{defaultValue:"Copied"}):m("common:copyPath",{defaultValue:"复制路径"}),"aria-label":m("common:copyPath",{defaultValue:"复制路径"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${P?"text-green-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:P?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),Je&&c.jsx("button",{onClick:Ot,title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?m("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):m("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{ee()&&e()},title:m("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":m("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="directory"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[_&&x.mode!=="directory"&&x.mode!=="loading"&&c.jsx("div",{className:"shrink-0 mb-2",children:c.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-fg-secondary hover:text-brand-500 transition-colors cursor-pointer",onClick:()=>C(K4(Re)),children:[c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 20 20",fill:"currentColor",children:c.jsx("path",{fillRule:"evenodd",d:"M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z",clipRule:"evenodd"})}),"返回上级目录"]})}),x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${bf(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${bf(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[m("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${bf(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{te.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="office"&&c.jsx("div",{ref:he,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(Bk,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{te.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const le=K?K.replace(/[/\\][^/\\]+$/,""):void 0,ae=K&&!po(K)?K:"",Me=x.format;return ae&&(Me==="code"||Me==="json"||Me==="text")?c.jsx("div",{ref:he,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(c_,{path:ae,initialContent:x.content,language:Jp(ae,Me),onDirtyChange:X})}):ae&&(Me==="markdown"||Me==="html")?c.jsx("div",{ref:he,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(O4,{path:ae,content:x.content,format:Me,basePath:le,onHtmlSelection:nt,onDirtyChange:X})}):c.jsx("div",{ref:he,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(wf,{content:x.content,format:Me,className:"text-fg-secondary text-sm",onHtmlSelection:nt,basePath:le})})})(),x.mode==="artifact"&&c.jsx("div",{ref:he,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(wf,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(M4,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?le=>f(x.browserId,le):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(Z4,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:re,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:le=>{if(!le||!i){I(null);return}I({x:le.x,y:le.y,text:le.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(Wk,{path:x.path,entries:x.entries,onNavigate:le=>C(le),onOpenFile:le=>C(le),onReveal:Ot,onCopyPath:Wt}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?m("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):m("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:Ot,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),c.jsx("button",{onClick:Ot,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:m("common:open",{defaultValue:"Open"})}),c.jsx("button",{onClick:Wt,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?m("common:copied",{defaultValue:"Copied"}):m("common:copy",{defaultValue:"Copy"})})]})]})]},`${Oe}#${z}`)]}),E&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:E.x,top:E.y-8},children:c.jsxs("button",{onMouseDown:le=>{le.preventDefault(),le.stopPropagation(),oe(E.text,E.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),m("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&st&&c.jsx(TC,{item:st,onClose:()=>N(!1),onShared:bt})]})}function eD({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=Mt(["team","common"]);return c.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",r,")"]}),c.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(l=>c.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${l.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[c.jsx(Ms,{name:l.name,size:16,bgClass:l.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),l.name,l.id!==t&&c.jsx("button",{onClick:()=>n(l.id),className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},l.id))}),e.length>0&&c.jsx("div",{className:"mt-1",children:c.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:l=>{l.target.value&&a(l.target.value)},children:[c.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),e.map(l=>c.jsxs("option",{value:l.id,children:["[",l.type==="agent"?"Agent":"Human","] ",l.name]},l.id))]})})]})}const tD={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},sD={text:"bg-brand-500/10 text-brand-500",thinking:"bg-amber-500/10 text-amber-600",tool:"bg-sky-500/10 text-sky-600"};function rD({match:s}){const e=s.snippet.slice(0,s.snippetMatchStart),t=s.snippet.slice(s.snippetMatchStart,s.snippetMatchStart+s.snippetMatchLength),r=s.snippet.slice(s.snippetMatchStart+s.snippetMatchLength);return c.jsxs("span",{className:"text-xs text-fg-secondary",children:[e,c.jsx("mark",{className:"bg-yellow-500/30 text-fg-primary rounded-[3px] px-0.5",children:t}),r]})}function iD({query:s,onQueryChange:e,matches:t,cursor:r,scanned:i,hasMore:n,loadingMore:a,truncated:o,onLoadEarlier:l,onJump:h,onClose:d,labelFor:u,serverResults:f,serverLoading:p,onServerResultClick:v}){const{t:b,i18n:g}=Mt(["team","common"]),O=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{O.current?.focus()},[]),S.useEffect(()=>{if(r<0)return;m.current?.querySelector(`[data-find-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);const x=_=>{if(t.length===0)return;const P=(((r<0?_>=0?-1:0:r)+_)%t.length+t.length)%t.length;h(P)},y=s.trim().length>0;return c.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/60 px-4 py-2 space-y-1.5 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("div",{className:"flex-1 relative",children:[c.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),c.jsx("input",{ref:O,value:s,onChange:_=>e(_.target.value),onKeyDown:_=>{_.key==="Escape"?(_.preventDefault(),d()):_.key==="Enter"?(_.preventDefault(),x(_.shiftKey?-1:1)):_.key==="ArrowDown"?(_.preventDefault(),x(1)):_.key==="ArrowUp"&&(_.preventDefault(),x(-1))},placeholder:b("page.findPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),c.jsx("span",{className:"text-[11px] text-fg-tertiary tabular-nums shrink-0 min-w-[44px] text-center",children:y&&t.length>0?b("page.findMatchCount",{current:(r<0?0:r)+1,total:t.length}):y?"0/0":""}),c.jsx("button",{onClick:()=>x(-1),disabled:t.length===0,title:b("page.findPrev"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"18 15 12 9 6 15"})})}),c.jsx("button",{onClick:()=>x(1),disabled:t.length===0,title:b("page.findNext"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("button",{onClick:d,title:b("page.findClose"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated transition-colors",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y&&c.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:b("page.findScopeLoaded",{count:i})}),o&&c.jsx("span",{className:"text-amber-600",children:b("page.findTruncated",{count:t.length})}),t.length===0&&!n&&c.jsx("span",{className:"text-fg-secondary",children:b("page.findNoMatches")}),n&&c.jsx("button",{onClick:l,disabled:a,className:"ml-auto text-brand-500 hover:text-brand-500 disabled:opacity-50 underline decoration-dotted",children:b(a?"page.findLoadingEarlier":"page.findLoadEarlier")})]}),y&&t.length>0&&c.jsx("div",{ref:m,className:"max-h-52 overflow-y-auto scrollbar-thin space-y-0.5",children:t.map((_,C)=>c.jsxs("button",{"data-find-idx":C,onClick:()=>h(C),className:`w-full text-left px-2.5 py-1.5 rounded-lg transition-colors ${C===r?"bg-brand-500/15 ring-1 ring-brand-500/40":"hover:bg-surface-elevated"}`,children:[c.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${sD[_.field]}`,children:b(tD[_.field])}),u&&c.jsx("span",{className:"text-[10px] text-fg-tertiary truncate",children:u(_)})]}),c.jsx("div",{className:"line-clamp-2 break-words",children:c.jsx(rD,{match:_})})]},`${_.messageId}-${_.field}-${C}`))}),y&&(p||f&&f.length>0)&&c.jsxs("div",{className:"border-t border-border-default/60 mt-1 px-1",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-medium py-0.5",children:b("page.findServerResultsTitle")}),p&&c.jsx("div",{className:"text-xs text-fg-tertiary px-2.5 py-1",children:b("page.searching")}),f&&f.length>0&&c.jsx("div",{className:"max-h-40 overflow-y-auto scrollbar-thin space-y-0.5",children:f.map(_=>c.jsxs("button",{onClick:()=>v?.(_),className:"w-full text-left px-2.5 py-1.5 rounded-lg transition-colors hover:bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-fg-tertiary mb-0.5 min-w-0",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${_.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:_.source==="channel"?"#":"1:1"}),c.jsx("span",{className:"truncate max-w-[9rem] text-fg-secondary font-medium",children:_.source==="channel"?_.channel?`#${_.channel}`:b("page.findServerResultsTitle"):_.sessionTitle||b("page.untitledSession")}),_.senderName&&c.jsx("span",{className:"truncate max-w-[6rem] shrink-0",children:_.senderName}),c.jsx("span",{className:"shrink-0 ml-auto tabular-nums",title:Bm(_.createdAt,g.language),children:Im(_.createdAt,b)})]}),c.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 break-words",children:_.text.length>200?_.text.slice(0,200)+"…":_.text})]},_.id))})]})]})}const nD=300,oD=48;function aD(s){const e=[];if(s.segments&&s.segments.length>0){for(const t of s.segments)if(t.type==="text")t.thinking&&e.push({field:"thinking",value:t.thinking}),t.content&&e.push({field:"text",value:t.content});else if(t.type==="tool"){const r=[t.tool,t.result,t.error].filter(i=>!!i);r.length>0&&e.push({field:"tool",value:r.join(`
|
|
58
|
-
`)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function lD(s,e,t,r=oD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function cD(s,e,t={}){const r=t.limit??nD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of aD(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=lD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function hD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function dD(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const uD="markus.scrollDebug";let vf=null,nv=!1;function fD(){if(!nv){try{vf=typeof localStorage<"u"&&localStorage.getItem(uD)==="1"}catch{vf=!1}nv=!0}return vf===!0}function Fi(s,e){fD()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function mD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function pD(s,e){return s.filter(t=>{if(!mD(t)||(t.details?.agentId??t.agentId)!==e.agentId)return!1;const i=t.details?.sessionId;return!(i&&e.sessionId&&i!==e.sessionId)})}const ov={urgent:0,high:1,normal:2,low:3};function av(s){return ov[s??"normal"]??ov.normal}function gD(s){return[...s].sort((e,t)=>{const r=av(e.priority)-av(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function OD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Em(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function xD(s,e){return e?gD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&OD(t)===e)):[]}const lv={sessionId:null,messageId:null};function bD(s){if(s.length===0)return lv;const e=new Set(s.map(Em).filter(n=>!!n));if(e.size!==1||s.some(n=>!Em(n)))return lv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const vD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","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","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function yD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of vD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function SD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function wD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const y_=16;function _D(s,e,t=y_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function kD(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const CD=S.lazy(()=>Lv(()=>import("./index-C_QhfMcC.js").then(s=>s.b7),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),th={mind:"mind",files:"files",tools:"tools",memory:"memory"},ng=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Am(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function PD(s,e){const{labelKey:t}=Bh(s);return t?e(t):s}function Mm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function cv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Mt(["agent","common"]),u=Wm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),_=S.useMemo(()=>ng.map(q=>({...q,label:d(`agent:tabs.${q.key}`)})),[d]),C=S.useMemo(()=>_.map(q=>({id:q.key})),[_]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),k=Rv(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const q=T.current;if(!q)return;q.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const N=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),N(),te.externalAgents.list().then(D=>{const ne=D.agents.find(j=>j.markusAgentId===s);y(ne??null)}).catch(()=>{}),St.on("agent:update",D=>{D.payload.agentId===s&&N()})),[s,N]),!f)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:d("agent:profilePage.loadingAgent")});const R=Bh(f.state.status).dotClass,A=a?.role==="owner"||a?.role==="admin",E=q=>h??th[q],I=q=>x||th[q]?"overview":q,H=th[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[I(m)==="overview"&&c.jsx(dv,{agent:f,onUpdate:N,externalInfo:x,t:d,canManageAgents:A,highlightMailboxId:n,initialSection:E(m)}),I(m)==="deliverables"&&c.jsx(yv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ms,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${R}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:PD(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>jr.navigate(es.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),A&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:q}=await te.agents.getFilesMap(s),D={type:"agent",name:Ev(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await qm.publishViaProxy({itemType:"agent",name:f.name,description:D.description,category:"general",config:D,files:q}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(q){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(q)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:_.filter(q=>!x||q.key==="overview").map(q=>c.jsxs("button",{onClick:()=>O(q.key),"data-active":g===q.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===q.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:q.icon}),q.label]},q.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?k.onTouchStart:void 0,onTouchEnd:u?k.onTouchEnd:void 0,children:[I(g)==="overview"&&c.jsx(dv,{agent:f,onUpdate:N,externalInfo:x,t:d,canManageAgents:A,highlightMailboxId:n,initialSection:h??H}),I(g)==="deliverables"&&c.jsx(yv,{agentId:s})]}),v&&c.jsx(qo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function TD({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Vm.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function go({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function hv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Nh,{agentId:s,activityId:e.id})})]})}function dv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[_,C]=S.useState(()=>FO(a,n));S.useEffect(()=>{C(FO(a,n))},[a,n]);const P=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const ne=D.agents.find(j=>j.agentId===s.id);ne&&l(ne)}).catch(()=>{}),te.agents.getActivities(s.id,{limit:_2}).then(D=>d(D.activities)).catch(()=>{}),te.system.storage().then(D=>{g(D.dataDir+"/agents/"+s.id);const ne=D.agents.find(j=>j.id===s.id);ne&&v(ne)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(ne=>s.state.activeTaskIds?.includes(ne.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,P,s.state.status]);const k=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},T=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),N=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(hs,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:N.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(hs,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:T.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:R,comms:A}=k2(h),E=VO(R),I=VO(A),H=s.state.activeTaskIds?.length??0,q=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,E.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:E.total}):null,I.total>0?r("agent:profilePage.overview.a2aRuns",{count:I.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Mm(x2(o,s.state.tokensUsedToday))}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(H),color:H>0?"blue":void 0}),i&&c.jsx("button",{onClick:k,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:sh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(H>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Am(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(TD,{section:_,onChange:C,t:r}),_==="usage"&&c.jsx(go,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Mm(o.totalTokens)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.storage"),value:Ov(p.size)}),b2(p.subItems).map(D=>{const ne=y2(D.name);return c.jsx(Hs,{label:ne?r(ne):D.name,value:Ov(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),_==="recent"&&c.jsxs(go,{children:[q&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:q}),E.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:E.shown.map(D=>c.jsx(hv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),I.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:I.shown.map(D=>c.jsx(hv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),E.total===0&&I.total===0&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")})]}),_==="mind"&&c.jsx(go,{children:c.jsx(UD,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),_==="files"&&c.jsx(go,{children:c.jsx(RD,{agentId:s.id})}),_==="tools"&&c.jsx(go,{children:c.jsx(ND,{tools:s.tools??[],agent:s})}),_==="memory"&&c.jsxs(go,{children:[c.jsx(ID,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(DD,{agentId:s.id})})]})]})}function QD(s,e){const t=s.split(`
|
|
58
|
+
`)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function lD(s,e,t,r=oD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function cD(s,e,t={}){const r=t.limit??nD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of aD(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=lD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function hD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function dD(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const uD="markus.scrollDebug";let vf=null,nv=!1;function fD(){if(!nv){try{vf=typeof localStorage<"u"&&localStorage.getItem(uD)==="1"}catch{vf=!1}nv=!0}return vf===!0}function Fi(s,e){fD()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function mD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function pD(s,e){return s.filter(t=>{if(!mD(t)||(t.details?.agentId??t.agentId)!==e.agentId)return!1;const i=t.details?.sessionId;return!(i&&e.sessionId&&i!==e.sessionId)})}const ov={urgent:0,high:1,normal:2,low:3};function av(s){return ov[s??"normal"]??ov.normal}function gD(s){return[...s].sort((e,t)=>{const r=av(e.priority)-av(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function OD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Em(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function xD(s,e){return e?gD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&OD(t)===e)):[]}const lv={sessionId:null,messageId:null};function bD(s){if(s.length===0)return lv;const e=new Set(s.map(Em).filter(n=>!!n));if(e.size!==1||s.some(n=>!Em(n)))return lv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const vD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","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","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function yD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of vD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function SD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function wD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const y_=16;function _D(s,e,t=y_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function kD(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const CD=S.lazy(()=>Lv(()=>import("./index-D8vskks7.js").then(s=>s.b7),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),th={mind:"mind",files:"files",tools:"tools",memory:"memory"},ng=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Am(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function PD(s,e){const{labelKey:t}=Bh(s);return t?e(t):s}function Mm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function cv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Mt(["agent","common"]),u=Wm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),_=S.useMemo(()=>ng.map(q=>({...q,label:d(`agent:tabs.${q.key}`)})),[d]),C=S.useMemo(()=>_.map(q=>({id:q.key})),[_]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),k=Rv(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const q=T.current;if(!q)return;q.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const N=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),N(),te.externalAgents.list().then(D=>{const ne=D.agents.find(j=>j.markusAgentId===s);y(ne??null)}).catch(()=>{}),St.on("agent:update",D=>{D.payload.agentId===s&&N()})),[s,N]),!f)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:d("agent:profilePage.loadingAgent")});const R=Bh(f.state.status).dotClass,A=a?.role==="owner"||a?.role==="admin",E=q=>h??th[q],I=q=>x||th[q]?"overview":q,H=th[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[I(m)==="overview"&&c.jsx(dv,{agent:f,onUpdate:N,externalInfo:x,t:d,canManageAgents:A,highlightMailboxId:n,initialSection:E(m)}),I(m)==="deliverables"&&c.jsx(yv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ms,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${R}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:PD(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>jr.navigate(es.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),A&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:q}=await te.agents.getFilesMap(s),D={type:"agent",name:Ev(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await qm.publishViaProxy({itemType:"agent",name:f.name,description:D.description,category:"general",config:D,files:q}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(q){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(q)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:_.filter(q=>!x||q.key==="overview").map(q=>c.jsxs("button",{onClick:()=>O(q.key),"data-active":g===q.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===q.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:q.icon}),q.label]},q.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?k.onTouchStart:void 0,onTouchEnd:u?k.onTouchEnd:void 0,children:[I(g)==="overview"&&c.jsx(dv,{agent:f,onUpdate:N,externalInfo:x,t:d,canManageAgents:A,highlightMailboxId:n,initialSection:h??H}),I(g)==="deliverables"&&c.jsx(yv,{agentId:s})]}),v&&c.jsx(qo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function TD({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Vm.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function go({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function hv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Nh,{agentId:s,activityId:e.id})})]})}function dv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[_,C]=S.useState(()=>FO(a,n));S.useEffect(()=>{C(FO(a,n))},[a,n]);const P=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const ne=D.agents.find(j=>j.agentId===s.id);ne&&l(ne)}).catch(()=>{}),te.agents.getActivities(s.id,{limit:_2}).then(D=>d(D.activities)).catch(()=>{}),te.system.storage().then(D=>{g(D.dataDir+"/agents/"+s.id);const ne=D.agents.find(j=>j.id===s.id);ne&&v(ne)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(ne=>s.state.activeTaskIds?.includes(ne.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,P,s.state.status]);const k=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},T=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),N=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(hs,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(hs,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:N.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(hs,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:T.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:R,comms:A}=k2(h),E=VO(R),I=VO(A),H=s.state.activeTaskIds?.length??0,q=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,E.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:E.total}):null,I.total>0?r("agent:profilePage.overview.a2aRuns",{count:I.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Is,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Is,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Mm(x2(o,s.state.tokensUsedToday))}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(H),color:H>0?"blue":void 0}),i&&c.jsx("button",{onClick:k,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:sh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(H>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Am(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(TD,{section:_,onChange:C,t:r}),_==="usage"&&c.jsx(go,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Mm(o.totalTokens)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Hs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Hs,{label:r("agent:profilePage.overview.storage"),value:Ov(p.size)}),b2(p.subItems).map(D=>{const ne=y2(D.name);return c.jsx(Hs,{label:ne?r(ne):D.name,value:Ov(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),_==="recent"&&c.jsxs(go,{children:[q&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:q}),E.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:E.shown.map(D=>c.jsx(hv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),I.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:I.shown.map(D=>c.jsx(hv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),E.total===0&&I.total===0&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")})]}),_==="mind"&&c.jsx(go,{children:c.jsx(UD,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),_==="files"&&c.jsx(go,{children:c.jsx(RD,{agentId:s.id})}),_==="tools"&&c.jsx(go,{children:c.jsx(ND,{tools:s.tools??[],agent:s})}),_==="memory"&&c.jsxs(go,{children:[c.jsx(ID,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(DD,{agentId:s.id})})]})]})}function QD(s,e){const t=s.split(`
|
|
59
59
|
`),r=e.split(`
|
|
60
60
|
`),i=t.length,n=r.length,a=Array.from({length:i+1},()=>new Array(n+1).fill(0));for(let f=i-1;f>=0;f--)for(let p=n-1;p>=0;p--)a[f][p]=t[f]===r[p]?a[f+1][p+1]+1:Math.max(a[f+1][p],a[f][p+1]);const o=[];let l=0,h=0,d=1,u=1;for(;l<i||h<n;)l<i&&h<n&&t[l]===r[h]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,h++):h<n&&(l>=i||a[l][h+1]>=a[l+1][h])?(o.push({type:"add",content:r[h],lineNum:u++}),h++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function uv(s){return s.match(/\S+|\s+/g)??[""]}function fv({oldText:s,newText:e,mode:t}){const r=uv(s),i=uv(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=r[u]===i[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let h=0,d=0;for(;h<n||d<a;)h<n&&d<a&&r[h]===i[d]?(l.push({text:t==="remove"?r[h]:i[d],changed:!1}),h++,d++):d<a&&(h>=n||o[h][d+1]>=o[h+1][d])?(t==="add"&&l.push({text:i[d],changed:!0}),d++):(t==="remove"&&l.push({text:r[h],changed:!0}),h++);return c.jsx("span",{children:l.map((u,f)=>u.changed?c.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):c.jsx("span",{children:u.text},f))})}function $D({agent:s,template:e,templateId:t}){const{t:r}=Mt(["agent","common"]),i=S.useMemo(()=>QD(s,e),[s,e]),[n,a]=S.useState(!0),o=3,l=S.useMemo(()=>{const p=i.map((O,m)=>O.type!=="equal"?m:-1).filter(O=>O>=0);if(p.length===0)return[];const v=[];let b=Math.max(0,p[0]-o),g=Math.min(i.length-1,p[0]+o);for(let O=1;O<p.length;O++){const m=Math.max(0,p[O]-o),x=Math.min(i.length-1,p[O]+o);m<=g+1||(v.push({start:b,end:g}),b=m),g=x}return v.push({start:b,end:g}),v},[i]),h=(p,v,b)=>{const g=p.type==="add"?"+":p.type==="remove"?"-":" ",O=p.type==="add"?"bg-green-500/8":p.type==="remove"?"bg-red-500/8":"",m=p.type==="add"?"text-green-600/90":p.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=p.type==="add"?"text-green-500":p.type==="remove"?"text-red-500":"text-fg-muted",y=p.type==="remove"?p.oldLineNum:p.lineNum;let _=null;return p.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?_=c.jsx(fv,{oldText:p.content,newText:b[v+1].content,mode:"remove"}):p.type==="add"&&v>0&&b[v-1].type==="remove"&&(_=c.jsx(fv,{oldText:b[v-1].content,newText:p.content,mode:"add"})),c.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[c.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),c.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:g}),c.jsxs("span",{className:`flex-1 text-[11px] font-mono ${m} whitespace-pre-wrap break-words leading-[20px]`,children:[_??p.content,p.content===""&&" "]})]},v)},d=i.filter(p=>p.type==="add").length,u=i.filter(p=>p.type==="remove").length,f=n?l.flatMap(p=>{const v=[];for(let b=p.start;b<=p.end;b++)v.push({...i[b],_idx:b});return v}):i.map((p,v)=>({...p,_idx:v}));return c.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),c.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),c.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),c.jsx("button",{onClick:()=>a(p=>!p),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),c.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((p,v)=>{const b=v>0?f[v-1]:null,g=n&&b&&p._idx-b._idx>1;return c.jsxs("div",{children:[g&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),h(p,p._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function jD(s,e){const t=s.split(`
|
|
61
61
|
`),r=e.split(`
|
|
@@ -72,7 +72,7 @@ ${le}
|
|
|
72
72
|
`+ne.join(`
|
|
73
73
|
---
|
|
74
74
|
|
|
75
|
-
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";jr.navigate(es.TEAM,{agentId:s,prefillMessage:j})},R=async q=>{if(y?.file===q){_(null);return}try{const D=await te.agents.roleDiff(s,q);D.agentContent!=null&&D.templateContent!=null&&_({file:q,agent:D.agentContent,template:D.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const A={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=q=>{const D=A[q];return D?e(`agent:profilePage.filesTab.fileLabels.${D}`):q},I=m?.hasTemplate&&!m.isUpToDate,H=a?T.some(q=>q.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[I&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(q=>q.file).join(", ")]})]}),c.jsx("button",{onClick:()=>N(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(hs,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(q=>{const D=T.some(ne=>ne.file===q.name);return c.jsxs("button",{onClick:()=>P(q.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===q.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[q.name,D&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},q.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[H&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{te.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx($D,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(ED,{content:t.find(q=>q.name===a)?.content??"",editContent:l,setEditContent:q=>{h(q),O(!0)},dirty:g,onSave:k}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Dh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function ED({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(CD,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function AD(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function MD({tools:s}){const{t:e}=Mt(["agent","common"]),t=yD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(hs,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=Vk(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=AD(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(Fk,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function LD({agent:s}){const{t:e}=Mt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),_=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${_?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${_?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),_&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(hs,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(Dh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function ND({tools:s,agent:e}){const{t}=Mt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(MD,{tools:s}):c.jsx(LD,{agent:e})]})}function DD({agentId:s}){const{t:e}=Mt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,_]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(A=>{r(A),h(A.recentDailyLogs??""),u(A.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},k=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),N=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const R=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:R.map(A=>c.jsx("button",{onClick:()=>o(A.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===A.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:A.label},A.key))}),a==="entries"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Dh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((A,E)=>{const I=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(I?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${A.type==="fact"?"bg-blue-500/15 text-blue-600":A.type==="task"?"bg-green-500/15 text-green-600":A.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:A.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${I?"":"line-clamp-2"}`,children:A.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${A.importance>=7?"bg-red-500/15 text-red-500":A.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",A.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(A.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:I?"▲":"▼"})]})]}),I&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:A.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",A.type]}),A.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",A.importance]}),c.jsx("span",{children:new Date(A.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Dh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(A=>{const E=g===A.id,I=async()=>{if(E){O(null),x([]);return}O(A.id),_(!0);try{const H=await te.agents.getMemorySession(s,A.id);x(H.messages)}catch{x([])}_(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:I,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:A.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[A.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(A.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const H=new Map;for(const q of m)q.role==="tool"&&q.toolCallId&&H.set(q.toolCallId,q.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(q=>q.role!=="tool").map((q,D)=>c.jsxs("div",{className:"px-3 py-2",children:[(q.role==="user"||q.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${q.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${q.role}`,{defaultValue:q.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(Eo,{content:q.content,className:"text-xs text-fg-secondary"})})]}),q.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[q.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(Eo,{content:q.content,className:"text-xs text-fg-secondary"})})]}),q.toolCalls&&q.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:q.toolCalls.map(ne=>{let j;try{j=JSON.parse(ne.arguments)}catch{}const X={tool:ne.name,status:"done",args:j,result:H.get(ne.id)};return c.jsx(zk,{entry:{type:"tool",info:X}},ne.id)})})]})]},D))})})()})]},A.id)})})}),a==="daily"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:A=>h(A.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:N?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:k,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:A=>u(A.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 ID({agentId:s,initialData:e}){const{t}=Mt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(k=>k.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>St.on("agent:update",k=>{k.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(k){const T=k instanceof Error?k.message:String(k),N=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:N?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const _=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const k=Date.now()-new Date(P).getTime();if(k<0){const T=Math.abs(k);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return k<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(k/1e3)}):k<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(k/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(k/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(hs,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Hs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(WD,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Hs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Hs,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx(Eo,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const k=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(k?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${k?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),k&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Nh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:_(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function BD({taskId:s,isLive:e}){const{t}=Mt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0),[h,d]=S.useState("compact");if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(p=>{i(p.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const p=St.on("task:log",b=>{const g=b.payload;if(g.taskId!==s)return;const O={id:g.id,taskId:g.taskId,agentId:g.agentId,seq:g.seq,type:g.logType,content:g.content,metadata:g.metadata,createdAt:g.createdAt};i(m=>O.id&&m.some(x=>x.id===O.id)?m:[...m,O]),O.type==="text"&&a("")}),v=St.on("task:log:delta",b=>{const g=b.payload;g.taskId===s&&a(O=>O+g.text)});return()=>{p(),v()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(p=>Zk(p)),f=new Set(u.filter(p=>p.executionRound!=null).map(p=>p.executionRound)).size>1;return c.jsx("div",{className:"px-3 py-2",children:h==="compact"?c.jsx(Av,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):c.jsx(Mv,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Nh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Mt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0),[l,h]=S.useState("compact");if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?St.on("agent:activity_log",f=>{const p=f.payload;if(p.agentId!==s||p.activityId!==e)return;const v={seq:p.seq,type:p.type,content:p.content,metadata:p.metadata,createdAt:p.createdAt};n(b=>b.some(g=>g.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>qk(u,e,s)).filter(u=>u!==null);return c.jsx("div",{className:"px-3 py-2",children:l==="compact"?c.jsx(Av,{entries:d,isActive:t,onExpand:()=>h("full")}):c.jsx(Mv,{entries:d,isActive:t,onCollapse:()=>h("compact")})})}function hs({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Is({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Hs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const mv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],pv=5,gv=1440;function WD({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Mt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<pv||m>gv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=mv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),mv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:pv,max:gv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Dh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Ov(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const xv={0:"0",1:"1",2:"2",3:"3",4:"4"},bv={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},XD={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"},zD={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Ac={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:"🧠"},qD=["all","interaction","task","notification","system"],ZD={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"]},VD={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"},FD={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 yf(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 vv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Am(d,e),p=Am(u,e),v=FD[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=yf(i);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:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=yf(i);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:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=yf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function UD({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Mt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[_,C]=S.useState(!1),[P,k]=S.useState(!0),[T,N]=S.useState(null),R=50,A=3,E=S.useCallback(async(B=!0)=>{B&&d(!0);try{const U=u==="all"?void 0:u,se=p==="all"?void 0:p,[G,he]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:R,category:U,status:se})]);a(G),l(he),k((he.history?.length??0)>=R)}catch{}d(!1)},[s,u,p]),I=S.useCallback(async()=>{if(!o)return;const B=u==="all"?void 0:u,U=p==="all"?void 0:p;try{const se=await te.agents.getMailbox(s,{limit:R,offset:o.history.length,category:B,status:U});l(G=>G?{...G,history:[...G.history,...se.history]}:se),k((se.history?.length??0)>=R)}catch{}},[s,o,u,p]),H=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await E()},[s,E]);S.useEffect(()=>{g(e??null),m(e??null),E()},[E,e]);const q=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(U=>U.id===O)){q.current=!1;const U=document.getElementById(`mbx-${O}`);if(U){setTimeout(()=>U.scrollIntoView({behavior:"smooth",block:"center"}),100);const se=setTimeout(()=>m(null),3e3);return()=>clearTimeout(se)}}else P&&!q.current&&(q.current=!0,(async()=>{let U=o?.history??[],se=P;for(;se;)try{const G=await te.agents.getMailbox(s,{limit:R,offset:U.length}),he=[...U,...G.history];U=he,se=(G.history?.length??0)>=R;const V=G.history.some(M=>M.id===O);if(l(M=>M?{...M,history:he}:G),k(se),V||!se)break}catch{break}q.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let B=null;const U=G=>{G.payload?.agentId===s&&(B&&clearTimeout(B),B=setTimeout(()=>{B=null,E(!1)},500))},se=[St.on("agent:mailbox",U),St.on("agent:decision",U),St.on("agent:attention",U),St.on("agent:focus",U),St.on("agent:update",U),St.on("agent:triage",U)];return()=>{B&&clearTimeout(B),se.forEach(G=>G())}},[s,E]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const D=n?.mailboxDepth??n?.queuedItems?.length??0,ne=Bh(t).running,j=(()=>{const B=n?.attentionState??"idle";return B==="deciding"||B==="idle"&&D>0?"deciding":B!=="idle"&&!n?.currentFocus?"idle":B})(),X=j==="idle"&&o?.history?.some(B=>B.status==="processing"),z=(n?.attentionState??"idle")==="idle"&&D>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[ne?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${zD[j]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${j}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),ne?n?.currentFocus?(()=>{const B=vv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Ac[n.currentFocus.type]??"●"," ",c.jsx("span",{className:"text-fg-primary font-medium",children:B.title}),B.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:B.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>N(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():z?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:D,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):j==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:D})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{E()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),ne&&X&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{H()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const B=n.queuedItems,U=B.length>A,se=U&&!x?B.slice(0,A):B,G=B.reduce((he,V)=>(he[V.sourceType]=(he[V.sourceType]??0)+1,he),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:B.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(G).map(([he,V])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Ac[he]??"●"," ",V]},he))})]}),c.jsxs("div",{className:"space-y-1",children:[se.map((he,V)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:V+1}),c.jsx("span",{className:"text-sm",children:Ac[he.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${bv[he.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${xv[he.priority]??he.priority}`,{defaultValue:`P${he.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:he.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(he.queuedAt).toLocaleTimeString()})]},he.id)),U&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:B.length-A})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const B=_D(n.notebook,_);return c.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-quaternary leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:y_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[B.visible.map(U=>{const se=kD(U.updatedAt),G=i(`agent:profilePage.relative.${se.unit==="seconds"?"secondsAgo":se.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:se.count,hours:se.count}),he=U.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:U.key}),c.jsxs("span",{className:`text-[10px] ${he}`,children:["[",U.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:G})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:U.text.length>500?U.text.slice(0,500)+"…":U.text})]},U.key)}),B.collapsible&&c.jsx("button",{onClick:()=>C(!_),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:_?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:B.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Nh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const U=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4;return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${U?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!U,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:qD.map(B=>{const U=o?.sourceTypeCounts,se=B==="all"?U?Object.values(U).reduce((G,he)=>G+he,0):void 0:U?(ZD[B]??[]).reduce((G,he)=>G+(U[he]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(B),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===B?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[i(`agent:profilePage.mind.categoryFilters.${B}`),se!=null&&se>0&&c.jsx("span",{className:"ml-1 opacity-60",children:se})]},B)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(B=>{const U=o?.statusCounts,se=B.key==="all"?U?Object.values(U).reduce((G,he)=>G+he,0):void 0:U?.[B.key];return c.jsxs("button",{onClick:()=>v(B.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===B.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[B.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B.dot}`}),i(`agent:profilePage.mind.statusFilters.${B.key}`),se!=null&&se>0&&c.jsx("span",{className:"ml-1 opacity-60",children:se})]},B.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(B=>{const U=b===B.id,se=Ac[B.sourceType]??"●",G=vv(B,i),he=wD({itemStatus:B.status,agentRunning:ne,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:B.id}),V=B.metadata?.senderName,M=B.metadata?.senderRole,re=O===B.id;return c.jsxs("div",{id:`mbx-${B.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${re?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>g(U?null:B.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:U?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${he==="stale"?"bg-amber-400/70":VD[B.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:se}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${U?"":"truncate"}`,children:G.title}),G.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${G.badge.color}`,children:G.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${bv[B.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${xv[B.priority]??B.priority}`,{defaultValue:""})})]}),G.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${U?"":"truncate"}`,children:G.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(B.queuedAt).toLocaleString()}),B.completedAt&&c.jsxs("span",{children:["→ ",new Date(B.completedAt).toLocaleTimeString()]}),B.activity&&c.jsxs(c.Fragment,{children:[B.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Mm(B.activity.totalTokens)})}),B.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:B.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:B.sourceType}),r&&SD({agentRunning:ne,itemId:B.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:B.status})&&c.jsxs("button",{onClick:Y=>{Y.stopPropagation(),N(B.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),U&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[V&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:V}),M&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",M,")"]})]}),B.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(B.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:B.payload.content}),B.decisions&&B.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:B.decisions.map(Y=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${XD[Y.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:Y.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:Y.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(Y.createdAt).toLocaleTimeString()})]},Y.id))})]}),B.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:B.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${B.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:B.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),B.activity.type==="task"&&B.payload?.taskId?c.jsx(BD,{taskId:B.payload.taskId,isLive:!B.activity.endedAt}):c.jsx(Nh,{agentId:s,activityId:B.activity.id,isLive:!B.activity.endedAt})]}):he==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):he==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):B.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},B.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:I,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(qo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const B=T;N(null),te.agents.cancelProcessing(s,{itemId:B}).then(()=>{let U=0;const se=()=>{U+=1,E(),U<8&&window.setTimeout(se,750)};se()}).catch(()=>{E()})},onCancel:()=>N(null)})]})}function yv({agentId:s}){const{t:e}=Mt(["agent","common"]),t=Ih(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(P2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}jr.navigate(es.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=St.on("deliverable:created",()=>l()),d=St.on("deliverable:updated",()=>l()),u=St.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=Xk[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=bO[h.status]??bO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const HD=S.lazy(()=>Lv(()=>import("./index-C_QhfMcC.js").then(s=>s.b7),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),og=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Sv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function wv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Mt("team"),[o,l]=S.useState(null),[h,d]=S.useState(null),[u,f]=S.useState("overview"),p=r&&i?i:u,[v,b]=S.useState(""),[g,O]=S.useState(""),[m,x]=S.useState(!1),[y,_]=S.useState(!1),[C,P]=S.useState(""),[k,T]=S.useState(""),N=S.useRef(null),R=S.useRef(null),A=S.useRef(null),E=S.useRef(null),[I,H]=S.useState(!1),[q,D]=S.useState(!1),[ne,j]=S.useState(""),[X,z]=S.useState(""),[B,U]=S.useState(!1),[se,G]=S.useState([]),he=S.useRef(null),V=S.useCallback(async()=>{try{const we=(await te.teams.list()).teams.find(lt=>lt.id===s);we&&l(we);const Ve=await te.teams.status(s);G(Ve.agents)}catch{}},[s]),M=S.useCallback(async()=>{try{const Oe=await te.teams.getFile(s,"ANNOUNCEMENT.md");b(Oe.content)}catch{b("")}try{const Oe=await te.teams.getFile(s,"NORMS.md");O(Oe.content)}catch{O("")}},[s]);S.useEffect(()=>{f("overview"),V(),M()},[s,V,M]),S.useEffect(()=>{m&&R.current&&R.current.focus()},[m]),S.useEffect(()=>{y&&E.current&&E.current.focus()},[y]);const re=async(Oe,we)=>{H(!0);try{await te.teams.updateFile(s,Oe,we),Oe==="ANNOUNCEMENT.md"?(b(we),x(!1)):(O(we),_(!1))}catch{}H(!1)},Y=async()=>{ne.trim()&&(await te.teams.update(s,{name:ne.trim()}),D(!1),V())},ee=async()=>{await te.teams.update(s,{description:X}),U(!1),V()};if(!o)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const K=o.members.find(Oe=>Oe.agentRole==="manager"),Ce=se.filter(Oe=>Oe.status!=="offline").length,Re=p==="announcements"&&m||p==="norms"&&y;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Re?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Re?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[p==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:K?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const we=se.find(Xe=>Xe.id===Oe.id),Ve=Sv[we?.status??"offline"]??"bg-gray-500",lt=Oe.type==="agent";return c.jsxs("div",{onClick:()=>lt&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${lt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ms,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ve}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:we?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),lt&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),p==="announcements"&&c.jsx(Mc,{content:v,draft:C,setDraft:P,editing:m,setEditing:x,textareaRef:R,contentRef:N,saving:I,onSave:()=>re("ANNOUNCEMENT.md",C),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),p==="norms"&&c.jsx(Mc,{content:g,draft:k,setDraft:T,editing:y,setEditing:_,textareaRef:E,contentRef:A,saving:I,onSave:()=>re("NORMS.md",k),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),p==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),q?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:he,value:ne,onChange:Oe=>j(Oe.target.value),onKeyDown:Oe=>Oe.key==="Enter"&&Y(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:Y,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{j(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),B?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:X,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:ee,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(_v,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const Te=u==="announcements"&&m||u==="norms"&&y;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${Te?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Ce," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:Oe}=await te.teams.getFilesMap(o.id),we=o.members.filter(lt=>lt.type==="agent"),Ve={type:"team",name:Ev(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:we.map(lt=>({name:lt.name,roleName:lt.role,role:lt.agentRole??"worker",count:1,skills:[]}))}};await qm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ve,files:Oe}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Oe){d({title:"Hub",message:`Failed to publish: ${Oe}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:og.map(Oe=>c.jsxs("button",{onClick:()=>f(Oe.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===Oe.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Oe.icon," ",a(Oe.labelKey)]},Oe.key))})]}),c.jsxs("div",{className:`${Te?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:K?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const we=se.find(Xe=>Xe.id===Oe.id),Ve=Sv[we?.status??"offline"]??"bg-gray-500",lt=Oe.type==="agent";return c.jsxs("div",{onClick:()=>lt&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${lt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ms,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ve}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:we?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),lt&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&c.jsx(Mc,{content:v,draft:C,setDraft:P,editing:m,setEditing:x,textareaRef:R,contentRef:N,saving:I,onSave:()=>re("ANNOUNCEMENT.md",C),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&c.jsx(Mc,{content:g,draft:k,setDraft:T,editing:y,setEditing:_,textareaRef:E,contentRef:A,saving:I,onSave:()=>re("NORMS.md",k),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),q?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:he,value:ne,onChange:Oe=>j(Oe.target.value),onKeyDown:Oe=>Oe.key==="Enter"&&Y(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:Y,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{j(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),B?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:X,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:ee,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(_v,{teamId:s,teamName:o.name,onDeleted:e})]})]}),h&&c.jsx(qo,{alertOnly:!0,variant:h.variant??"primary",title:h.title,message:h.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function Mc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(HD,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function _v({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const YD=["chat","overview","deliverables"],GD=["chat","overview","announcements","norms","settings"];function KD(s,e){if(s==="chat")return e("page.chatTitle");if(ng.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=og.find(i=>i.key===s);return r?e(r.labelKey):s}function JD(s){if(s==="chat")return"💬";const e=ng.find(r=>r.key===s);if(e)return e.icon;const t=og.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}function Aa(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const eI=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Qr{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Qr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){const r=this.view.get(e);if(r!==t&&(r===void 0||r===Qr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Qr.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Qr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){eI(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Qr.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Qr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Qr.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Qr.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const tt=Qr.NEW_CHAT_ID,Ma=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";function tI(s){const e=S.useRef(new Qr),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,A)=>{const E=e.current.addStreamSession(R,A);Ma(R)&&Ks.markAgentStreaming(R,!0),E&&d()},[d]),p=S.useCallback(R=>e.current.hasLiveStream(R)||e.current.getPhase(R)==="streaming",[]),v=S.useCallback((R,A)=>{const E=e.current.removeStreamSession(R,A);Ma(R)&&Ks.markAgentStreaming(R,p(R)),E&&d()},[p,d]),b=S.useCallback((R,A)=>e.current.setActiveSession(R,A),[]),g=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const O=S.useCallback((R,A,E)=>{const I=e.current.updateMessages(R,A,E);I.displayChanged&&I.newMessages&&r(I.newMessages)},[]),m=S.useCallback((R,A,E)=>{e.current.updateMessages(R,A,E).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const H=e.current.getMessages(R);H&&e.current.currentConvKey===R&&r([...H])}))},[]),x=S.useCallback((R,A,E)=>{const I=e.current.appendActivity(R,A,E);I.displayChanged&&I.newActivities&&o(I.newActivities)},[]),y=S.useCallback(R=>e.current.getPhase(R),[]),_=S.useCallback(R=>e.current.beginLoad(R),[]),C=S.useCallback(R=>{e.current.beginStream(R),Ma(R)&&Ks.markAgentStreaming(R,!0)},[]),P=S.useCallback(R=>{e.current.endStream(R),Ma(R)&&Ks.markAgentStreaming(R,e.current.hasLiveStream(R))},[]),k=S.useCallback((R,A)=>{const E=e.current.abortStream(R,A);E&&Ma(R)&&Ks.markAgentStreaming(R,p(R)),E&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),T=S.useCallback((R,A)=>{e.current.resetConv(R,A),e.current.deleteBuffer(R)},[]),N=S.useCallback(async(R,A,E)=>{e.current.loadingSession=R,e.current.beginLoad(A);try{const I=await E(),H=e.current.applyLoadResult(A,R,I.messages);return H.displayChanged&&H.newMessages&&r(H.newMessages),{count:I.messages.length,hasMore:I.hasMore,oldestCursor:I.oldestCursor}}catch{return e.current.currentConvKey===A&&e.current.getPhase(A)!=="streaming"&&(r([]),e.current.completeLoad(A)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,getPhase:y,beginLoad:_,beginStream:C,endStream:P,resetConv:T,abortStream:k,loadAndDisplay:N,setActiveSession:b,clearActiveSession:g,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:v,getStreamSession:u,saveSessionToCache:(R,A)=>e.current.saveToCache(),restoreSessionFromCache:(R,A)=>{const E=e.current.restoreFromCache(R,A);return r(E??[]),E},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,A)=>{const E=e.current.updateMessages(R,()=>A);E.displayChanged&&E.newMessages&&r(E.newMessages)}}}function Sf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function kv(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function Cv(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function sI(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Xe=>{if(Xe)for(const[Qe,oe]of e.current)oe===Xe&&e.current.delete(Qe)},i=Xe=>{if(Xe)for(const[Qe,oe]of t.current)oe===Xe&&t.current.delete(Qe)},n=Xe=>{const Qe=e.current.get(Xe);Qe&&(Qe.abort(),e.current.delete(Xe));const oe=t.current.get(Xe);oe&&(oe.abort(),t.current.delete(Xe))},a=Xe=>{const Qe=e.current.get(tt);Qe&&e.current.size===1&&(e.current.delete(tt),e.current.set(Xe,Qe))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:_,abortStream:C,clearStreamSession:P,setStreamSession:k,getStreamSession:T,setActiveSession:N,incrementSending:R,decrementSending:A,loadAndDisplay:E,thinkingTimeoutRef:I,sessionSwitchSeqRef:H,setSending:q,setActivities:D,setInput:ne,setChatContext:j,setPendingImages:X,setMentionDropdown:z,setChatReplyTo:B,setActiveSessionId:U,setStoredActiveSession:se,setOpenSessionTabs:G,setSessions:he,setLoadingChat:V,setWindowBounds:M,setThinkingAgents:re,makeConvKey:Y,makeDmChannel:ee,addRecentMsgId:K,resumeChatScrollFollow:Ce,loadSessions:Re}=s,{t:Te}=s,Oe=S.useCallback(async(Xe,Qe)=>{const oe=H.current,Ke=g.current===Qe&&(b(Qe)?.length??0)===0;Ke&&V(!0);try{const{count:nt,hasMore:Ot,oldestCursor:Wt}=await E(Xe,Qe,async()=>{const At=await te.sessions.getMessages(Xe,50);return{messages:Uk(At.messages.map(rh).filter(je=>je.sender!=="agent"||je.text||je.segments&&je.segments.length>0||je.isStreaming)),hasMore:At.hasMore,oldestCursor:At.messages[0]?new Date(At.messages[0].createdAt).toISOString():null}});return M(Xe,{hasMore:Ot,oldestCursor:Wt}),nt}finally{Ke&&g.current===Qe&&H.current===oe&&V(!1)}},[E,b,H]),we=()=>{const Xe=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Xe){const Qe=Sf(f.current.activeSessionId,tt);Qe.kind==="cancel"&&te.agents.cancelProcessing(Xe,Qe.target).catch(()=>{})}n(f.current.activeSessionId??tt),Xe&&f.current.activeSessionId&&f.current.activeSessionId!==tt&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ve=S.useCallback(async(Xe,Qe,oe)=>{if(!Xe||!Qe||Qe===tt||l.current.has(Qe))return;let Ke=null;try{const nt=e.current.get(Qe);if(nt&&!nt.signal.aborted&&T(oe)?.has(Qe)){g.current===oe&&q(!0);return}const Ot=()=>{Hk({liveSessions:T(oe),sessionId:Qe,placeholderId:tt})&&(P(oe,Qe),g.current===oe&&(q(!1),O(oe,fe=>ru(fe),Qe)))},Wt=`${Xe}:${Qe}`,At=o.current.get(Wt)??0;if(Date.now()-At<1500)return;o.current.set(Wt,Date.now());let vt;const je=await te.sessions.streamStatus(Xe,Qe);je.messageId&&(vt=je.messageId);const Pt=b(oe)??[],Ps=je.status==="streaming",pt=Yk(Pt,{expectedMessageId:je.messageId,allowCurrentTurnPartial:Ps}),_t=!!je.active&&(je.status==="done"||je.status==="error")&&!!pt?.isStreaming;if(kv({aborted:!1,sawTerminal:_t,serverStatus:Cv(je.status)})==="finalize"){Ot();return}o.current.set(Wt,Date.now());for(const fe of t.current.values())fe.abort();t.current.clear(),Ke=new AbortController,t.current.set(Qe,Ke),y(oe),q(!0),k(oe,Qe);let ht=pt?.id;if(!pt||pt.isError)ht=`reattach_${Date.now()}`,O(oe,fe=>[...fe,{id:ht,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],Qe);else{const fe=(pt.segments??[]).filter(be=>be.type==="tool").map(be=>be.status==="stopped"||be.status==="running"?{...be,status:"running"}:be);O(oe,be=>be.map(_e=>_e.id===pt.id?{..._e,text:"",isStreaming:!0,isStopped:!1,segments:fe,committedSegments:void 0}:_e),Qe)}const st=fe=>{g.current===oe&&(u.current=Date.now(),m(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ve=>ve.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ve,ye)=>({m:ve,j:ye})).reverse().find(ve=>ve.m.sender==="agent"&&ve.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];return _e[Fe]={...J,text:(J.text??"")+fe,segments:vO(J.segments??[],fe),isStreaming:!0},_e},Qe))},bt=fe=>{g.current===oe&&(u.current=Date.now(),m(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ve=>ve.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ve,ye)=>({m:ve,j:ye})).reverse().find(ve=>ve.m.sender==="agent"&&ve.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];return _e[Fe]={...J,segments:yO(J.segments??[],fe),isStreaming:!0},_e},Qe))},$t=fe=>{if(g.current===oe&&(u.current=Date.now(),fe.phase!=="heartbeat")){if((fe.phase==="start"||fe.phase==="end")&&x(oe,{...fe,phase:fe.phase,ts:Date.now()},Qe),fe.phase==="start"){const be=`${fe.tool}_${Date.now()}`,_e=new Date().toISOString(),Ne=Fe=>{const J=[...Fe];for(let ve=J.length-1;ve>=0;ve--){const ye=J[ve];if(ye.type==="tool"&&ye.tool===fe.tool&&(ye.status==="running"||ye.status==="stopped"))return J[ve]={...ye,status:"running",args:fe.arguments??ye.args},J}return J.push({type:"tool",key:be,tool:fe.tool,status:"running",args:fe.arguments,createdAt:_e}),J};O(oe,Fe=>{const J=[...Fe],ve=ht?J.findIndex(ze=>ze.id===ht):-1;if(ve<0)return Fe;const ye=Ne(J[ve].segments??[]),ge=J[ve].committedSegments,ke=ge&&Ne(ge);return J[ve]={...J[ve],segments:ye,committedSegments:ke,isStreaming:!0},J},Qe)}else if(fe.phase==="end"){const be=new Date().toISOString(),_e=Ne=>{const Fe=[...Ne];for(let J=Fe.length-1;J>=0;J--){const ve=Fe[J];if(ve.type==="tool"&&ve.tool===fe.tool&&(ve.status==="running"||ve.status==="stopped")){Fe[J]={...ve,status:fe.success===!1?"error":"done",args:fe.arguments??ve.args,result:fe.result,error:fe.error,durationMs:fe.durationMs,liveOutput:void 0,createdAt:be};break}}return Fe};O(oe,Ne=>{const Fe=[...Ne],J=ht?Fe.findIndex(ke=>ke.id===ht):-1;if(J<0)return Ne;const ve=_e(Fe[J].segments??[]),ye=Fe[J].committedSegments,ge=ye&&_e(ye);return Fe[J]={...Fe[J],segments:ve,committedSegments:ge,isStreaming:!0},Fe},Qe)}else if(fe.phase==="subagent_progress"&&fe.subagentEvent){const be=_e=>{const Ne=[..._e];for(let Fe=Ne.length-1;Fe>=0;Fe--){const J=Ne[Fe];if(J.type==="tool"&&(J.tool==="spawn_subagent"||J.tool==="spawn_subagents")&&(J.status==="running"||J.status==="stopped")){Ne[Fe]={...J,status:"running",subagentLogs:SO(J.subagentLogs,fe.subagentEvent)};break}}return Ne};m(oe,_e=>{const Ne=[..._e],Fe=ht?Ne.findIndex(ge=>ge.id===ht):-1;if(Fe<0)return _e;const J=be(Ne[Fe].segments??[]),ve=Ne[Fe].committedSegments,ye=ve&&be(ve);return Ne[Fe]={...Ne[Fe],segments:J,committedSegments:ye,isStreaming:!0},Ne},Qe)}}},Tt=fe=>{g.current===oe&&(u.current=Date.now(),O(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(J=>J.id===ht):-1;if(Ne<0)return be;const Fe=[..._e[Ne].committedSegments??[]];if(fe.type==="thinking_commit")Fe.push({type:"text",content:"",thinking:fe.content,createdAt:fe.createdAt});else if(fe.type==="text_commit")Fe.push({type:"text",content:fe.content,createdAt:fe.createdAt});else return be;return _e[Ne]={..._e[Ne],committedSegments:Fe,isStreaming:!0},_e},Qe))},xt=fe=>{if(g.current!==oe)return;u.current=Date.now();const be=(fe.segments??[]).map((_e,Ne)=>_e.type==="tool"?{type:"tool",key:`${_e.tool}_${Ne}`,tool:_e.tool??"tool",status:_e.status==="error"?"error":_e.status==="running"||_e.status==="stopped"?"running":"done",args:_e.arguments,result:_e.result,error:_e.error,durationMs:_e.durationMs,createdAt:_e.createdAt,..._e.subagentLogs?.length?{subagentLogs:_e.subagentLogs}:{}}:{type:"text",content:_e.content??"",thinking:_e.thinking,createdAt:_e.createdAt});O(oe,_e=>{const Ne=[..._e],Fe=ht?Ne.findIndex(J=>J.id===ht):-1;return Fe<0?_e:(Ne[Fe]={...Ne[Fe],text:fe.content||Ne[Fe].text,segments:be,committedSegments:be,isStreaming:!0,isStopped:!1},Ne)},Qe);for(const _e of be)_e.type==="tool"&&x(oe,{tool:_e.tool,phase:_e.status==="running"||_e.status==="stopped"?"start":"end",success:_e.status!=="error",arguments:_e.args,result:_e.result,error:_e.error,durationMs:_e.durationMs,ts:Date.now()},Qe)},le=8;let ae=null;const Me=fe=>{g.current===oe&&O(oe,be=>{const _e=be.map((Fe,J)=>({m:Fe,j:J})).reverse().find(Fe=>Fe.m.sender==="agent"&&Fe.m.isStreaming)?.j??-1;if(_e<0||be[_e].reconnecting===fe)return be;const Ne=[...be];return Ne[_e]={...Ne[_e],reconnecting:fe},Ne},Qe)};for(let fe=1;fe<=le;fe++){if(Ke.signal.aborted)return;try{ae=await te.sessions.reattachStream(Xe,Qe,{onChunk:st,onThinking:bt,onActivity:$t,onCommit:Tt,onSnapshot:xt},Ke.signal,0)}catch(_e){if(Ke.signal.aborted)throw _e;ae=null}if(!ae||!ae.attached){ae=null;break}if(ae.terminal)break;Me(!0);const be=await te.sessions.streamStatus(Xe,Qe).catch(()=>null);if(be?.messageId&&(vt=be.messageId),!be||!be.active||be.status==="not_found"||be.status==="idle"){Me(!1),ae=null;break}await new Promise(_e=>setTimeout(_e,Math.min(800*fe,4e3))),Me(!1)}if(!ae){_(oe),P(oe,Qe),g.current===oe&&(q(!1),vt&&ht&&O(oe,fe=>ka(fe,ht,vt),Qe),Oe(Qe,oe).catch(()=>{}).finally(()=>{O(oe,fe=>ru(fe,"done"),Qe)})),i(Ke);return}if(g.current===oe){let fe;O(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ye=>ye.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ye,ge)=>({m:ye,j:ge})).reverse().find(ye=>ye.m.sender==="agent"&&ye.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];if(!J.isStreaming)return be;fe=J.id;const ve=ae.segments?.length?wO(ae.segments,J.segments):void 0;return _e[Fe]={...J,text:ae.content||J.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ve?{segments:ve,committedSegments:ve}:{}},_e},Qe),fe&&O(oe,be=>ka(be,fe,ae.messageId),Qe),q(!1)}_(oe),P(oe,Qe),i(Ke)}catch(nt){const Ot=Ke?[...t.current.values()].includes(Ke):!1;if(i(Ke),_(oe),P(oe,Qe),g.current===oe&&(q(!1),Ot&&O(oe,Wt=>ru(Wt),Qe)),nt instanceof Error&&nt.name==="AbortError")return}},[x,y,_,T,b,k,O,m]),lt=S.useCallback(async(Xe,Qe)=>{const oe=f.current,Ke=!Xe&&oe.chatContext.length>0?oe.chatContext.map(_t=>_t.content).join(`
|
|
75
|
+
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";jr.navigate(es.TEAM,{agentId:s,prefillMessage:j})},R=async q=>{if(y?.file===q){_(null);return}try{const D=await te.agents.roleDiff(s,q);D.agentContent!=null&&D.templateContent!=null&&_({file:q,agent:D.agentContent,template:D.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const A={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=q=>{const D=A[q];return D?e(`agent:profilePage.filesTab.fileLabels.${D}`):q},I=m?.hasTemplate&&!m.isUpToDate,H=a?T.some(q=>q.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[I&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(q=>q.file).join(", ")]})]}),c.jsx("button",{onClick:()=>N(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(hs,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(q=>{const D=T.some(ne=>ne.file===q.name);return c.jsxs("button",{onClick:()=>P(q.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===q.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[q.name,D&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},q.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[H&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{te.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx($D,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(ED,{content:t.find(q=>q.name===a)?.content??"",editContent:l,setEditContent:q=>{h(q),O(!0)},dirty:g,onSave:k}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Dh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function ED({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(CD,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function AD(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function MD({tools:s}){const{t:e}=Mt(["agent","common"]),t=yD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(hs,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=Vk(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=AD(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(Fk,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function LD({agent:s}){const{t:e}=Mt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),_=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${_?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${_?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),_&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(hs,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(Dh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function ND({tools:s,agent:e}){const{t}=Mt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(MD,{tools:s}):c.jsx(LD,{agent:e})]})}function DD({agentId:s}){const{t:e}=Mt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,_]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(A=>{r(A),h(A.recentDailyLogs??""),u(A.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},k=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),N=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const R=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:R.map(A=>c.jsx("button",{onClick:()=>o(A.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===A.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:A.label},A.key))}),a==="entries"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Dh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((A,E)=>{const I=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(I?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${A.type==="fact"?"bg-blue-500/15 text-blue-600":A.type==="task"?"bg-green-500/15 text-green-600":A.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:A.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${I?"":"line-clamp-2"}`,children:A.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${A.importance>=7?"bg-red-500/15 text-red-500":A.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",A.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(A.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:I?"▲":"▼"})]})]}),I&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:A.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",A.type]}),A.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",A.importance]}),c.jsx("span",{children:new Date(A.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Dh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(A=>{const E=g===A.id,I=async()=>{if(E){O(null),x([]);return}O(A.id),_(!0);try{const H=await te.agents.getMemorySession(s,A.id);x(H.messages)}catch{x([])}_(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:I,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:A.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[A.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(A.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const H=new Map;for(const q of m)q.role==="tool"&&q.toolCallId&&H.set(q.toolCallId,q.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(q=>q.role!=="tool").map((q,D)=>c.jsxs("div",{className:"px-3 py-2",children:[(q.role==="user"||q.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${q.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${q.role}`,{defaultValue:q.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(Eo,{content:q.content,className:"text-xs text-fg-secondary"})})]}),q.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[q.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(Eo,{content:q.content,className:"text-xs text-fg-secondary"})})]}),q.toolCalls&&q.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:q.toolCalls.map(ne=>{let j;try{j=JSON.parse(ne.arguments)}catch{}const X={tool:ne.name,status:"done",args:j,result:H.get(ne.id)};return c.jsx(zk,{entry:{type:"tool",info:X}},ne.id)})})]})]},D))})})()})]},A.id)})})}),a==="daily"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:A=>h(A.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(hs,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:N?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:k,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:A=>u(A.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 ID({agentId:s,initialData:e}){const{t}=Mt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(k=>k.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>St.on("agent:update",k=>{k.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(k){const T=k instanceof Error?k.message:String(k),N=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:N?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const _=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const k=Date.now()-new Date(P).getTime();if(k<0){const T=Math.abs(k);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return k<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(k/1e3)}):k<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(k/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(k/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(hs,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Hs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(WD,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Hs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Hs,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx(Eo,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const k=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(k?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${k?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),k&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Nh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(hs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:_(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function BD({taskId:s,isLive:e}){const{t}=Mt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0),[h,d]=S.useState("compact");if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(p=>{i(p.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const p=St.on("task:log",b=>{const g=b.payload;if(g.taskId!==s)return;const O={id:g.id,taskId:g.taskId,agentId:g.agentId,seq:g.seq,type:g.logType,content:g.content,metadata:g.metadata,createdAt:g.createdAt};i(m=>O.id&&m.some(x=>x.id===O.id)?m:[...m,O]),O.type==="text"&&a("")}),v=St.on("task:log:delta",b=>{const g=b.payload;g.taskId===s&&a(O=>O+g.text)});return()=>{p(),v()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(p=>Zk(p)),f=new Set(u.filter(p=>p.executionRound!=null).map(p=>p.executionRound)).size>1;return c.jsx("div",{className:"px-3 py-2",children:h==="compact"?c.jsx(Av,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):c.jsx(Mv,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Nh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Mt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0),[l,h]=S.useState("compact");if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?St.on("agent:activity_log",f=>{const p=f.payload;if(p.agentId!==s||p.activityId!==e)return;const v={seq:p.seq,type:p.type,content:p.content,metadata:p.metadata,createdAt:p.createdAt};n(b=>b.some(g=>g.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>qk(u,e,s)).filter(u=>u!==null);return c.jsx("div",{className:"px-3 py-2",children:l==="compact"?c.jsx(Av,{entries:d,isActive:t,onExpand:()=>h("full")}):c.jsx(Mv,{entries:d,isActive:t,onCollapse:()=>h("compact")})})}function hs({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Is({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Hs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const mv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],pv=5,gv=1440;function WD({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Mt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<pv||m>gv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=mv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),mv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:pv,max:gv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Dh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Ov(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const xv={0:"0",1:"1",2:"2",3:"3",4:"4"},bv={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},XD={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"},zD={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Ac={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:"🧠"},qD=["all","interaction","task","notification","system"],ZD={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"]},VD={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"},FD={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 yf(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 vv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Am(d,e),p=Am(u,e),v=FD[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=yf(i);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:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=yf(i);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:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=yf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function UD({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Mt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[_,C]=S.useState(!1),[P,k]=S.useState(!0),[T,N]=S.useState(null),R=50,A=3,E=S.useCallback(async(B=!0)=>{B&&d(!0);try{const U=u==="all"?void 0:u,se=p==="all"?void 0:p,[G,he]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:R,category:U,status:se})]);a(G),l(he),k((he.history?.length??0)>=R)}catch{}d(!1)},[s,u,p]),I=S.useCallback(async()=>{if(!o)return;const B=u==="all"?void 0:u,U=p==="all"?void 0:p;try{const se=await te.agents.getMailbox(s,{limit:R,offset:o.history.length,category:B,status:U});l(G=>G?{...G,history:[...G.history,...se.history]}:se),k((se.history?.length??0)>=R)}catch{}},[s,o,u,p]),H=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await E()},[s,E]);S.useEffect(()=>{g(e??null),m(e??null),E()},[E,e]);const q=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(U=>U.id===O)){q.current=!1;const U=document.getElementById(`mbx-${O}`);if(U){setTimeout(()=>U.scrollIntoView({behavior:"smooth",block:"center"}),100);const se=setTimeout(()=>m(null),3e3);return()=>clearTimeout(se)}}else P&&!q.current&&(q.current=!0,(async()=>{let U=o?.history??[],se=P;for(;se;)try{const G=await te.agents.getMailbox(s,{limit:R,offset:U.length}),he=[...U,...G.history];U=he,se=(G.history?.length??0)>=R;const V=G.history.some(M=>M.id===O);if(l(M=>M?{...M,history:he}:G),k(se),V||!se)break}catch{break}q.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let B=null;const U=G=>{G.payload?.agentId===s&&(B&&clearTimeout(B),B=setTimeout(()=>{B=null,E(!1)},500))},se=[St.on("agent:mailbox",U),St.on("agent:decision",U),St.on("agent:attention",U),St.on("agent:focus",U),St.on("agent:update",U),St.on("agent:triage",U)];return()=>{B&&clearTimeout(B),se.forEach(G=>G())}},[s,E]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const D=n?.mailboxDepth??n?.queuedItems?.length??0,ne=Bh(t).running,j=(()=>{const B=n?.attentionState??"idle";return B==="deciding"||B==="idle"&&D>0?"deciding":B!=="idle"&&!n?.currentFocus?"idle":B})(),X=j==="idle"&&o?.history?.some(B=>B.status==="processing"),z=(n?.attentionState??"idle")==="idle"&&D>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[ne?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${zD[j]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${j}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),ne?n?.currentFocus?(()=>{const B=vv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Ac[n.currentFocus.type]??"●"," ",c.jsx("span",{className:"text-fg-primary font-medium",children:B.title}),B.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:B.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>N(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():z?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:D,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):j==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:D})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{E()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),ne&&X&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{H()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const B=n.queuedItems,U=B.length>A,se=U&&!x?B.slice(0,A):B,G=B.reduce((he,V)=>(he[V.sourceType]=(he[V.sourceType]??0)+1,he),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:B.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(G).map(([he,V])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Ac[he]??"●"," ",V]},he))})]}),c.jsxs("div",{className:"space-y-1",children:[se.map((he,V)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:V+1}),c.jsx("span",{className:"text-sm",children:Ac[he.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${bv[he.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${xv[he.priority]??he.priority}`,{defaultValue:`P${he.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:he.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(he.queuedAt).toLocaleTimeString()})]},he.id)),U&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:B.length-A})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const B=_D(n.notebook,_);return c.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-quaternary leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:y_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[B.visible.map(U=>{const se=kD(U.updatedAt),G=i(`agent:profilePage.relative.${se.unit==="seconds"?"secondsAgo":se.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:se.count,hours:se.count}),he=U.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:U.key}),c.jsxs("span",{className:`text-[10px] ${he}`,children:["[",U.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:G})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:U.text.length>500?U.text.slice(0,500)+"…":U.text})]},U.key)}),B.collapsible&&c.jsx("button",{onClick:()=>C(!_),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:_?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:B.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Nh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const U=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4;return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${U?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!U,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:qD.map(B=>{const U=o?.sourceTypeCounts,se=B==="all"?U?Object.values(U).reduce((G,he)=>G+he,0):void 0:U?(ZD[B]??[]).reduce((G,he)=>G+(U[he]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(B),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===B?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[i(`agent:profilePage.mind.categoryFilters.${B}`),se!=null&&se>0&&c.jsx("span",{className:"ml-1 opacity-60",children:se})]},B)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(B=>{const U=o?.statusCounts,se=B.key==="all"?U?Object.values(U).reduce((G,he)=>G+he,0):void 0:U?.[B.key];return c.jsxs("button",{onClick:()=>v(B.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===B.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[B.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B.dot}`}),i(`agent:profilePage.mind.statusFilters.${B.key}`),se!=null&&se>0&&c.jsx("span",{className:"ml-1 opacity-60",children:se})]},B.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(B=>{const U=b===B.id,se=Ac[B.sourceType]??"●",G=vv(B,i),he=wD({itemStatus:B.status,agentRunning:ne,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:B.id}),V=B.metadata?.senderName,M=B.metadata?.senderRole,re=O===B.id;return c.jsxs("div",{id:`mbx-${B.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${re?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>g(U?null:B.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:U?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${he==="stale"?"bg-amber-400/70":VD[B.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:se}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${U?"":"truncate"}`,children:G.title}),G.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${G.badge.color}`,children:G.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${bv[B.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${xv[B.priority]??B.priority}`,{defaultValue:""})})]}),G.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${U?"":"truncate"}`,children:G.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(B.queuedAt).toLocaleString()}),B.completedAt&&c.jsxs("span",{children:["→ ",new Date(B.completedAt).toLocaleTimeString()]}),B.activity&&c.jsxs(c.Fragment,{children:[B.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Mm(B.activity.totalTokens)})}),B.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:B.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:B.sourceType}),r&&SD({agentRunning:ne,itemId:B.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:B.status})&&c.jsxs("button",{onClick:Y=>{Y.stopPropagation(),N(B.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),U&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[V&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:V}),M&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",M,")"]})]}),B.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(B.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:B.payload.content}),B.decisions&&B.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:B.decisions.map(Y=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${XD[Y.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:Y.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:Y.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(Y.createdAt).toLocaleTimeString()})]},Y.id))})]}),B.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:B.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${B.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:B.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),B.activity.type==="task"&&B.payload?.taskId?c.jsx(BD,{taskId:B.payload.taskId,isLive:!B.activity.endedAt}):c.jsx(Nh,{agentId:s,activityId:B.activity.id,isLive:!B.activity.endedAt})]}):he==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):he==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):B.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},B.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:I,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(qo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const B=T;N(null),te.agents.cancelProcessing(s,{itemId:B}).then(()=>{let U=0;const se=()=>{U+=1,E(),U<8&&window.setTimeout(se,750)};se()}).catch(()=>{E()})},onCancel:()=>N(null)})]})}function yv({agentId:s}){const{t:e}=Mt(["agent","common"]),t=Ih(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(P2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}jr.navigate(es.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=St.on("deliverable:created",()=>l()),d=St.on("deliverable:updated",()=>l()),u=St.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=Xk[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=bO[h.status]??bO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const HD=S.lazy(()=>Lv(()=>import("./index-D8vskks7.js").then(s=>s.b7),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),og=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Sv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function wv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Mt("team"),[o,l]=S.useState(null),[h,d]=S.useState(null),[u,f]=S.useState("overview"),p=r&&i?i:u,[v,b]=S.useState(""),[g,O]=S.useState(""),[m,x]=S.useState(!1),[y,_]=S.useState(!1),[C,P]=S.useState(""),[k,T]=S.useState(""),N=S.useRef(null),R=S.useRef(null),A=S.useRef(null),E=S.useRef(null),[I,H]=S.useState(!1),[q,D]=S.useState(!1),[ne,j]=S.useState(""),[X,z]=S.useState(""),[B,U]=S.useState(!1),[se,G]=S.useState([]),he=S.useRef(null),V=S.useCallback(async()=>{try{const we=(await te.teams.list()).teams.find(lt=>lt.id===s);we&&l(we);const Ve=await te.teams.status(s);G(Ve.agents)}catch{}},[s]),M=S.useCallback(async()=>{try{const Oe=await te.teams.getFile(s,"ANNOUNCEMENT.md");b(Oe.content)}catch{b("")}try{const Oe=await te.teams.getFile(s,"NORMS.md");O(Oe.content)}catch{O("")}},[s]);S.useEffect(()=>{f("overview"),V(),M()},[s,V,M]),S.useEffect(()=>{m&&R.current&&R.current.focus()},[m]),S.useEffect(()=>{y&&E.current&&E.current.focus()},[y]);const re=async(Oe,we)=>{H(!0);try{await te.teams.updateFile(s,Oe,we),Oe==="ANNOUNCEMENT.md"?(b(we),x(!1)):(O(we),_(!1))}catch{}H(!1)},Y=async()=>{ne.trim()&&(await te.teams.update(s,{name:ne.trim()}),D(!1),V())},ee=async()=>{await te.teams.update(s,{description:X}),U(!1),V()};if(!o)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const K=o.members.find(Oe=>Oe.agentRole==="manager"),Ce=se.filter(Oe=>Oe.status!=="offline").length,Re=p==="announcements"&&m||p==="norms"&&y;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Re?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Re?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[p==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:K?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const we=se.find(Xe=>Xe.id===Oe.id),Ve=Sv[we?.status??"offline"]??"bg-gray-500",lt=Oe.type==="agent";return c.jsxs("div",{onClick:()=>lt&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${lt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ms,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ve}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:we?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),lt&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),p==="announcements"&&c.jsx(Mc,{content:v,draft:C,setDraft:P,editing:m,setEditing:x,textareaRef:R,contentRef:N,saving:I,onSave:()=>re("ANNOUNCEMENT.md",C),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),p==="norms"&&c.jsx(Mc,{content:g,draft:k,setDraft:T,editing:y,setEditing:_,textareaRef:E,contentRef:A,saving:I,onSave:()=>re("NORMS.md",k),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),p==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),q?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:he,value:ne,onChange:Oe=>j(Oe.target.value),onKeyDown:Oe=>Oe.key==="Enter"&&Y(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:Y,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{j(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),B?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:X,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:ee,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(_v,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const Te=u==="announcements"&&m||u==="norms"&&y;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${Te?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Ce," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:Oe}=await te.teams.getFilesMap(o.id),we=o.members.filter(lt=>lt.type==="agent"),Ve={type:"team",name:Ev(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:we.map(lt=>({name:lt.name,roleName:lt.role,role:lt.agentRole??"worker",count:1,skills:[]}))}};await qm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ve,files:Oe}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Oe){d({title:"Hub",message:`Failed to publish: ${Oe}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:og.map(Oe=>c.jsxs("button",{onClick:()=>f(Oe.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===Oe.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Oe.icon," ",a(Oe.labelKey)]},Oe.key))})]}),c.jsxs("div",{className:`${Te?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:K?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const we=se.find(Xe=>Xe.id===Oe.id),Ve=Sv[we?.status??"offline"]??"bg-gray-500",lt=Oe.type==="agent";return c.jsxs("div",{onClick:()=>lt&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${lt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ms,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ve}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:we?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),lt&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&c.jsx(Mc,{content:v,draft:C,setDraft:P,editing:m,setEditing:x,textareaRef:R,contentRef:N,saving:I,onSave:()=>re("ANNOUNCEMENT.md",C),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&c.jsx(Mc,{content:g,draft:k,setDraft:T,editing:y,setEditing:_,textareaRef:E,contentRef:A,saving:I,onSave:()=>re("NORMS.md",k),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),q?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:he,value:ne,onChange:Oe=>j(Oe.target.value),onKeyDown:Oe=>Oe.key==="Enter"&&Y(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:Y,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{j(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),B?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:X,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:ee,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(_v,{teamId:s,teamName:o.name,onDeleted:e})]})]}),h&&c.jsx(qo,{alertOnly:!0,variant:h.variant??"primary",title:h.title,message:h.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function Mc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(HD,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function _v({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const YD=["chat","overview","deliverables"],GD=["chat","overview","announcements","norms","settings"];function KD(s,e){if(s==="chat")return e("page.chatTitle");if(ng.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=og.find(i=>i.key===s);return r?e(r.labelKey):s}function JD(s){if(s==="chat")return"💬";const e=ng.find(r=>r.key===s);if(e)return e.icon;const t=og.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}function Aa(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const eI=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Qr{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Qr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){const r=this.view.get(e);if(r!==t&&(r===void 0||r===Qr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Qr.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Qr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){eI(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Qr.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Qr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Qr.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Qr.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const tt=Qr.NEW_CHAT_ID,Ma=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";function tI(s){const e=S.useRef(new Qr),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,A)=>{const E=e.current.addStreamSession(R,A);Ma(R)&&Ks.markAgentStreaming(R,!0),E&&d()},[d]),p=S.useCallback(R=>e.current.hasLiveStream(R)||e.current.getPhase(R)==="streaming",[]),v=S.useCallback((R,A)=>{const E=e.current.removeStreamSession(R,A);Ma(R)&&Ks.markAgentStreaming(R,p(R)),E&&d()},[p,d]),b=S.useCallback((R,A)=>e.current.setActiveSession(R,A),[]),g=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const O=S.useCallback((R,A,E)=>{const I=e.current.updateMessages(R,A,E);I.displayChanged&&I.newMessages&&r(I.newMessages)},[]),m=S.useCallback((R,A,E)=>{e.current.updateMessages(R,A,E).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const H=e.current.getMessages(R);H&&e.current.currentConvKey===R&&r([...H])}))},[]),x=S.useCallback((R,A,E)=>{const I=e.current.appendActivity(R,A,E);I.displayChanged&&I.newActivities&&o(I.newActivities)},[]),y=S.useCallback(R=>e.current.getPhase(R),[]),_=S.useCallback(R=>e.current.beginLoad(R),[]),C=S.useCallback(R=>{e.current.beginStream(R),Ma(R)&&Ks.markAgentStreaming(R,!0)},[]),P=S.useCallback(R=>{e.current.endStream(R),Ma(R)&&Ks.markAgentStreaming(R,e.current.hasLiveStream(R))},[]),k=S.useCallback((R,A)=>{const E=e.current.abortStream(R,A);E&&Ma(R)&&Ks.markAgentStreaming(R,p(R)),E&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),T=S.useCallback((R,A)=>{e.current.resetConv(R,A),e.current.deleteBuffer(R)},[]),N=S.useCallback(async(R,A,E)=>{e.current.loadingSession=R,e.current.beginLoad(A);try{const I=await E(),H=e.current.applyLoadResult(A,R,I.messages);return H.displayChanged&&H.newMessages&&r(H.newMessages),{count:I.messages.length,hasMore:I.hasMore,oldestCursor:I.oldestCursor}}catch{return e.current.currentConvKey===A&&e.current.getPhase(A)!=="streaming"&&(r([]),e.current.completeLoad(A)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,getPhase:y,beginLoad:_,beginStream:C,endStream:P,resetConv:T,abortStream:k,loadAndDisplay:N,setActiveSession:b,clearActiveSession:g,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:v,getStreamSession:u,saveSessionToCache:(R,A)=>e.current.saveToCache(),restoreSessionFromCache:(R,A)=>{const E=e.current.restoreFromCache(R,A);return r(E??[]),E},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,A)=>{const E=e.current.updateMessages(R,()=>A);E.displayChanged&&E.newMessages&&r(E.newMessages)}}}function Sf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function kv(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function Cv(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function sI(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Xe=>{if(Xe)for(const[Qe,oe]of e.current)oe===Xe&&e.current.delete(Qe)},i=Xe=>{if(Xe)for(const[Qe,oe]of t.current)oe===Xe&&t.current.delete(Qe)},n=Xe=>{const Qe=e.current.get(Xe);Qe&&(Qe.abort(),e.current.delete(Xe));const oe=t.current.get(Xe);oe&&(oe.abort(),t.current.delete(Xe))},a=Xe=>{const Qe=e.current.get(tt);Qe&&e.current.size===1&&(e.current.delete(tt),e.current.set(Xe,Qe))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:_,abortStream:C,clearStreamSession:P,setStreamSession:k,getStreamSession:T,setActiveSession:N,incrementSending:R,decrementSending:A,loadAndDisplay:E,thinkingTimeoutRef:I,sessionSwitchSeqRef:H,setSending:q,setActivities:D,setInput:ne,setChatContext:j,setPendingImages:X,setMentionDropdown:z,setChatReplyTo:B,setActiveSessionId:U,setStoredActiveSession:se,setOpenSessionTabs:G,setSessions:he,setLoadingChat:V,setWindowBounds:M,setThinkingAgents:re,makeConvKey:Y,makeDmChannel:ee,addRecentMsgId:K,resumeChatScrollFollow:Ce,loadSessions:Re}=s,{t:Te}=s,Oe=S.useCallback(async(Xe,Qe)=>{const oe=H.current,Ke=g.current===Qe&&(b(Qe)?.length??0)===0;Ke&&V(!0);try{const{count:nt,hasMore:Ot,oldestCursor:Wt}=await E(Xe,Qe,async()=>{const At=await te.sessions.getMessages(Xe,50);return{messages:Uk(At.messages.map(rh).filter(je=>je.sender!=="agent"||je.text||je.segments&&je.segments.length>0||je.isStreaming)),hasMore:At.hasMore,oldestCursor:At.messages[0]?new Date(At.messages[0].createdAt).toISOString():null}});return M(Xe,{hasMore:Ot,oldestCursor:Wt}),nt}finally{Ke&&g.current===Qe&&H.current===oe&&V(!1)}},[E,b,H]),we=()=>{const Xe=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Xe){const Qe=Sf(f.current.activeSessionId,tt);Qe.kind==="cancel"&&te.agents.cancelProcessing(Xe,Qe.target).catch(()=>{})}n(f.current.activeSessionId??tt),Xe&&f.current.activeSessionId&&f.current.activeSessionId!==tt&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ve=S.useCallback(async(Xe,Qe,oe)=>{if(!Xe||!Qe||Qe===tt||l.current.has(Qe))return;let Ke=null;try{const nt=e.current.get(Qe);if(nt&&!nt.signal.aborted&&T(oe)?.has(Qe)){g.current===oe&&q(!0);return}const Ot=()=>{Hk({liveSessions:T(oe),sessionId:Qe,placeholderId:tt})&&(P(oe,Qe),g.current===oe&&(q(!1),O(oe,fe=>ru(fe),Qe)))},Wt=`${Xe}:${Qe}`,At=o.current.get(Wt)??0;if(Date.now()-At<1500)return;o.current.set(Wt,Date.now());let vt;const je=await te.sessions.streamStatus(Xe,Qe);je.messageId&&(vt=je.messageId);const Pt=b(oe)??[],Ps=je.status==="streaming",pt=Yk(Pt,{expectedMessageId:je.messageId,allowCurrentTurnPartial:Ps}),_t=!!je.active&&(je.status==="done"||je.status==="error")&&!!pt?.isStreaming;if(kv({aborted:!1,sawTerminal:_t,serverStatus:Cv(je.status)})==="finalize"){Ot();return}o.current.set(Wt,Date.now());for(const fe of t.current.values())fe.abort();t.current.clear(),Ke=new AbortController,t.current.set(Qe,Ke),y(oe),q(!0),k(oe,Qe);let ht=pt?.id;if(!pt||pt.isError)ht=`reattach_${Date.now()}`,O(oe,fe=>[...fe,{id:ht,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],Qe);else{const fe=(pt.segments??[]).filter(be=>be.type==="tool").map(be=>be.status==="stopped"||be.status==="running"?{...be,status:"running"}:be);O(oe,be=>be.map(_e=>_e.id===pt.id?{..._e,text:"",isStreaming:!0,isStopped:!1,segments:fe,committedSegments:void 0}:_e),Qe)}const st=fe=>{g.current===oe&&(u.current=Date.now(),m(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ve=>ve.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ve,ye)=>({m:ve,j:ye})).reverse().find(ve=>ve.m.sender==="agent"&&ve.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];return _e[Fe]={...J,text:(J.text??"")+fe,segments:vO(J.segments??[],fe),isStreaming:!0},_e},Qe))},bt=fe=>{g.current===oe&&(u.current=Date.now(),m(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ve=>ve.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ve,ye)=>({m:ve,j:ye})).reverse().find(ve=>ve.m.sender==="agent"&&ve.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];return _e[Fe]={...J,segments:yO(J.segments??[],fe),isStreaming:!0},_e},Qe))},$t=fe=>{if(g.current===oe&&(u.current=Date.now(),fe.phase!=="heartbeat")){if((fe.phase==="start"||fe.phase==="end")&&x(oe,{...fe,phase:fe.phase,ts:Date.now()},Qe),fe.phase==="start"){const be=`${fe.tool}_${Date.now()}`,_e=new Date().toISOString(),Ne=Fe=>{const J=[...Fe];for(let ve=J.length-1;ve>=0;ve--){const ye=J[ve];if(ye.type==="tool"&&ye.tool===fe.tool&&(ye.status==="running"||ye.status==="stopped"))return J[ve]={...ye,status:"running",args:fe.arguments??ye.args},J}return J.push({type:"tool",key:be,tool:fe.tool,status:"running",args:fe.arguments,createdAt:_e}),J};O(oe,Fe=>{const J=[...Fe],ve=ht?J.findIndex(ze=>ze.id===ht):-1;if(ve<0)return Fe;const ye=Ne(J[ve].segments??[]),ge=J[ve].committedSegments,ke=ge&&Ne(ge);return J[ve]={...J[ve],segments:ye,committedSegments:ke,isStreaming:!0},J},Qe)}else if(fe.phase==="end"){const be=new Date().toISOString(),_e=Ne=>{const Fe=[...Ne];for(let J=Fe.length-1;J>=0;J--){const ve=Fe[J];if(ve.type==="tool"&&ve.tool===fe.tool&&(ve.status==="running"||ve.status==="stopped")){Fe[J]={...ve,status:fe.success===!1?"error":"done",args:fe.arguments??ve.args,result:fe.result,error:fe.error,durationMs:fe.durationMs,liveOutput:void 0,createdAt:be};break}}return Fe};O(oe,Ne=>{const Fe=[...Ne],J=ht?Fe.findIndex(ke=>ke.id===ht):-1;if(J<0)return Ne;const ve=_e(Fe[J].segments??[]),ye=Fe[J].committedSegments,ge=ye&&_e(ye);return Fe[J]={...Fe[J],segments:ve,committedSegments:ge,isStreaming:!0},Fe},Qe)}else if(fe.phase==="subagent_progress"&&fe.subagentEvent){const be=_e=>{const Ne=[..._e];for(let Fe=Ne.length-1;Fe>=0;Fe--){const J=Ne[Fe];if(J.type==="tool"&&(J.tool==="spawn_subagent"||J.tool==="spawn_subagents")&&(J.status==="running"||J.status==="stopped")){Ne[Fe]={...J,status:"running",subagentLogs:SO(J.subagentLogs,fe.subagentEvent)};break}}return Ne};m(oe,_e=>{const Ne=[..._e],Fe=ht?Ne.findIndex(ge=>ge.id===ht):-1;if(Fe<0)return _e;const J=be(Ne[Fe].segments??[]),ve=Ne[Fe].committedSegments,ye=ve&&be(ve);return Ne[Fe]={...Ne[Fe],segments:J,committedSegments:ye,isStreaming:!0},Ne},Qe)}}},Tt=fe=>{g.current===oe&&(u.current=Date.now(),O(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(J=>J.id===ht):-1;if(Ne<0)return be;const Fe=[..._e[Ne].committedSegments??[]];if(fe.type==="thinking_commit")Fe.push({type:"text",content:"",thinking:fe.content,createdAt:fe.createdAt});else if(fe.type==="text_commit")Fe.push({type:"text",content:fe.content,createdAt:fe.createdAt});else return be;return _e[Ne]={..._e[Ne],committedSegments:Fe,isStreaming:!0},_e},Qe))},xt=fe=>{if(g.current!==oe)return;u.current=Date.now();const be=(fe.segments??[]).map((_e,Ne)=>_e.type==="tool"?{type:"tool",key:`${_e.tool}_${Ne}`,tool:_e.tool??"tool",status:_e.status==="error"?"error":_e.status==="running"||_e.status==="stopped"?"running":"done",args:_e.arguments,result:_e.result,error:_e.error,durationMs:_e.durationMs,createdAt:_e.createdAt,..._e.subagentLogs?.length?{subagentLogs:_e.subagentLogs}:{}}:{type:"text",content:_e.content??"",thinking:_e.thinking,createdAt:_e.createdAt});O(oe,_e=>{const Ne=[..._e],Fe=ht?Ne.findIndex(J=>J.id===ht):-1;return Fe<0?_e:(Ne[Fe]={...Ne[Fe],text:fe.content||Ne[Fe].text,segments:be,committedSegments:be,isStreaming:!0,isStopped:!1},Ne)},Qe);for(const _e of be)_e.type==="tool"&&x(oe,{tool:_e.tool,phase:_e.status==="running"||_e.status==="stopped"?"start":"end",success:_e.status!=="error",arguments:_e.args,result:_e.result,error:_e.error,durationMs:_e.durationMs,ts:Date.now()},Qe)},le=8;let ae=null;const Me=fe=>{g.current===oe&&O(oe,be=>{const _e=be.map((Fe,J)=>({m:Fe,j:J})).reverse().find(Fe=>Fe.m.sender==="agent"&&Fe.m.isStreaming)?.j??-1;if(_e<0||be[_e].reconnecting===fe)return be;const Ne=[...be];return Ne[_e]={...Ne[_e],reconnecting:fe},Ne},Qe)};for(let fe=1;fe<=le;fe++){if(Ke.signal.aborted)return;try{ae=await te.sessions.reattachStream(Xe,Qe,{onChunk:st,onThinking:bt,onActivity:$t,onCommit:Tt,onSnapshot:xt},Ke.signal,0)}catch(_e){if(Ke.signal.aborted)throw _e;ae=null}if(!ae||!ae.attached){ae=null;break}if(ae.terminal)break;Me(!0);const be=await te.sessions.streamStatus(Xe,Qe).catch(()=>null);if(be?.messageId&&(vt=be.messageId),!be||!be.active||be.status==="not_found"||be.status==="idle"){Me(!1),ae=null;break}await new Promise(_e=>setTimeout(_e,Math.min(800*fe,4e3))),Me(!1)}if(!ae){_(oe),P(oe,Qe),g.current===oe&&(q(!1),vt&&ht&&O(oe,fe=>ka(fe,ht,vt),Qe),Oe(Qe,oe).catch(()=>{}).finally(()=>{O(oe,fe=>ru(fe,"done"),Qe)})),i(Ke);return}if(g.current===oe){let fe;O(oe,be=>{const _e=[...be],Ne=ht?_e.findIndex(ye=>ye.id===ht):-1,Fe=Ne>=0?Ne:_e.map((ye,ge)=>({m:ye,j:ge})).reverse().find(ye=>ye.m.sender==="agent"&&ye.m.isStreaming)?.j??-1;if(Fe<0)return be;const J=_e[Fe];if(!J.isStreaming)return be;fe=J.id;const ve=ae.segments?.length?wO(ae.segments,J.segments):void 0;return _e[Fe]={...J,text:ae.content||J.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ve?{segments:ve,committedSegments:ve}:{}},_e},Qe),fe&&O(oe,be=>ka(be,fe,ae.messageId),Qe),q(!1)}_(oe),P(oe,Qe),i(Ke)}catch(nt){const Ot=Ke?[...t.current.values()].includes(Ke):!1;if(i(Ke),_(oe),P(oe,Qe),g.current===oe&&(q(!1),Ot&&O(oe,Wt=>ru(Wt),Qe)),nt instanceof Error&&nt.name==="AbortError")return}},[x,y,_,T,b,k,O,m]),lt=S.useCallback(async(Xe,Qe)=>{const oe=f.current,Ke=!Xe&&oe.chatContext.length>0?oe.chatContext.map(_t=>_t.content).join(`
|
|
76
76
|
|
|
77
77
|
`)+`
|
|
78
78
|
|