@markus-global/cli 0.12.0-rc.3 → 0.12.0

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.
Files changed (65) hide show
  1. package/dist/web-ui/assets/{AsyncState-Bn4fEZi_.js → AsyncState-Czik5FUM.js} +1 -1
  2. package/dist/web-ui/assets/{CommentInput-K5GGyiKb.js → CommentInput-BsaOrj2g.js} +1 -1
  3. package/dist/web-ui/assets/{ContentRenderer-BfUE28DF.js → ContentRenderer-Cl9-dJ-4.js} +2 -2
  4. package/dist/web-ui/assets/{DeliverableShareModal-BA31hw63.js → DeliverableShareModal-wgdeaboz.js} +1 -1
  5. package/dist/web-ui/assets/{Deliverables-DTE21gMR.js → Deliverables-Czrn3ezy.js} +1 -1
  6. package/dist/web-ui/assets/{Notifications-DrhzF29n.js → Notifications-BoxombIH.js} +1 -1
  7. package/dist/web-ui/assets/{Search-B_FQwfHn.js → Search-D9FOOaVc.js} +1 -1
  8. package/dist/web-ui/assets/{SendToChat-DjBI_C0Z.js → SendToChat-D95-I-fu.js} +1 -1
  9. package/dist/web-ui/assets/{Settings-BG3HtYuY.js → Settings-DvknF2D-.js} +1 -1
  10. package/dist/web-ui/assets/{Store-CvRIK-5v.js → Store-CVTUuEyr.js} +1 -1
  11. package/dist/web-ui/assets/{Switch-DBd7W9Pv.js → Switch-CJm0Y6Ab.js} +1 -1
  12. package/dist/web-ui/assets/{Team-Cre9JXT2.js → Team-CnQniCUA.js} +4 -4
  13. package/dist/web-ui/assets/{Work-C77VUxw5.js → Work-Dmxua6PP.js} +1 -1
  14. package/dist/web-ui/assets/{arc-B8WSMmgB.js → arc-BLg_pCBM.js} +1 -1
  15. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DE0fnpkU.js → architectureDiagram-3BPJPVTR-Cmx-kPk8.js} +1 -1
  16. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BnEt7L8I.js → blockDiagram-GPEHLZMM-C7M18dlD.js} +1 -1
  17. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-0jt--EpH.js → c4Diagram-AAUBKEIU-Cfwl8fbI.js} +1 -1
  18. package/dist/web-ui/assets/channel-0w5HoIsN.js +1 -0
  19. package/dist/web-ui/assets/{chunk-2J33WTMH-CLyqQEQo.js → chunk-2J33WTMH-C5mU_TTU.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-4BX2VUAB-mylnMthq.js → chunk-4BX2VUAB-CQCbo-ag.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-55IACEB6-DtElV09S.js → chunk-55IACEB6-4c3wqJwT.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-727SXJPM-BpRwLol3.js → chunk-727SXJPM-DXdlGwqz.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-AQP2D5EJ-5yxNM2TB.js → chunk-AQP2D5EJ-K192souI.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-FMBD7UC4-no_NwFEB.js → chunk-FMBD7UC4-D5Q3CYrz.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-ND2GUHAM-JvDwwYzS.js → chunk-ND2GUHAM-qNuRMI8p.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-QZHKN3VN-C-NPps0e.js → chunk-QZHKN3VN-BkmKoVv4.js} +1 -1
  27. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C7BIpwAA.js +1 -0
  28. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C7BIpwAA.js +1 -0
  29. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-OUCdAUoH.js → cose-bilkent-S5V4N54A-Cc-LCylz.js} +1 -1
  30. package/dist/web-ui/assets/{dagre-BM42HDAG-BJNrdNyh.js → dagre-BM42HDAG-CcbGFoMh.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-2AECGRRQ-CXqfw0Vf.js → diagram-2AECGRRQ-BMK1aNmF.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-5GNKFQAL-Dhik8K7x.js → diagram-5GNKFQAL-DLZ1Dlob.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-KO2AKTUF-DzTqoIpG.js → diagram-KO2AKTUF-DgF4N3Vp.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-LMA3HP47-CzPaYK-1.js → diagram-LMA3HP47-Dj6Rsgtz.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-OG6HWLK6-D3i9cNLV.js → diagram-OG6HWLK6-B33vd8GS.js} +1 -1
  36. package/dist/web-ui/assets/{docx-preview-BE8zQneZ.js → docx-preview-Cbe9vyIJ.js} +1 -1
  37. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DZ6wi5nS.js → erDiagram-TEJ5UH35-C0ArR1aG.js} +1 -1
  38. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-CEbBUrOM.js → flowDiagram-I6XJVG4X-wdN-ujEZ.js} +1 -1
  39. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-lo_doOaC.js → ganttDiagram-6RSMTGT7-BUKw6wm1.js} +1 -1
  40. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-C3mdtDuF.js → gitGraphDiagram-PVQCEYII-DU3TBBvN.js} +1 -1
  41. package/dist/web-ui/assets/{index-DyYU0JDE.js → index-Ci5bUF3m.js} +5 -5
  42. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-6I0hh52X.js → infoDiagram-5YYISTIA-Dk634Bq4.js} +1 -1
  43. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BOk8zKdQ.js → ishikawaDiagram-YF4QCWOH-BE5upFcq.js} +1 -1
  44. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-C3KEoO7x.js → journeyDiagram-JHISSGLW-C_fU89IU.js} +1 -1
  45. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-DCT0_9gO.js → kanban-definition-UN3LZRKU-DCPTTiVV.js} +1 -1
  46. package/dist/web-ui/assets/{mermaid.core-BOX2l4yL.js → mermaid.core-CwgDshh9.js} +5 -5
  47. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-KkRXcsxC.js → mindmap-definition-RKZ34NQL-B1O4o7mE.js} +1 -1
  48. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Crj5MjvX.js → pieDiagram-4H26LBE5-HKc1yZ37.js} +1 -1
  49. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CKhlan97.js → quadrantDiagram-W4KKPZXB-DSJ8Nt1Y.js} +1 -1
  50. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-B7OrOTSq.js → requirementDiagram-4Y6WPE33-Bnk4zXkX.js} +1 -1
  51. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CzvhKY35.js → sankeyDiagram-5OEKKPKP-DW5T8bfU.js} +1 -1
  52. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CiNjJsfF.js → sequenceDiagram-3UESZ5HK-D80T-VQ2.js} +1 -1
  53. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DBsBa5mY.js → stateDiagram-AJRCARHV-DbMI2WnT.js} +1 -1
  54. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-BxYWXdlm.js +1 -0
  55. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-CL-8e5v_.js → timeline-definition-PNZ67QCA-m1796nxN.js} +1 -1
  56. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CWgqoJu8.js → vennDiagram-CIIHVFJN-uQ9kkGtM.js} +1 -1
  57. package/dist/web-ui/assets/{wardley-L42UT6IY-ZgIWnerm.js → wardley-L42UT6IY-Bwp548d-.js} +1 -1
  58. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CBWa7zOH.js → wardleyDiagram-YWT4CUSO-D1Dcm5Tb.js} +1 -1
  59. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-Du9MvrT6.js → xychartDiagram-2RQKCTM6-CRhoH3Re.js} +1 -1
  60. package/dist/web-ui/index.html +1 -1
  61. package/package.json +1 -1
  62. package/dist/web-ui/assets/channel-MmWww9CF.js +0 -1
  63. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-lROpDb6P.js +0 -1
  64. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-lROpDb6P.js +0 -1
  65. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DsfVE1eK.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DyYU0JDE.js","assets/index-D4zDaGe4.css"])))=>i.map(i=>d[i]);
2
- import{r as S,k as Wm,u as Pt,C as Iv,j as c,q as $o,af as Xm,ag as zm,w as _t,l as te,ah as Zk,a as qm,b as Zm,P as Yt,c as Xh,M as Vk,A as Ns,n as Mr,J as Wo,i as Vm,ai as Fk,aj as Uk,ak as Hk,al as Yk,am as Gk,an as bO,ao as ac,o as vO,O as Kk,D as Jk,h as Fm,d as eC,ap as Bv,aq as ih,ar as tC,as as yO,at as sC,V as rC,$ as Wv,L as iC,au as nC,av as oC,_ as Xv,aw as aC,ax as nh,ay as lC,az as ou,aA as cC,aB as hC,aC as SO,aD as wO,aE as _O,aF as Sa,aG as kO,aH as dC,aI as CO,aJ as Mn,aK as Dc,aL as Ic,aM as uC,aN as PO,aO as fC,aP as mC,aQ as pC,aR as gC,aS as TO,s as QO,m as $O,aT as OC,aU as xC,aV as au,aW as jO,aX as bC,aY as lu,aZ as cu,a_ as vC,G as hu,a$ as yC,b0 as RO,b1 as lc,b2 as EO,b3 as SC,b4 as wC,b5 as _C,b6 as AO,b7 as kC,b8 as CC,b9 as PC,ba as TC,bb as QC,bc as $C,bd as jC,be as RC,bf as MO,bg as EC,bh as AC,p as MC,bi as LC,bj as NC,bk as DC,bl as IC}from"./index-DyYU0JDE.js";import{P as zv,E as BC,L as qv,S as WC}from"./AsyncState-Bn4fEZi_.js";import{p as XC,r as LO}from"./CommentInput-K5GGyiKb.js";import{ContentRenderer as kf,resolveFormat as zC}from"./ContentRenderer-BfUE28DF.js";import{a as qC,c as ZC,D as VC}from"./DeliverableShareModal-BA31hw63.js";import{i as FC,S as NO}from"./Switch-DBd7W9Pv.js";function co(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ci5bUF3m.js","assets/index-D4zDaGe4.css"])))=>i.map(i=>d[i]);
2
+ import{r as S,k as Wm,u as Pt,C as Iv,j as c,q as $o,af as Xm,ag as zm,w as _t,l as te,ah as Zk,a as qm,b as Zm,P as Yt,c as Xh,M as Vk,A as Ns,n as Mr,J as Wo,i as Vm,ai as Fk,aj as Uk,ak as Hk,al as Yk,am as Gk,an as bO,ao as ac,o as vO,O as Kk,D as Jk,h as Fm,d as eC,ap as Bv,aq as ih,ar as tC,as as yO,at as sC,V as rC,$ as Wv,L as iC,au as nC,av as oC,_ as Xv,aw as aC,ax as nh,ay as lC,az as ou,aA as cC,aB as hC,aC as SO,aD as wO,aE as _O,aF as Sa,aG as kO,aH as dC,aI as CO,aJ as Mn,aK as Dc,aL as Ic,aM as uC,aN as PO,aO as fC,aP as mC,aQ as pC,aR as gC,aS as TO,s as QO,m as $O,aT as OC,aU as xC,aV as au,aW as jO,aX as bC,aY as lu,aZ as cu,a_ as vC,G as hu,a$ as yC,b0 as RO,b1 as lc,b2 as EO,b3 as SC,b4 as wC,b5 as _C,b6 as AO,b7 as kC,b8 as CC,b9 as PC,ba as TC,bb as QC,bc as $C,bd as jC,be as RC,bf as MO,bg as EC,bh as AC,p as MC,bi as LC,bj as NC,bk as DC,bl as IC}from"./index-Ci5bUF3m.js";import{P as zv,E as BC,L as qv,S as WC}from"./AsyncState-Czik5FUM.js";import{p as XC,r as LO}from"./CommentInput-BsaOrj2g.js";import{ContentRenderer as kf,resolveFormat as zC}from"./ContentRenderer-Cl9-dJ-4.js";import{a as qC,c as ZC,D as VC}from"./DeliverableShareModal-wgdeaboz.js";import{i as FC,S as NO}from"./Switch-CJm0Y6Ab.js";function co(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
3
3
  font-size: .6rem;
4
4
  font-weight: bold;
5
5
  color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function DO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const UC=(s,e)=>Math.abs(s-e)<1.01,HC=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},IO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},YC=s=>s,GC=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),r=[];for(let i=e;i<=t;i++)r.push(i);return r},KC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;const i=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(i(IO(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const h=l.borderBoxSize[0];if(h){i({width:h.inlineSize,height:h.blockSize});return}}i(IO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},BO={passive:!0},WO=typeof window>"u"?!0:"onscrollend"in window,JC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&WO?()=>{}:HC(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;i=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,BO);const h=s.options.useScrollendEvent&&WO;return h&&t.addEventListener("scrollend",l,BO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},e2=(s,e,t)=>{if(e?.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},t2=(s,{adjustments:e=0,behavior:t},r)=>{var i,n;const a=s+e;(n=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||n.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:t})};class s2{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,r,i;return((i=(r=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let t=null;const r=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),t=null},observe:i=>{var n;return(n=r())==null?void 0:n.observe(i,{box:"border-box"})},unobserve:i=>{var n;return(n=r())==null?void 0:n.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([r,i])=>{typeof i>"u"&&delete t[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:YC,rangeExtractor:GC,onChange:()=>{},measureElement:e2,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,t)},this.maybeNotify=co(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,r)=>{const i=new Map,n=new Map;for(let a=r-1;a>=0;a--){const o=t[a];if(i.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&i.set(o.lane,!0),i.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=co(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,r,i,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=co(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const p of this.laneAssignments.keys())p>=t&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let p=0;p<d;p++){const v=u[p];v&&(f[v.lane]=p)}for(let p=d;p<t;p++){const v=n(p),b=this.laneAssignments.get(p);let g,O;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const C=f[g],P=C!==void 0?u[C]:void 0;O=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?u[p-1]:this.getFurthestMeasurement(u,p);O=C?C.end+this.options.gap:r+i,g=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),k=O+y;u[p]={index:p,start:O,size:y,end:k,key:v,lane:g},f[g]=p}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=co(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?r2({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=co(()=>{let t=null,r=null;const i=this.calculateRange();return i&&(t=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,r]},(t,r,i,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const r=this.options.indexAttribute,i=t.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,i-n),o=Math.min(this.options.count-1,i+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const r=this.indexFromElement(t),i=this.options.getItemKey(r),n=this.elementsCache.get(i);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,r)=>{var i;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=r-a;o!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,r)),this.notify(!1))},this.getVirtualItems=co(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,r)=>{const i=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=r[o];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const r=this.getMeasurements();if(r.length!==0)return DO(r[Zv(0,r.length-1,i=>DO(r[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,r,i=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=t>=a+n?"end":"start"),r==="center"?t+=(i-n)/2:r==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,r="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const i=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(r==="auto")if(a.end>=n+i-this.options.scrollPaddingEnd)r="end";else if(a.start<=n+this.options.scrollPaddingStart)r="start";else return[n,r];if(r==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),r];const o=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,r,a.size),r]},this.scrollToOffset=(t,{align:r="start",behavior:i="auto"}={})=>{const n=this.getOffsetForAlignment(t,r),a=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:r="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,r);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:i,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:n,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=r[r.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&n.some(o=>o===null);){const o=r[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}i=Math.max(...n.filter(o=>o!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:r,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,n=1,a=i!==this.scrollState.lastTargetOffset;if(!a&&UC(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Zv=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function r2({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=Zv(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(d=>d>=t);){const d=s[a];h[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const XO=typeof document<"u"?S.useLayoutEffect:S.useEffect;function i2({useFlushSync:s=!0,...e}){const t=S.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Wm.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=S.useState(()=>new s2(r));return i.setOptions(r),XO(()=>i._didMount(),[]),XO(()=>i._willUpdate()),i}function n2(s){return i2({observeElementRect:KC,observeElementOffset:JC,scrollToFn:t2,...s})}function o2({approval:s,submitting:e,readOnly:t,onClose:r,onDecision:i}){const{t:n}=Pt(["team","common"]);Iv(!0);const[a,o]=S.useState(""),l=typeof s.details?.command=="string"?s.details.command:"",h=typeof s.details?.toolName=="string"?s.details.toolName:"",d=u=>{t||e||i(u,a.trim()||void 0)};return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:u=>{u.target===u.currentTarget&&r()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/15 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug break-words",children:s.title||n("team:toolApproval.defaultTitle",{defaultValue:"Tool execution needs approval"})}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[c.jsxs("p",{className:"text-xs text-fg-tertiary",children:[s.agentName,h?` · ${h}`:""]}),t&&c.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/15 text-green-600",children:[c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})}),n("team:toolApproval.resolved",{defaultValue:"Resolved"})]})]})]}),c.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[c.jsx("p",{className:"text-sm text-fg-secondary leading-relaxed",children:n("team:toolApproval.lead",{defaultValue:"The agent is paused until you approve or reject this action."})}),s.description&&c.jsx("div",{className:"text-xs text-fg-secondary leading-relaxed [&_p]:my-0 [&_p]:text-xs",children:c.jsx($o,{content:s.description.replace(/\s*Command:[\s\S]*$/,""),className:"text-xs [&_p]:text-xs [&_li]:text-xs"})}),l&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("div",{className:"text-[11px] font-medium text-fg-tertiary uppercase tracking-wide",children:n("team:toolApproval.commandLabel",{defaultValue:"Command"})}),c.jsx("pre",{className:"text-xs text-fg-primary bg-surface-overlay border border-border-default rounded-xl px-3 py-2.5 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed",children:l})]}),!t&&c.jsx("textarea",{rows:2,value:a,onChange:u=>o(u.target.value),placeholder:n("team:toolApproval.commentPlaceholder",{defaultValue:"Optional note (e.g. why you reject)…"}),className:"w-full px-3.5 py-2.5 text-sm bg-surface-overlay border border-border-default rounded-xl text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50 resize-y"})]}),c.jsx("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:t?c.jsx("button",{onClick:r,className:"px-5 py-2 text-sm font-medium text-fg-secondary border border-border-default rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:close",{defaultValue:"Close"})}):c.jsxs(c.Fragment,{children:[c.jsxs("button",{disabled:e,onClick:()=>d(!1),className:"px-5 py-2 text-sm font-medium bg-red-600/85 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]}),n("common:reject",{defaultValue:"Reject"})]}),c.jsxs("button",{disabled:e,onClick:()=>d(!0),className:"px-5 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-2",children:[e&&c.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n("common:approve",{defaultValue:"Approve"})]})]})})]})}),document.body)}const zO={urgent:"bg-red-500/15 text-red-500",high:"bg-amber-500/15 text-amber-600",normal:"bg-blue-500/15 text-blue-500",low:"bg-surface-overlay text-fg-tertiary"};function a2({notification:s,agentName:e,acknowledging:t,index:r=0,total:i=1,onClose:n,onAcknowledge:a}){const{t:o,i18n:l}=Pt(["team","common"]);Iv(!0);const h=Xm(s.createdAt,o),d=zm(s.createdAt,l.language),u=s.priority||"normal",f=s.metadata??{},p=e||(typeof f.agentName=="string"?f.agentName:void 0),v=i>1,b=r>=i-1,g=Math.max(0,i-r-1);return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:O=>{O.target===O.currentTarget&&n()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[p&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:p}),u!=="normal"&&c.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${zO[u]??zO.normal}`,children:u}),v&&c.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface-overlay text-fg-secondary tabular-nums",children:o("page.notifyReviewProgress",{ns:"team",defaultValue:"{{current}} / {{total}}",current:r+1,total:i})}),(h||d)&&c.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-fg-tertiary tabular-nums",title:d,children:[c.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("path",{d:"M12 7v5l3 2"})]}),h,h&&d&&c.jsx("span",{className:"text-fg-muted",children:"·"}),d]})]})]}),c.jsx("button",{onClick:n,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:o("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),v&&c.jsx("div",{className:"h-0.5 w-full bg-surface-overlay shrink-0",children:c.jsx("div",{className:"h-full bg-blue-500 transition-[width] duration-200",style:{width:`${(r+1)/i*100}%`}})}),c.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:c.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:c.jsx($o,{content:s.body||""})})}),c.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[c.jsx("button",{onClick:n,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:o("common:close")}),c.jsx("button",{onClick:()=>{a()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?o("common:loading"):b?o("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"}):o("page.notifyReviewNext",{ns:"team",defaultValue:"Next",count:g})})]})]})}),document.body)}const Vv=12,du=400,l2=4,c2=350;function Fv(s){return Math.max(0,s.scrollHeight-s.clientHeight)}function qO(s){return Fv(s)>1}function Bc(s){return Fv(s)-s.scrollTop}function h2(s){return Bc(s)<=Vv}function d2(s,e){return Math.abs(e)<=Math.abs(s)?"none":e<0?"up":e>0?"down":"none"}const u2=new Set(["ArrowUp","PageUp","Home"]),f2=new Set(["ArrowDown","PageDown","End"]);function m2(s){return u2.has(s)?"up":f2.has(s)?"down":"none"}function p2(s,e){return s==null?"none":e>s+1?"up":e<s-1?"down":"none"}function g2(s){return s.scrollable?s.takeover?s.gestureDirection==="up"||s.intentPending?"hold":s.distance<=Vv?"resume":"hold":s.gestureDirection==="up"&&s.gestureActive||!s.programmatic&&s.deltaScrollTop<-4?"handover":"follow":s.takeover?"resume":"follow"}function O2(s){return!s.takeover&&!s.gestureActive}function x2(s,e){return e&&s==="up"}function ho(s,e){return`${s||"_"}::${e??""}`}function b2(s,e){let t=null;for(const r of s)r.start>e+1||(!t||r.start>t.start)&&(t=r);return t??s[0]??null}function v2(s,e){if(h2(e))return{kind:"bottom"};const t=b2(s,e.scrollTop);return t?{kind:"row",id:t.id,delta:e.scrollTop-t.start}:{kind:"bottom"}}function y2(s,e){return s+e}const S2=12;function ZO(s,e=S2){return{kind:"row",id:s,delta:-e}}function VO(s){const e=s.getBoundingClientRect().top,t=s.scrollTop,r=[];for(const i of Array.from(s.querySelectorAll("[data-index]"))){const a=i.querySelector('[id^="msg-"]')?.id?.slice(4);a&&r.push({id:a,start:t+(i.getBoundingClientRect().top-e)})}return r.sort((i,n)=>i.start-n.start),r}function w2(s,e,t,r){const i=s.find(n=>n.id===t);return i?y2(i.start-e.scrollTop,r):null}class _2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(e)for(this.entries.delete(e),this.entries.set(e,t);this.entries.size>this.capacity;){const r=this.entries.keys().next();if(r.done)break;this.entries.delete(r.value)}}get(e){if(!e)return null;const t=this.entries.get(e);return t?(this.entries.delete(e),this.entries.set(e,t),t):null}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const FO=new _2,UO={jump:3,prepend:2,restore:1};function k2(s,e){return!s||s.key!==e.key?!0:UO[e.priority]>=UO[s.priority]}const C2=1e4,HO=300;function P2(s,e){return e-s>C2}function YO(s,e){return s&&e===!0}function T2(s){return s.rendered?s.stable?"apply":"refine":s.stale?s.priority==="restore"?"release-bottom":"release-hold":!s.absent||s.canLoadMore?"keep":s.priority==="restore"?"release-bottom":"release-hold"}function uu(s){return s!=="prepend"}const fu=Object.freeze({text:"",images:[],context:[],replyTo:null});function GO(s){return s.text===""&&s.images.length===0&&s.context.length===0&&s.replyTo===null}function Q2(s){return{text:s.text,images:s.images,context:s.context,replyTo:s.replyTo}}class $2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(!e)return;this.entries.delete(e);const r=Q2(t);if(!GO(r))for(this.entries.set(e,r);this.entries.size>this.capacity;){const i=this.entries.keys().next().value;if(i===void 0)break;this.entries.delete(i)}}get(e){const t=this.peek(e);return GO(t)?fu:(this.entries.delete(e),this.entries.set(e,t),t)}peek(e){return e?this.entries.get(e)??fu:fu}size(){return this.entries.size}clear(){this.entries.clear()}}const wa=new $2;function KO(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function JO(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function e0(s,e){return!!s&&!!e&&s.has(e)}function j2(s){return s.msgIsStreaming&&s.liveStreamForView}const R2=10*6e4;class E2{bySession=new Map;listeners=new Set;_revision=0;getRevision=()=>this._revision;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});applyServerState(e,t,r,i=Date.now()){const n=this.bySession.get(t);if(n&&n.source==="server"&&n.at>i)return;const a=!n||n.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"server",at:i}),a&&this.bump()}reconcileFromServer(e,t,r=Date.now()){for(const[i,n]of Object.entries(t))this.applyServerState(e,i,n,r)}applyLocalOptimistic(e,t,r){const i=this.bySession.get(t),n=Date.now();if(i&&i.source==="server"&&i.at>=n)return;const a=!i||i.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"local",at:n}),a&&this.bump()}isStreaming(e){return e?this.bySession.get(e)?.streaming??!1:!1}isAgentStreaming(e){if(!e)return!1;for(const t of this.bySession.values())if(t.agentId===e&&t.streaming)return!0;return!1}streamingAgentIds(){const e=new Set;for(const t of this.bySession.values())t.streaming&&e.add(t.agentId);return e}hasEntry(e){return this.bySession.has(e)}prune(e=Date.now(),t=R2){for(const[r,i]of this.bySession)!i.streaming&&e-i.at>t&&this.bySession.delete(r)}bump(){this._revision+=1;for(const e of this.listeners)try{e()}catch{}}}const cs=new E2;function oh(){return S.useSyncExternalStore(cs.subscribe,cs.getRevision,cs.getRevision)}function Uv(s){return S.useSyncExternalStore(cs.subscribe,cs.getRevision,cs.getRevision),cs.isAgentStreaming(s)}function A2(s){const e=s?.payload;return!e||typeof e.sessionId!="string"||typeof e.streaming!="boolean"?null:{agentId:typeof e.agentId=="string"?e.agentId:"",sessionId:e.sessionId,streaming:e.streaming}}let t0=!1;function M2(){t0||(t0=!0,_t.on("session:stream_state",s=>{const e=A2(s);if(!e)return;const t=Date.parse(s.timestamp??"")||Date.now();cs.applyServerState(e.agentId,e.sessionId,e.streaming,t)}))}async function L2(s,e){if(!(!s||e.length===0)){try{const t=await te.sessions.streamStatusBatch(s,e);cs.reconcileFromServer(s,t.streaming??{},t.at)}catch{}cs.prune()}}function N2(s,e){return!s||s.mode!=="direct"||e.chatMode!=="direct"||!s.sessionId&&!s.preferMain?!1:!!s.agentId&&s.agentId===e.agentId}function Va({children:s,onClose:e,title:t,width:r="w-[440px]"}){return c.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:c.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[c.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function vo({label:s,children:e}){return c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function D2({onClose:s,onCreate:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("");return c.jsx(Va,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.createTeam.teamName"),children:c.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),c.jsx(vo,{label:t("team:modals.createTeam.description"),children:c.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),c.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:c.jsx(Zk,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:c.jsx("span",{className:"text-brand-400 font-medium"}),1:c.jsx("span",{className:"text-brand-400"})}})}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function I2({onClose:s,onAdd:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("member"),[o,l]=S.useState(""),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(!1),O=p?.inviteToken?`${window.location.origin}/#invite?token=${p.inviteToken}`:null,m=async()=>{if(d(""),!r.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(r.trim(),n,o.trim());v({...y,userName:r.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),g(!0),setTimeout(()=>g(!1),2e3))};return p?c.jsxs(Va,{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(Va,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[c.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),c.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",c.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),c.jsx(vo,{label:t("team:modals.addHuman.name"),children:c.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),c.jsx(vo,{label:t("team:modals.addHuman.role"),children:c.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[c.jsx("option",{value:"owner",children:t("common:role.owner")}),c.jsx("option",{value:"admin",children:t("common:role.admin")}),c.jsx("option",{value:"member",children:t("common:role.member")}),c.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),c.jsx(vo,{label:t("team:modals.addHuman.emailRequired"),children:c.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),h&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:m,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function B2({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=Pt(["team","common"]);return c.jsx(Va,{onClose:t,title:i("team:modals.addExisting.title"),children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?c.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):c.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>c.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[c.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),c.jsxs("div",{className:"flex-1",children:[c.jsx("div",{className:"font-medium text-sm",children:n.name}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&c.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),c.jsx("div",{className:"flex justify-end pt-2",children:c.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function W2({onClose:s,onConnected:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState(""),[o,l]=S.useState(!1),[h,d]=S.useState(null),[u,f]=S.useState(null),p=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const g=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!g.ok){const m=await g.json().catch(()=>({}));throw new Error(m.error??`HTTP ${g.status}`)}const O=await g.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(g){a(String(g))}l(!1)},v=(b,g)=>{navigator.clipboard.writeText(b),f(g),setTimeout(()=>f(null),2e3)};return c.jsx(Va,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:h?(()=>{const b=h.gatewayUrl??`${window.location.origin}/api/gateway`,g=h.token?t("team:modals.openClaw.bearerTokenLine",{token:h.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:h.externalAgentId,tokenSection:g});return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-center py-6",children:[c.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),c.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),c.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:c.jsx("strong",{children:r})})]}),c.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),c.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),c.jsx("div",{className:"flex justify-end pt-5",children:c.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.openClaw.agentName"),children:c.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:p,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}function Hv(s){return`group:${s}`}function X2(s){const{chatMode:e,agentTeamId:t,channelTeamId:r,knownTeamIds:i}=s,n=e==="direct"?t:e==="channel"?r:null;return n&&(i instanceof Set?i.has(n):Array.from(i).includes(n))?`team/t/${n}`:"team"}function z2(s,e){return s&&typeof s.tokensUsedToday=="number"&&Number.isFinite(s.tokensUsedToday)?s.tokensUsedToday:typeof e=="number"&&Number.isFinite(e)?e:0}function q2(s){return s?s.filter(e=>e&&typeof e.size=="number"&&e.size>0).slice().sort((e,t)=>t.size-e.size||e.name.localeCompare(t.name)):[]}const Z2=new Set(["workspace","sessions","tool-outputs","daily-logs","role","subagent-logs","worktrees"]);function V2(s){return Z2.has(s)?`agent:profilePage.overview.storageBuckets.${s}`:null}const Cf={idle:{tone:"ok",dotClass:"bg-green-400",running:!0,chipClass:"bg-green-500/10 border border-green-500/20",textClass:"text-green-600",labelKey:"common:status.idle"},working:{tone:"busy",dotClass:"bg-blue-400 animate-pulse",running:!0,chipClass:"bg-blue-500/10 border border-blue-500/20",textClass:"text-blue-500",labelKey:"common:status.working"},error:{tone:"danger",dotClass:"bg-red-400 animate-pulse",running:!0,chipClass:"bg-red-500/10 border border-red-500/20",textClass:"text-red-500",labelKey:"common:status.error"},paused:{tone:"warn",dotClass:"bg-amber-400",running:!1,chipClass:"bg-amber-500/10 border border-amber-500/20",textClass:"text-amber-600",labelKey:"common:status.paused"},offline:{tone:"muted",dotClass:"bg-gray-400",running:!1,chipClass:"bg-gray-500/10 border border-border-default",textClass:"text-fg-tertiary",labelKey:"common:status.offline"}};function zh(s){const e=s?Cf[s]:void 0;return e||{...Cf.offline,labelKey:null}}const F2=Cf.working;function gl(s,e){const t=zh(s);return!e||!t.running||t.tone==="danger"||t.tone==="busy"?t:F2}const U2=5;function s0(s,e=U2){const t=Array.isArray(s)?s:[];return{shown:t.slice().sort((i,n)=>Date.parse(n.startedAt)-Date.parse(i.startedAt)).slice(0,Math.max(0,e)),total:t.length}}const H2=100;function Y2(s){const e=Array.isArray(s)?s:[];return{heartbeats:e.filter(t=>t.type==="heartbeat"),comms:e.filter(t=>t.type==="a2a")}}const Um=["files","mind","recent","tools","memory","usage"],G2=Um[0];function r0(s,e){return e?"mind":Um.find(r=>r===s)??G2}function K2(s){return s?"right-panel":"page"}function J2(s){const e=s?.deferredItemIds?.length??0,t=s?.droppedItemIds?.length??0,r=s?.inlineCompletedIds?.length??0,i=1,n=i+e+t+r;return{processed:i,deferred:e,dropped:t,inlineCompleted:r,total:n,isBatch:n>1}}let cc=new Map;function eP({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=Pt(["team","common"]),[a,o]=S.useState(""),[l,h]=S.useState(new Set),[d,u]=S.useState(""),[f,p]=S.useState(!1),v=S.useMemo(()=>{const m=[];for(const x of s)m.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&m.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return m},[s,e,t]),b=S.useMemo(()=>{if(!d)return v;const m=d.toLowerCase();return v.filter(x=>x.name.toLowerCase().includes(m)||x.subtitle.toLowerCase().includes(m))},[v,d]),g=m=>{h(x=>{const y=new Set(x);return y.has(m)?y.delete(m):y.add(m),y})},O=async()=>{if(!a.trim()||l.size===0)return;p(!0);const m=[...l],x={},y={};for(const k of m){const C=v.find(P=>P.id===k);C&&(x[k]=C.type,y[k]=C.name)}await i(a.trim(),m,x,y),p(!1)};return c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),c.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:c.jsx("input",{value:a,onChange:m=>o(m.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),c.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:c.jsx("input",{value:d,onChange:m=>u(m.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&c.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(m=>c.jsxs("button",{onClick:()=>g(m.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(m.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(m.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(m.id)&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx(Ns,{name:m.name,size:20,bgClass:m.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate text-[11px] font-medium block",children:m.name}),c.jsx("span",{className:"text-[9px] text-fg-tertiary",children:m.subtitle})]}),c.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${m.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:m.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},m.id))]}),c.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),c.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const tP=S.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:h,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:p,onSelectDm:v,onSelectTeam:b,selectedTeamId:g,onRefreshTeams:O,onRefreshAgents:m,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:k,onManageGroupMembers:C,unreadByAgent:P,unreadByChannel:_,width:T,onResizeStart:R,hidden:L,onCollapse:M,initialLoading:E,previewMode:B,focused:U,l2Available:F}){const{t:X}=Pt(["team","common"]),ae=qm(),j=Zm(Yt.TEAM),W=Xh(),D=e?.role==="owner"||e?.role==="admin",V=S.useMemo(()=>new Set(a.map(q=>q.markusAgentId).filter(Boolean)),[a]);oh();const se=cs.streamingAgentIds(),[fe,z]=S.useState([]),[re,Z]=S.useState(new Set),[A,J]=S.useState(!1),[Y,oe]=S.useState(!1),[K,pe]=S.useState(null),[je,we]=S.useState(!1),[Ye,Qe]=S.useState(!1),[Ee,ye]=S.useState(null),[G,qe]=S.useState(null),[Ue,He]=S.useState(null),[mt,xt]=S.useState(!1),[bt,vt]=S.useState(""),[Pe,Et]=S.useState(null),[Ft,Es]=S.useState(null),[rt,yt]=S.useState(null),[Bt,dt]=S.useState(!1),Ze=S.useRef(null),[Xt,ot]=S.useState(null),At=S.useRef(null),ds=S.useRef(null),[he,ce]=S.useState(null),$e=(q,me="success")=>{ce({message:q,type:me}),setTimeout(()=>ce(null),3e3)},[Xe,de]=S.useState(null),[De,ve]=S.useState(!1),tt=S.useRef(!1);S.useEffect(()=>{if(B)return;te.governance.getSystemStatus().then(be=>{tt.current=!0,de(be.globalPaused)}).catch(()=>{tt.current=!0,de(!1)});const q=_t.on("system:pause-all",()=>{tt.current&&de(!0)}),me=_t.on("system:resume-all",()=>{tt.current&&de(!1)});return()=>{q(),me()}},[]),S.useEffect(()=>{if(!B)return;const q=setTimeout(()=>{const me=ds.current,be=At.current;me&&be&&be.scrollTo({top:me.offsetTop-be.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(q)},[B]);const ze=S.useCallback(()=>{Xe!==null&&ee({title:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title"),message:X(Xe?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:X(Xe?"chat.resume":"chat.pause"),onConfirm:async()=>{ve(!0);try{Xe?(await te.governance.resumeAll(),de(!1)):(await te.governance.pauseAll(),de(!0))}catch{}ve(!1)}})},[Xe]),[Ve,ee]=S.useState(null),Te=(q,me,be,Ie,Ge)=>{ee({title:q,message:me,onConfirm:be,confirmLabel:Ie,checkboxes:Ge})},[Se,xe]=S.useState(null),[_e,Fe]=S.useState(null),at=S.useRef(null),St=S.useRef(null),[ct,ht]=S.useState(!1),[Qt,ci]=S.useState(null),[le,$t]=S.useState(""),ge=S.useCallback((q,me=176,be=220)=>{const Ie=window.innerWidth,Ge=window.innerHeight,Ke=8;let lt=q.clientX,Rt=q.clientY;return lt+me>Ie-Ke&&(lt=Math.max(Ke,Ie-me-Ke)),Rt+be>Ge-Ke&&(Rt=Math.max(Ke,Ge-be-Ke)),lt=Math.max(Ke,Math.min(lt,Ie-me-Ke)),Rt=Math.max(Ke,Math.min(Rt,Ge-be-Ke)),{x:lt,y:Rt}},[]),[Us,pt]=S.useState(cc),Bs=S.useMemo(()=>t.map(q=>q.id).sort().join(","),[t]);S.useEffect(()=>{if(!t.length||!j)return;let q=!1;(async()=>{const lt=[];await Promise.allSettled(t.map(async Rt=>{if(!cc.has(Rt.id))try{const{sessions:gt}=await te.sessions.listByAgent(Rt.id,1);if(!gt.length)return;const{messages:ls}=await te.sessions.getMessages(gt[0].id,1);if(ls.length){const xs=ls[0],ir=xs.metadata?.segments;let zt=xs.content;if(ir&&ir.length>0){const bs=[...ir].reverse().find(es=>es.type==="text");bs&&bs.type==="text"&&(zt=bs.content)}const _s=zt.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);_s&&lt.push([Rt.id,_s])}}catch{}})),!q&&lt.length&&pt(Rt=>{const gt=new Map(Rt);for(const[ls,xs]of lt)gt.set(ls,xs);return cc=gt,gt})})();const be=new Set(t.map(lt=>lt.id)),Ie=lt=>Fk(lt).replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ge=(lt,Rt)=>{if(!lt||!Rt||!be.has(lt))return;const gt=Ie(Rt);gt&&pt(ls=>{const xs=new Map(ls);return xs.set(lt,gt),cc=xs,xs})},Ke=_t.on("chat:proactive_message",lt=>{const Rt=lt.payload;Ge(Rt.agentId??"",Rt.message??"")});return()=>{q=!0,Ke()}},[Bs,j]);const wt=S.useCallback(()=>{B||te.teams.list().then(q=>z(q.ungrouped)).catch(()=>{})},[B]);S.useEffect(()=>{wt()},[wt]),S.useEffect(()=>{if(!j)return;const q=_t.on("team:update",wt),me=_t.on("agent:removed",wt);return()=>{q(),me()}},[wt,j]),S.useEffect(()=>{if(!G&&!Ue&&!Pe&&!Bt&&!rt)return;const q=()=>{qe(null),He(null),Et(null),yt(null),dt(!1)},me=setTimeout(()=>document.addEventListener("click",q),0);return()=>{clearTimeout(me),document.removeEventListener("click",q)}},[G,Ue,Pe,Bt,rt]);const ln=(q,me)=>{Te(`${X("common:delete")} "${me}"?`,X("modals.deleteTeam.message"),async be=>{const Ie=be?.deleteMembers??!0,Ge=be?.purgeFiles??!1;await te.teams.delete(q,Ie,{purgeFiles:Ge}),O(),wt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("contextMenu.deleteTeam"),[{id:"deleteMembers",label:X("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:X("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Fo=async(q,me)=>{try{const Ie=await(me==="start"?te.teams.startAll:te.teams.stopAll)(q),Ge=Ie.success?.length??0,Ke=Ie.failed?.length??0;Ke>0?$e(X("batchAction.failed",{action:X(`batchAction.operation.${me}`),ok:Ge,fail:Ke}),"error"):Ge>0&&$e(X("batchAction.succeeded",{count:Ge,action:X(`batchAction.past.${me}`)}),"success"),m()}catch(be){$e(X("batchAction.failedToRun",{action:X(`batchAction.operation.${me}`),error:be instanceof Error?be.message:String(be)}),"error")}},cn=async(q,me,be)=>{await te.teams.update(q,{managerId:me,managerType:be}),O()},Pl=async q=>{if(!le.trim()){ci(null);return}await te.teams.update(q,{name:le.trim()}),ci(null),O()},Tl=async(q,me)=>{me==="offline"?await te.agents.start(q):await te.agents.stop(q),m()},gs=(q,me)=>{Te(X("modals.removeFromTeam.title"),X("modals.removeFromTeam.message"),async()=>{await te.teams.removeMember(q,me),O(),wt()},X("common:remove"))},rs=(q,me,be,Ie)=>{Te(`${X("common:remove")} "${me}"?`,X(be==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ge=>{if(be==="agent"&&Ie){const Ke=o.find(lt=>lt.type==="team"&&lt.teamId===Ie);Ke?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+Ke.channelKey)}if(be==="agent"){const Ke=Ge?.purgeFiles??!1;await te.agents.remove(q,{purgeFiles:Ke})}else await te.users.remove(q);m(),O(),x?.(),wt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("common:remove"),be==="agent"?[{id:"purgeFiles",label:X("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},ws=q=>{if(q.isOrgSecretary||q.protected)return!0;if(q.teamId)return!1;const me=(q.role??"").toLowerCase().trim(),be=(q.name??"").trim();return be==="Secretary"||be==="秘书"||me==="secretary"||me.startsWith("secretary")},xr=(q,me,be)=>{const Ie=t.find(Ge=>Ge.id===me);Ie&&ws(Ie)||(St.current={x:q.clientX,y:q.clientY},at.current=setTimeout(()=>{xe({agentId:me,fromTeamId:be}),ht(!0)},200))},Uo=q=>{if(!St.current||!at.current)return;const me=Math.abs(q.clientX-St.current.x),be=Math.abs(q.clientY-St.current.y);(me>5||be>5)&&(ct||(clearTimeout(at.current),at.current=null))},Ql=async()=>{if(at.current&&(clearTimeout(at.current),at.current=null),St.current=null,ct&&Se&&_e){const q=_e==="_ungrouped"?void 0:_e;try{if(Se.fromTeamId&&Se.fromTeamId!==q&&await te.teams.removeMember(Se.fromTeamId,Se.agentId),q&&q!==Se.fromTeamId){const me=t.find(be=>be.id===Se.agentId);await te.teams.addMember(q,Se.agentId,"agent")}O(),m(),wt()}catch(me){$e(X("batchAction.moveFailed",{error:me instanceof Error?me.message:String(me)}),"error")}}xe(null),Fe(null),ht(!1)},Xr=S.useMemo(()=>new Map(r.map(q=>[q.id,q])),[r]),Os=S.useMemo(()=>{const q=new Map,me=[];for(const be of t)if(be.teamId&&Xr.has(be.teamId)){const Ie=q.get(be.teamId)??[];Ie.push(be),q.set(be.teamId,Ie)}else me.push(be);return{byTeam:q,ungrouped:me}},[t,Xr]),Vn=(q,me)=>{const be=l==="direct"&&h===q.id,Ie=V.has(q.id),Ge=q.status==="offline",Ke=gl(q.status,!Ge&&se.has(q.id)),lt=Ke.tone==="busy",Rt=Ke.dotClass,ls=(void 0)?.managerId===q.id,xs=q.role?.toLowerCase().replace(/[-_]/g," ").trim(),ir=q.name.toLowerCase().trim(),zt=xs&&xs!==ir,_s=Us.get(q.id)||q.currentActivity?.label?.slice(0,60)||"",bs=lt?X("common:status.working"):q.status==="error"?X("common:status.error"):X(Ge?"common:status.offline":"common:status.online");return c.jsx("div",{className:`relative mb-0.5 ${ct&&Se?.agentId===q.id?"opacity-40":""}`,onPointerDown:es=>xr(es,q.id,me),onPointerMove:Uo,onPointerUp:Ql,children:c.jsxs("button",{"data-l1-nav-id":`agent:${q.id}`,onClick:()=>{ct||f(q.id)},onContextMenu:es=>{if(!D)return;es.preventDefault();const nr=ge(es);xt(!1),vt(""),He({agentId:q.id,teamId:me,...nr})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ae?"":"touch-none"} ${Ge?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Qi(be)}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:Ge?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),zt&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",q.role,")"]}),ls&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Ie&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ge&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:X("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:_s||" "})]}),c.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(P?.get(q.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:P.get(q.id)}),q.mailboxDepth!=null&&q.mailboxDepth>0&&c.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:q.mailboxDepth}),c.jsx("span",{title:bs,onClick:es=>{es.stopPropagation(),k(q.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Rt}`}),ae&&D&&c.jsx("span",{role:"button",tabIndex:0,onClick:es=>{if(es.stopPropagation(),Ue?.agentId===q.id)He(null);else{const nr=ge(es);xt(!1),vt(""),He({agentId:q.id,teamId:me,...nr})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},q.id)},$l=(q,me,be,Ie)=>{const Ge=ct&&_e===q&&Se?.fromTeamId!==q,Ke=Xt===q,lt=g===q,Rt=P?(Os.byTeam.get(q)??[]).reduce((qt,zr)=>qt+(P.get(zr.id)??0),0):0,ls=o.find(qt=>qt.type==="team"&&qt.teamId===q)?.channelKey??Hv(q),xs=_?_[ls]??0:0,ir=Rt+xs,zt=Os.byTeam.get(q)??[],_s=zt.filter(qt=>qt.status==="offline").length,bs=zt.length,es=bs>0&&_s===bs,nr=_s>0&&!es,dn=es?"bg-gray-500":nr?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":q,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ge?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Ke?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{ct&&Fe(q)},onPointerLeave:()=>{ct&&_e===q&&Fe(null)},children:[c.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[c.jsxs("button",{"data-l1-nav-id":`team:${q}`,onClick:()=>{b&&q!=="_ungrouped"&&b(q)},onContextMenu:qt=>{if(!D||!me)return;qt.preventDefault();const zr=ge(qt);qe({teamId:q,...zr})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${es?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Qi(lt)}`,children:[c.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${es?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[me?.avatarUrl?c.jsx("img",{src:me.avatarUrl,alt:Ie,className:"w-full h-full rounded-full object-cover",onError:qt=>{qt.target.style.display="none",qt.target.nextElementSibling?.classList.remove("hidden")}}):null,c.jsxs("svg",{className:`w-3 h-3 ${me?.avatarUrl?"hidden":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),bs>0&&c.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${dn}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[Qt===q?c.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:le,onChange:qt=>$t(qt.target.value),onBlur:()=>Pl(q),onKeyDown:qt=>{qt.key==="Enter"&&Pl(q),qt.key==="Escape"&&ci(null)},onClick:qt=>qt.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Ie}),c.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[X("chat.members_other",{count:be}),es&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:X("common:status.offline")}),nr&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[_s,"/",bs]})]})]}),ir>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:ir}),c.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),D&&me&&c.jsx("button",{onClick:qt=>{if(qt.stopPropagation(),G?.teamId===q)qe(null);else{const zr=ge(qt);qe({teamId:q,...zr})}},className:"w-7 h-7 flex items-center justify-center text-fg-muted hover:text-fg-primary rounded-md hover:bg-white/[0.08] transition-colors shrink-0",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ge&&ct&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:X("chat.dropHere")})]},q)},is=S.useMemo(()=>{const q=new Map,me=[],be=[],Ie=[];for(const Ge of o)if(Ge.channelKey.startsWith("dm:a2a:"))Ie.push(Ge);else if(Ge.type==="custom")be.push(Ge);else if(Ge.teamId){const Ke=q.get(Ge.teamId)??[];Ke.push(Ge),q.set(Ge.teamId,Ke)}else{const Ke=r.find(lt=>Ge.name.toLowerCase().includes(lt.name.toLowerCase())||lt.name.toLowerCase().includes(Ge.name.toLowerCase()));if(Ke){const lt=q.get(Ke.id)??[];lt.push(Ge),q.set(Ke.id,lt)}else me.push(Ge)}return{byTeam:q,unmatched:me,custom:be,dmChannels:Ie}},[o,r]),Tr=S.useMemo(()=>{const q=new Map;let me=0;for(const Ge of Os.ungrouped)q.set(Ge.id,me++);for(const Ge of r)for(const Ke of Os.byTeam.get(Ge.id)??[])q.set(Ke.id,me++);const be=Number.MAX_SAFE_INTEGER,Ie=Ge=>{const Ke=Ge.split(":");return Ke.length<4?[]:[Ke[2],Ke[3]].map(lt=>q.get(lt)??be).sort((lt,Rt)=>lt-Rt)};return[...is.dmChannels].sort((Ge,Ke)=>{const lt=Ie(Ge.channelKey),Rt=Ie(Ke.channelKey),gt=lt[0]??be,ls=lt[1]??be,xs=Rt[0]??be,ir=Rt[1]??be;return gt!==xs?gt-xs:ls!==ir?ls-ir:Ge.channelKey.localeCompare(Ke.channelKey)})},[is.dmChannels,Os,r]),[hn,jt]=S.useState(!1),br=l==="channel"&&is.dmChannels.some(q=>q.channelKey===d);S.useEffect(()=>{br&&jt(!0)},[br]);const jl=S.useMemo(()=>{const q=[];e&&q.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const be of i)be.id!==e?.id&&q.push({kind:"dm",id:`dm:${be.id}`,userId:be.id});for(const be of is.custom)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});for(const be of is.unmatched)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});const me=Os.ungrouped.length>0?Os.ungrouped:r.length===0?t:[];for(const be of me)q.push({kind:"agent",id:`agent:${be.id}`,agentId:be.id});for(const be of r)q.push({kind:"team",id:`team:${be.id}`,teamId:be.id});if(hn)for(const be of Tr)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});return q},[e,i,is,Os,r,t,hn]),Rl=S.useRef(jl);Rl.current=jl;const El=S.useCallback(q=>{q.kind==="dm"?v(q.userId):q.kind==="channel"?p(q.channelKey):q.kind==="agent"?f(q.agentId):q.kind==="team"&&b?.(q.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${q.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,p,f,b]);S.useEffect(()=>{if(B||ae||!j||L)return;const q=me=>{const be=W?.keyboardPane??"content";if(be==="l0"||be==="l2"||me.metaKey||me.ctrlKey||me.altKey||Vm(me.target))return;const Ie=me.key.length===1?me.key.toLowerCase():me.key;if(Ie==="h"||Ie==="ArrowLeft"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),W?.setL0FocusPageId(Yt.TEAM),W?.setLeftCollapsed(!1),W?.setKeyboardPane("l0");return}if(Ie==="l"||Ie==="ArrowRight"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),F&&W?.setKeyboardPane("l2");return}if(be!=="l1"&&!(U&&(Ie==="j"||Ie==="k"||Ie==="ArrowDown"||Ie==="ArrowUp")))return;const Ge=Ie==="j"||Ie==="ArrowDown"?1:Ie==="k"||Ie==="ArrowUp"?-1:0;if(!Ge)return;me.preventDefault(),me.stopPropagation(),W?.setKeyboardPane("l1");const Ke=Rl.current;if(Ke.length===0)return;let lt=-1;if(l==="dm"){const gt=u||e?.id;gt&&(lt=Ke.findIndex(ls=>ls.kind==="dm"&&ls.userId===gt))}else l==="direct"?lt=Ke.findIndex(gt=>gt.kind==="agent"&&gt.agentId===h):l==="channel"&&(lt=Ke.findIndex(gt=>gt.kind==="channel"&&gt.channelKey===d),lt<0&&g&&(lt=Ke.findIndex(gt=>gt.kind==="team"&&gt.teamId===g)));lt<0&&(lt=Ge>0?-1:0);const Rt=Math.max(0,Math.min(Ke.length-1,lt+Ge));El(Ke[Rt])};return document.addEventListener("keydown",q,!0),()=>document.removeEventListener("keydown",q,!0)},[B,ae,j,L,W,U,F,l,u,e?.id,h,d,g,El]);const Qi=q=>q?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${T!=null?"shrink-0":"flex-1 min-w-0"} ${U?"ring-1 ring-inset ring-brand-500/30":""}`,style:L?{display:"none"}:T!=null?{width:T}:void 0,children:[c.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[ae&&c.jsx(Vk,{}),!ae&&M&&c.jsx("button",{onClick:M,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsx("h2",{className:"text-lg font-semibold",children:X("chat.title")}),D&&c.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ze,children:[c.jsxs("button",{onClick:()=>dt(!Bt),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[c.jsx("span",{className:"text-brand-500",children:"+"})," ",X("chat.manage"),c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Bt?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),Bt&&c.jsxs("div",{ref:q=>{if(!q)return;const me=q.getBoundingClientRect(),be=window.innerWidth,Ie=8;me.right>be-Ie&&(q.style.left="auto",q.style.right="0"),me.left<Ie&&(q.style.left="0",q.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[c.jsxs("button",{onClick:()=>{dt(!1),ye("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),c.jsx("circle",{cx:"12",cy:"5",r:"2"}),c.jsx("path",{d:"M12 7v4"}),c.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),X("chat.addAgent")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addAgentDesc")})]}),c.jsxs("button",{onClick:()=>{dt(!1),ye("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),c.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),X("chat.newTeam")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newTeamDesc")})]}),c.jsxs("button",{onClick:()=>{dt(!1),oe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M20 8v6"}),c.jsx("path",{d:"M23 11h-6"})]}),X("chat.addHuman")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addHumanDesc")})]}),c.jsxs("button",{onClick:()=>{dt(!1),Qe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),c.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),X("chat.newGroupChat")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newGroupChatDesc")})]}),Xe!==null&&c.jsxs("button",{onClick:()=>{dt(!1),ze()},disabled:De,className:`w-full text-left px-4 py-2.5 text-xs hover:bg-surface-elevated border-t border-border-default transition-colors disabled:opacity-50 ${Xe?"text-green-600":"text-red-500"}`,children:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Xe?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",X("chat.resume")]}):c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",X("contextMenu.stopAll")]})}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:At,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.people")}),e&&c.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Qi(l==="dm"&&(u===e.id||!u))}`,children:[c.jsx(Ns,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:X("chat.myNotes")})]}),c.jsx("span",{className:"text-fg-secondary shrink-0",children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(q=>q.id!==e?.id).map(q=>{const me=e?.id?`dm:${[e.id,q.id].sort().join(":")}`:"",be=me&&_?_[me]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${q.id}`,onClick:()=>v(q.id),onContextMenu:Ie=>{if(!D||q.id===e?.id)return;Ie.preventDefault();const Ge=ge(Ie);Et({userId:q.id,...Ge})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${l==="dm"&&u===q.id?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:q.email||q.role})]}),be>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:be}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},q.id)})]}),is.custom.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:X("chat.groups")}),is.custom.map(q=>{const me=l==="channel"&&d===q.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),onContextMenu:be=>{be.preventDefault();const Ie=ge(be);yt({gcId:q.id,...Ie})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Qi(me)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.members_other",{count:q.memberCount??0})})]})]},q.id)})]}),E?c.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((q,me)=>c.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[c.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),c.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),c.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},me))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:X("chat.noAgentsYet")}):null,is.unmatched.map(q=>{const me=_?.[q.channelKey]??0;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Qi(l==="channel"&&d===q.channelKey)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.groupChat")})]}),me>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:me}):q.memberCount!==void 0&&q.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:q.memberCount}):null]},q.id)}),Os.ungrouped.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.agents")}),Os.ungrouped.map(q=>Vn(q))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:ds,children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.teams")}),r.map(q=>{const me=Os.byTeam.get(q.id)??[],be=q.members?.length||me.length;return $l(q.id,q,be,q.name)})]}),r.length===0&&Os.ungrouped.length===0&&t.length>0&&t.map(q=>Vn(q)),Tr.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>jt(q=>!q),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${hn?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),X("chat.agentDMs"),c.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Tr.length})]}),hn&&Tr.map(q=>{const me=l==="channel"&&d===q.channelKey,be=_?.[q.channelKey]??0,Ie=q.name.replace(/^DM:\s*/,"");return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Qi(me)}`,children:[c.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:Ie}),be>0&&c.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:be})]},q.id)})]})]})]}),R&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:R,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),G&&(()=>{const q=Os.byTeam.get(G.teamId)??[],me=q.some(Ie=>Ie.status==="offline"),be=q.some(Ie=>Ie.status!=="offline");return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:G.x,top:G.y},onClick:Ie=>Ie.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const Ie=Xr.get(G.teamId);Ie&&(ci(G.teamId),$t(Ie.name)),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),X("contextMenu.renameTeam")]}),me&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"start"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.startAll")]}),be&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"stop"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stopAll")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{qe(null),Mr.navigate(Yt.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),X("chat.addAgent")]}),fe.length>0&&c.jsxs("button",{onClick:()=>{qe(null),pe(G.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),c.jsx("polyline",{points:"17 11 19 13 23 9"})]}),X("contextMenu.addExisting")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{const Ie=Xr.get(G.teamId);Ie&&ln(G.teamId,Ie.name),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.deleteTeam")]})]})})(),Ue&&(()=>{const q=t.find(Ke=>Ke.id===Ue.agentId);if(!q||!D)return null;const be=(Ue.teamId?Xr.get(Ue.teamId):void 0)?.managerId===q.id,Ie=q.id===e?.id,Ge=ws(q);return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:Ue.x,top:Ue.y,maxHeight:Math.max(160,window.innerHeight-Ue.y-8)},onClick:Ke=>Ke.stopPropagation(),children:[Ge&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:X("contextMenu.orgSecretaryProtected")}),c.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),c.jsxs("button",{onClick:()=>{He(null),k(q.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),X("contextMenu.viewProfile")]}),q.status==="offline"?c.jsxs("button",{onClick:()=>{Tl(q.id,"offline"),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{Tl(q.id,q.status??"idle"),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stop")]}),!Ge&&Ue.teamId&&!be&&c.jsxs("button",{onClick:()=>{cn(Ue.teamId,q.id,"agent"),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),X("contextMenu.setAsManager")]}),!Ge&&Ue.teamId&&c.jsxs("button",{onClick:()=>{gs(Ue.teamId,q.id),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),X("contextMenu.removeFromTeam")]}),!Ge&&(()=>{const Ke=r.filter(gt=>gt.id!==Ue.teamId);if(Ke.length===0)return null;const lt=bt.trim().toLowerCase(),Rt=lt?Ke.filter(gt=>gt.name.toLowerCase().includes(lt)):Ke;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>xt(gt=>!gt),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:X("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${mt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),mt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:gt=>gt.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:bt,onChange:gt=>vt(gt.target.value),onKeyDown:gt=>gt.stopPropagation(),placeholder:X("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Rt.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:X("contextMenu.moveToEmpty")}):Rt.map(gt=>c.jsx("button",{type:"button",onClick:async()=>{Ue.teamId&&await te.teams.removeMember(Ue.teamId,q.id),await te.teams.addMember(gt.id,q.id,"agent"),O(),m(),wt(),He(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:gt.name,children:gt.name},gt.id))})]})]})})(),!Ge&&!Ie&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"agent",Ue.teamId),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})]})]})})(),Pe&&(()=>{const q=i.find(me=>me.id===Pe.userId);return!q||!D?null:c.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Pe.x,top:Pe.y},onClick:me=>me.stopPropagation(),children:c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"human"),Et(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})})})(),A&&c.jsx(D2,{onClose:()=>J(!1),onCreate:async(q,me)=>{try{const{team:be}=await te.teams.create(q,me);J(!1),O(),ot(be.id),setTimeout(()=>{document.querySelector(`[data-team-id="${be.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>ot(null),3e3)}catch(be){$e(X("chat.failedToCreateTeam",{message:be instanceof Error?be.message:String(be)}),"error")}}}),Y&&c.jsx(I2,{onClose:()=>{oe(!1),x?.()},onAdd:async(q,me,be)=>{const{inviteToken:Ie}=await te.users.create(q,me,void 0,be);return x?.(),{inviteToken:Ie}}}),K!==null&&c.jsx(B2,{teamId:K,ungrouped:fe,onClose:()=>pe(null),onAdd:async(q,me)=>{await te.teams.addMember(K,q,me),pe(null),O(),wt()}}),je&&c.jsx(W2,{onClose:()=>we(!1),onConnected:()=>{we(!1),m(),O()}}),rt&&(()=>{const q=o.find(me=>me.id===rt.gcId);return q?c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:rt.x,top:rt.y},onClick:me=>me.stopPropagation(),children:[q.type==="custom"&&c.jsxs("button",{onClick:()=>{yt(null),C?C(q.channelKey):p(q.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),X("contextMenu.manageMembers")]}),c.jsxs("button",{onClick:async()=>{yt(null),Te(X("modals.deleteGroupChat.title"),X("modals.deleteGroupChat.message",{name:q.name}),async()=>{await te.groupChats.delete(q.id),y()},X("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ye&&c.jsx(eP,{agents:t,humans:i,authUser:e,onClose:()=>Qe(!1),onCreate:async(q,me,be,Ie)=>{await te.groupChats.create({name:q,memberIds:me,memberTypes:be,memberNames:Ie,creatorId:e?.id,creatorName:e?.name}),Qe(!1),y()}}),Ee&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>ye(null),children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:q=>q.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:X(Ee==="agent"?"chat.addAgent":"chat.newTeam")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:X("chat.methodChoiceSubtitle")})]}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsxs("button",{onClick:()=>{const q=Ee;ye(null);const me=t.find(be=>be.role==="secretary")??t.find(be=>be.name?.toLowerCase().includes("secretary"));me?(f(me.id),Mr.navigate(Yt.TEAM,{agentId:me.id,prefillMessage:X(q==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):q==="agent"?Mr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),c.jsx("path",{d:"M20 3v4"}),c.jsx("path",{d:"M22 5h-4"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:X("chat.methodSecretary")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X("chat.methodSecretaryDesc")})]}),c.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:X("chat.recommended")})]}),c.jsxs("button",{onClick:()=>{const q=Ee;ye(null),q==="agent"?Mr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:X("chat.methodManual")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X(Ee==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),c.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:c.jsx("button",{onClick:()=>ye(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:X("common:cancel")})})]})}),Ve&&c.jsx(Wo,{title:Ve.title,message:Ve.message,confirmLabel:Ve.confirmLabel,checkboxes:Ve.checkboxes,onConfirm:q=>{Ve.onConfirm(q),ee(null)},onCancel:()=>ee(null)}),he&&c.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${he.type==="error"?"bg-red-500/10 text-red-500 border border-red-500/30":"bg-surface-elevated/95 text-fg-primary border border-border-default/50"}`,children:he.message})]})});function i0({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:h,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:p,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:g,unreadByAgent:O,width:m,onResizeStart:x,focused:y}){const{t:k}=Pt(["team","common"]),C=Xh(),P=Zm(Yt.TEAM),_=r?.role==="owner"||r?.role==="admin";oh();const T=S.useMemo(()=>e.filter(Y=>Y.teamId===s.id),[e,s.id]),R=S.useMemo(()=>{const Y=new Set((s.members??[]).filter(oe=>oe.type==="human").map(oe=>oe.id));return t.filter(oe=>Y.has(oe.id))},[s.members,t]),L=i&&n==="channel"&&o===i.channelKey,M=S.useMemo(()=>{const Y=[];i&&Y.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const oe of T)Y.push({kind:"agent",id:`agent:${oe.id}`,agentId:oe.id});for(const oe of R)Y.push({kind:"dm",id:`dm:${oe.id}`,userId:oe.id});return Y},[i,T,R]),E=S.useRef(M);E.current=M;const B=S.useCallback(Y=>{Y.kind==="channel"?u(Y.channelKey):Y.kind==="agent"?d(Y.agentId):f(Y.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${Y.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);S.useEffect(()=>{if(!P)return;const Y=oe=>{if((C?.keyboardPane??"content")!=="l2"||oe.metaKey||oe.ctrlKey||oe.altKey||Vm(oe.target))return;const pe=oe.key.length===1?oe.key.toLowerCase():oe.key;if(pe==="h"||pe==="ArrowLeft"){oe.preventDefault(),oe.stopPropagation(),C?.setKeyboardPane("l1");return}if(pe==="l"||pe==="ArrowRight"){oe.preventDefault(),oe.stopPropagation();return}const je=pe==="j"||pe==="ArrowDown"?1:pe==="k"||pe==="ArrowUp"?-1:0;if(!je)return;oe.preventDefault(),oe.stopPropagation();const we=E.current;if(we.length===0)return;let Ye=-1;n==="channel"?Ye=we.findIndex(Ee=>Ee.kind==="channel"&&Ee.channelKey===o):n==="direct"?Ye=we.findIndex(Ee=>Ee.kind==="agent"&&Ee.agentId===a):n==="dm"&&l&&(Ye=we.findIndex(Ee=>Ee.kind==="dm"&&Ee.userId===l)),Ye<0&&(Ye=je>0?-1:0);const Qe=Math.max(0,Math.min(we.length-1,Ye+je));B(we[Qe])};return document.addEventListener("keydown",Y,!0),()=>document.removeEventListener("keydown",Y,!0)},[P,C,n,o,a,l,B]);const U=Y=>Y?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[F,X]=S.useState(null),[ae,j]=S.useState(!1),[W,D]=S.useState(""),[V,se]=S.useState(null),fe=(Y,oe,K,pe,je)=>{se({title:Y,message:oe,onConfirm:K,confirmLabel:pe,checkboxes:je})},z=S.useCallback((Y,oe=176,K=220)=>{const pe=window.innerWidth,je=window.innerHeight,we=8;let Ye=Y.clientX,Qe=Y.clientY;return Ye+oe>pe-we&&(Ye=Math.max(we,pe-oe-we)),Qe+K>je-we&&(Qe=Math.max(we,je-K-we)),Ye=Math.max(we,Math.min(Ye,pe-oe-we)),Qe=Math.max(we,Math.min(Qe,je-K-we)),{x:Ye,y:Qe}},[]);S.useEffect(()=>{if(!F)return;const Y=()=>X(null),oe=setTimeout(()=>document.addEventListener("click",Y),0);return()=>{clearTimeout(oe),document.removeEventListener("click",Y)}},[F]);const re=S.useCallback(async(Y,oe)=>{oe==="offline"?await te.agents.start(Y):await te.agents.stop(Y),b()},[b]),Z=S.useCallback(async Y=>{await te.teams.update(s.id,{managerId:Y,managerType:"agent"}),g()},[s.id,g]),A=S.useCallback(async Y=>{await te.teams.removeMember(s.id,Y),g(),b()},[s.id,g,b]),J=S.useCallback(async(Y,oe)=>{await te.teams.removeMember(s.id,Y),await te.teams.addMember(oe,Y,"agent"),g(),b()},[s.id,g,b]);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:m!=null?{width:m}:{width:260},children:[c.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:p,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:k("common:back",{defaultValue:"Back"}),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&c.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&c.jsxs("div",{className:"mb-3",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:k("chat.groupChat",{defaultValue:"Group Chat"})}),c.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${U(!!L)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:k("chat.members_other",{count:i.memberCount||T.length+R.length})})]})]})]}),T.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.agents",{defaultValue:"Agents"}),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:T.length})]}),T.map(Y=>{const oe=n==="direct"&&a===Y.id,K=s.managerId===Y.id,pe=Y.status==="offline",je=gl(Y.status,cs.isAgentStreaming(Y.id)).dotClass;return c.jsxs("button",{"data-l2-nav-id":`agent:${Y.id}`,onClick:()=>d(Y.id),onContextMenu:we=>{if(!_)return;we.preventDefault();const Ye=z(we);j(!1),D(""),X({agentId:Y.id,...Ye})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${pe?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${U(oe)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:pe?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:Y.name}),K&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),pe&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:k("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Y.role||" "})]}),(O?.get(Y.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(Y.id)}),c.jsx("span",{title:Y.status,onClick:we=>{we.stopPropagation(),v(Y.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${je}`})]},Y.id)})]}),R.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.people"),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:R.length})]}),R.map(Y=>{const oe=Y.id===r?.id,K=n==="dm"&&l===Y.id;return c.jsxs("button",{"data-l2-nav-id":`dm:${Y.id}`,onClick:()=>f(Y.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${U(K)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[Y.name,oe?` (${k("chat.you",{defaultValue:"You"})})`:""]}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Y.email||Y.role})]}),c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},Y.id)})]}),T.length===0&&R.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:k("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),F&&(()=>{const Y=T.find(K=>K.id===F.agentId);if(!Y||!_)return null;const oe=s.managerId===Y.id;return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:F.x,top:F.y,maxHeight:Math.max(160,window.innerHeight-F.y-8)},onClick:K=>K.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{X(null),v(Y.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),k("contextMenu.viewProfile")]}),Y.status==="offline"?c.jsxs("button",{onClick:()=>{re(Y.id,"offline"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),k("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{re(Y.id,Y.status??"idle"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),k("contextMenu.stop")]}),!oe&&c.jsxs("button",{onClick:()=>{Z(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),k("contextMenu.setAsManager")]}),c.jsxs("button",{onClick:()=>{A(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),k("contextMenu.removeFromTeam")]}),(()=>{const K=h.filter(we=>we.id!==s.id);if(K.length===0)return null;const pe=W.trim().toLowerCase(),je=pe?K.filter(we=>we.name.toLowerCase().includes(pe)):K;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>j(we=>!we),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:k("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${ae?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ae&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:we=>we.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:W,onChange:we=>D(we.target.value),onKeyDown:we=>we.stopPropagation(),placeholder:k("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:je.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:k("contextMenu.moveToEmpty")}):je.map(we=>c.jsx("button",{type:"button",onClick:()=>{J(Y.id,we.id),X(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:we.name,children:we.name},we.id))})]})]})})(),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{fe(`${k("common:remove")} "${Y.name}"?`,k("modals.removeAgent.message"),async K=>{const pe=K?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await te.agents.remove(Y.id,{purgeFiles:pe}),b(),X(null)},k("common:remove"),[{id:"purgeFiles",label:k("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),k("contextMenu.removeFromOrg")]})]})})(),V&&c.jsx(Wo,{title:V.title,message:V.message,confirmLabel:V.confirmLabel,checkboxes:V.checkboxes,onConfirm:Y=>{V.onConfirm(Y),se(null)},onCancel:()=>se(null)})]})}function Pf(){return Pf=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},Pf.apply(null,arguments)}function sP(s,e){if(s==null)return{};var t={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(e.indexOf(r)!==-1)continue;t[r]=s[r]}return t}let Tf=[],Yv=[];(()=>{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<s.length;e++)(e%2?Yv:Tf).push(t=t+s[e])})();function rP(s){if(s<768)return!1;for(let e=0,t=Tf.length;;){let r=e+t>>1;if(s<Tf[r])t=r;else if(s>=Yv[r])e=r+1;else return!0;if(e==t)return!1}}function n0(s){return s>=127462&&s<=127487}const o0=8205;function iP(s,e,t=!0,r=!0){return(t?Gv:nP)(s,e,r)}function Gv(s,e,t){if(e==s.length)return e;e&&Kv(s.charCodeAt(e))&&Jv(s.charCodeAt(e-1))&&e--;let r=mu(s,e);for(e+=a0(r);e<s.length;){let i=mu(s,e);if(r==o0||i==o0||t&&rP(i))e+=a0(i),r=i;else if(n0(i)){let n=0,a=e-2;for(;a>=0&&n0(mu(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function nP(s,e,t){for(;e>1;){let r=Gv(s,e-2,t);if(r<e)return r;e--}return 0}function mu(s,e){let t=s.charCodeAt(e);if(!Jv(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return Kv(r)?(t-55296<<10)+(r-56320)+65536:t}function Kv(s){return s>=56320&&s<57344}function Jv(s){return s>=55296&&s<56320}function a0(s){return s<65536?1:2}let Lt=class ey{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,r){[e,t]=jo(this,e,t);let i=[];return this.decompose(0,e,i,2),r.length&&r.decompose(0,r.length,i,3),this.decompose(t,this.length,i,1),Kr.from(i,this.length-(t-e)+r.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=jo(this,e,t);let r=[];return this.decompose(e,t,r,0),Kr.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 Na(this),n=new Na(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 Na(this,e)}iterRange(e,t=this.length){return new ty(this,e,t)}iterLines(e,t){let r;if(e==null)r=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;r=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new sy(r)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?ey.empty:e.length<=32?new as(e):Kr.from(as.split(e,[]))}};class as extends Lt{constructor(e,t=oP(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.text[n],o=i+a.length;if((t?r:o)>=e)return new aP(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new as(l0(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=Wc(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]=jo(this,e,t);let i=Wc(this.text,Wc(r.text,l0(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new as(i,n):Kr.from(as.split(i,[]),n)}sliceString(e,t=this.length,r=`
@@ -55,7 +55,7 @@ ${he}
55
55
  `)})},[i,s]);S.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),ce=$e=>{if(!(he?$e.metaKey&&!$e.ctrlKey:$e.ctrlKey&&!$e.metaKey)||!$e.shiftKey||$e.altKey||$e.key.toLowerCase()!=="a")return;const de=J.current?.getSelection()?.trim();de&&($e.preventDefault(),Ue(de))};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[s.kind,i,Ue]);const mt=S.useCallback(he=>{if(!he.text.trim()||!i)return;const ce=re.current?.querySelector("iframe")?.getBoundingClientRect(),$e=(ce?.left??0)+he.rect.x+he.rect.width/2,Xe=(ce?.top??0)+he.rect.y;B({x:$e,y:Xe,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);S.useEffect(()=>{const he=re.current;if(!he||!i)return;const ce=()=>{requestAnimationFrame(()=>{const Xe=window.getSelection(),de=Xe?.toString().trim();if(!de||!Xe?.rangeCount){B(null);return}const De=Xe.getRangeAt(0);if(!he.contains(De.commonAncestorContainer)){B(null);return}const ve=De.getBoundingClientRect();B({x:ve.left+ve.width/2,y:ve.top,text:de})})},$e=Xe=>{const de=document.getElementById("right-panel-selection-toolbar");de&&de.contains(Xe.target)||B(null)};return he.addEventListener("mouseup",ce),document.addEventListener("mousedown",$e),()=>{he.removeEventListener("mouseup",ce),document.removeEventListener("mousedown",$e)}},[i,x.mode]);const xt=()=>{te.files.reveal(je||K).catch(()=>{})},bt=()=>{navigator.clipboard?.writeText(je||K).then(()=>{_(!0),setTimeout(()=>_(!1),1500)}).catch(()=>{})},vt=S.useMemo(()=>{if(!i)return null;const he=je||K;if(s.kind==="deliverable"){const ce=s.deliverable;if(!ce.id&&!ce.reference)return null;const $e=pe||ce.title||ce.reference||ce.id;return{label:`📄 ${$e.length>40?`${$e.slice(0,24)}…${$e.slice(-12)}`:$e}`,content:["[deliverable]",ce.id?`ID: ${ce.id}`:"",ce.title?`Title: ${ce.title}`:"",ce.reference?`Reference: ${ce.reference}`:"",ce.taskId?`Task: ${ce.taskId}`:"",ce.projectId?`Project: ${ce.projectId}`:""].filter(Boolean).join(`
56
56
  `)}}if(s.kind==="file"){if(!he||uo(he))return null;const ce=pe||he.split(/[/\\]/).pop()||he;return{label:`📄 ${ce.length>40?`${ce.slice(0,24)}…${ce.slice(-12)}`:ce}`,content:["[file]",`Path: ${he}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
57
57
  `)}}return null},[i,s,je,K,pe,x]),[Pe,Et]=S.useState(!1),Ft=S.useCallback(()=>{vt&&(i?.(vt),Et(!0),setTimeout(()=>Et(!1),1200))},[vt,i]),Es=S.useCallback(async()=>{if(s.kind==="deliverable"){Mr.navigate(Yt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ce=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const $e=await window.markusDesktop.browser.getState(s.browserId);if($e.ok){if($e.directoryPath){await te.system.openPath($e.directoryPath).catch(()=>te.files.reveal($e.directoryPath));return}$e.url&&$e.url!=="about:blank"&&(ce=$e.url)}}catch{}if(!ce||ce==="about:blank")return;if(/^https?:\/\//i.test(ce)||/^file:\/\//i.test(ce)){ac(ce);return}await te.system.openPath(ce).catch(()=>ac(mv(ce)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){ac(he);return}await te.system.openPath(he).catch(()=>ac(mv(he)))}},[s]),rt=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,yt=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),Bt=!!K&&!uo(K)&&(s.kind==="file"||s.kind==="deliverable"),dt=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!K&&!uo(K)&&!s.deliverable.artifactType&&qC(s.deliverable.format),Ze=s.kind==="deliverable"?{...s.deliverable,hubShareId:L?.id??s.deliverable.hubShareId??null,shareStatus:L?.status??s.deliverable.shareStatus??null,shareUrl:L?.url??s.deliverable.shareUrl??null,shareVisibility:L?.visibility??s.deliverable.shareVisibility??null}:null,Xt=S.useCallback(he=>{M(he)},[]),ot=S.useMemo(()=>ZC(vO,Fm.getUrl()),[]),At=s.kind==="deliverable"?s.deliverable.id:null;S.useEffect(()=>{if(!At||!vO())return;let he=!1;const ce=async()=>{try{const Xe=await ot.listMine();if(he)return;const de=s.kind==="deliverable"?s.deliverable:null;if(!de)return;const De=de.hubShareId&&Xe.find(ze=>ze.id===de.hubShareId)||Xe.find(ze=>ze.localId===de.id);if(!De)return;M(ze=>ze&&ze.id===De.id&&ze.status===De.status?ze:De);const ve={hubShareId:de.hubShareId??De.id??null,shareStatus:De.status??null,shareUrl:De.url??null,shareVisibility:de.shareVisibility??De.visibility??null};(de.shareStatus!==ve.shareStatus||de.hubShareId!==ve.hubShareId||de.shareUrl!==ve.shareUrl||de.shareVisibility!==ve.shareVisibility)&&de.id&&te.deliverables.update(de.id,ve).catch(ze=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ze)})}catch{}};ce();const $e=setInterval(ce,3e4);return()=>{he=!0,clearInterval($e)}},[ot,At,s]);const ds=Ze?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:m("common:browserMode",{defaultValue:"Browser"}),"aria-label":m("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":p==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:m("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":m("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":p==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),we||h?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0 self-stretch flex flex-col justify-end",children:[c.jsxs("div",{ref:Z,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:he=>{const ce=he.currentTarget;ce.scrollWidth<=ce.clientWidth||Math.abs(he.deltaY)<=Math.abs(he.deltaX)||(ce.scrollLeft+=he.deltaY,he.preventDefault())},children:[n?.map(he=>{const ce=he.id===a,$e=he.payload.kind==="url"?he.payload.pageId:void 0,Xe=he.payload.kind==="terminal"?he.payload.terminalId:void 0,de=$e!=null?U[$e]:Xe?X[Xe]:void 0,De=de?`${he.title} — ${m("common:browserTabControlledBy",{name:de.agentName})}`:he.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ce?de?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":de?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":ce,ref:ce?A:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:De,onPointerDown:ve=>{ve.button===0&&(he.id!==a&&!oe()||o?.(he.id))},onClick:()=>{he.id!==a&&!oe()||o?.(he.id)},children:[de&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:m("common:browserTabControlledBy",{name:de.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:de.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:ve=>{ve.button===0&&(ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id))},onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ce?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:m("common:closeTab",{defaultValue:"Close tab"}),"aria-label":m("common:closeTab",{defaultValue:"Close tab"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:m("common:newTab",{defaultValue:"New Tab"}),"aria-label":m("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),c.jsx(vD,{scrollRef:Z,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:K||pe,children:pe}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[Qe&&c.jsx("button",{type:"button",onClick:ye,title:m("common:refreshPreview",{defaultValue:"刷新"}),"aria-label":m("common:refreshPreview",{defaultValue:"刷新"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{className:x.mode==="loading"?"animate-spin":"",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),Qe&&c.jsx("button",{type:"button",onClick:()=>fe(he=>!he),"aria-pressed":se,title:se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),"aria-label":se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${se?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{He()},title:m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),vt&&c.jsx("button",{type:"button",onClick:Ft,title:Pe?m("common:addedToChat",{defaultValue:"Added to chat"}):s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),"aria-label":s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Pe?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:Pe?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h6"}),c.jsx("line",{x1:"17",y1:"3",x2:"17",y2:"9"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"})]})}),dt&&c.jsxs("button",{type:"button",onClick:()=>R(!0),title:m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${ds==="published"?"text-green-500 hover:text-green-400":ds==="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"})]}),(ds==="published"||ds==="pending_review"||ds==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${ds==="published"?"bg-green-500":ds==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),rt&&c.jsx("button",{type:"button",onClick:()=>{Es()},title:yt,"aria-label":yt,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),Bt&&c.jsx("button",{onClick:bt,title:P?m("common:copied",{defaultValue:"Copied"}):m("common:copyPath",{defaultValue:"复制路径"}),"aria-label":m("common:copyPath",{defaultValue:"复制路径"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${P?"text-green-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:P?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),Bt&&c.jsx("button",{onClick:xt,title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?m("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):m("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{oe()&&e()},title:m("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":m("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="directory"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[k&&x.mode!=="directory"&&x.mode!=="loading"&&c.jsx("div",{className:"shrink-0 mb-2",children:c.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-fg-secondary hover:text-brand-500 transition-colors cursor-pointer",onClick:()=>C(_D(je)),children:[c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 20 20",fill:"currentColor",children:c.jsx("path",{fillRule:"evenodd",d:"M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z",clipRule:"evenodd"})}),"返回上级目录"]})}),x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${yf(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${yf(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[m("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${yf(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{te.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="office"&&c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(Kk,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{te.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const he=K?K.replace(/[/\\][^/\\]+$/,""):void 0,ce=K&&!uo(K)?K:"",$e=x.format;return ce&&($e==="code"||$e==="json"||$e==="text")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(x_,{path:ce,initialContent:x.content,language:tg(ce,$e),onDirtyChange:W})}):ce&&($e==="markdown"||$e==="html")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(z4,{path:ce,content:x.content,format:$e,basePath:he,onHtmlSelection:mt,onDirtyChange:W})}):c.jsx("div",{ref:re,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.content,format:$e,className:"text-fg-secondary text-sm",onHtmlSelection:mt,basePath:he})})})(),x.mode==="artifact"&&c.jsx("div",{ref:re,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(aD,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(OD,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:J,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:he=>{if(!he||!i){B(null);return}B({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(Jk,{path:x.path,entries:x.entries,onNavigate:he=>C(he),onOpenFile:he=>C(he),onReveal:xt,onCopyPath:bt}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?m("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):m("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:xt,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),c.jsx("button",{onClick:xt,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:m("common:open",{defaultValue:"Open"})}),c.jsx("button",{onClick:bt,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?m("common:copied",{defaultValue:"Copied"}):m("common:copy",{defaultValue:"Copy"})})]})]})]},`${Ye}#${D}`)]}),E&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:E.x,top:E.y-8},children:c.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),Ue(E.text,E.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),m("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&Ze&&c.jsx(VC,{item:Ze,onClose:()=>R(!1),onShared:Xt})]})}function CD({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=Pt(["team","common"]);return c.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",r,")"]}),c.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(l=>c.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${l.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[c.jsx(Ns,{name:l.name,size:16,bgClass:l.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),l.name,l.id!==t&&c.jsx("button",{onClick:()=>n(l.id),className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},l.id))}),e.length>0&&c.jsx("div",{className:"mt-1",children:c.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:l=>{l.target.value&&a(l.target.value)},children:[c.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),e.map(l=>c.jsxs("option",{value:l.id,children:["[",l.type==="agent"?"Agent":"Human","] ",l.name]},l.id))]})})]})}const PD={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},TD={text:"bg-brand-500/10 text-brand-500",thinking:"bg-amber-500/10 text-amber-600",tool:"bg-sky-500/10 text-sky-600"};function QD({match:s}){const e=s.snippet.slice(0,s.snippetMatchStart),t=s.snippet.slice(s.snippetMatchStart,s.snippetMatchStart+s.snippetMatchLength),r=s.snippet.slice(s.snippetMatchStart+s.snippetMatchLength);return c.jsxs("span",{className:"text-xs text-fg-secondary",children:[e,c.jsx("mark",{className:"bg-yellow-500/30 text-fg-primary rounded-[3px] px-0.5",children:t}),r]})}function $D({query:s,onQueryChange:e,matches:t,cursor:r,scanned:i,hasMore:n,loadingMore:a,truncated:o,onLoadEarlier:l,onJump:h,onClose:d,labelFor:u,serverResults:f,serverLoading:p,onServerResultClick:v}){const{t:b,i18n:g}=Pt(["team","common"]),O=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{O.current?.focus()},[]),S.useEffect(()=>{if(r<0)return;m.current?.querySelector(`[data-find-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);const x=k=>{if(t.length===0)return;const P=(((r<0?k>=0?-1:0:r)+k)%t.length+t.length)%t.length;h(P)},y=s.trim().length>0;return c.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/60 px-4 py-2 space-y-1.5 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("div",{className:"flex-1 relative",children:[c.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),c.jsx("input",{ref:O,value:s,onChange:k=>e(k.target.value),onKeyDown:k=>{k.key==="Escape"?(k.preventDefault(),d()):k.key==="Enter"?(k.preventDefault(),x(k.shiftKey?-1:1)):k.key==="ArrowDown"?(k.preventDefault(),x(1)):k.key==="ArrowUp"&&(k.preventDefault(),x(-1))},placeholder:b("page.findPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),c.jsx("span",{className:"text-[11px] text-fg-tertiary tabular-nums shrink-0 min-w-[44px] text-center",children:y&&t.length>0?b("page.findMatchCount",{current:(r<0?0:r)+1,total:t.length}):y?"0/0":""}),c.jsx("button",{onClick:()=>x(-1),disabled:t.length===0,title:b("page.findPrev"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"18 15 12 9 6 15"})})}),c.jsx("button",{onClick:()=>x(1),disabled:t.length===0,title:b("page.findNext"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("button",{onClick:d,title:b("page.findClose"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated transition-colors",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y&&c.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:b("page.findScopeLoaded",{count:i})}),o&&c.jsx("span",{className:"text-amber-600",children:b("page.findTruncated",{count:t.length})}),t.length===0&&!n&&c.jsx("span",{className:"text-fg-secondary",children:b("page.findNoMatches")}),n&&c.jsx("button",{onClick:l,disabled:a,className:"ml-auto text-brand-500 hover:text-brand-500 disabled:opacity-50 underline decoration-dotted",children:b(a?"page.findLoadingEarlier":"page.findLoadEarlier")})]}),y&&t.length>0&&c.jsx("div",{ref:m,className:"max-h-52 overflow-y-auto scrollbar-thin space-y-0.5",children:t.map((k,C)=>c.jsxs("button",{"data-find-idx":C,onClick:()=>h(C),className:`w-full text-left px-2.5 py-1.5 rounded-lg transition-colors ${C===r?"bg-brand-500/15 ring-1 ring-brand-500/40":"hover:bg-surface-elevated"}`,children:[c.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${TD[k.field]}`,children:b(PD[k.field])}),u&&c.jsx("span",{className:"text-[10px] text-fg-tertiary truncate",children:u(k)})]}),c.jsx("div",{className:"line-clamp-2 break-words",children:c.jsx(QD,{match:k})})]},`${k.messageId}-${k.field}-${C}`))}),y&&(p||f&&f.length>0)&&c.jsxs("div",{className:"border-t border-border-default/60 mt-1 px-1",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-medium py-0.5",children:b("page.findServerResultsTitle")}),p&&c.jsx("div",{className:"text-xs text-fg-tertiary px-2.5 py-1",children:b("page.searching")}),f&&f.length>0&&c.jsx("div",{className:"max-h-40 overflow-y-auto scrollbar-thin space-y-0.5",children:f.map(k=>c.jsxs("button",{onClick:()=>v?.(k),className:"w-full text-left px-2.5 py-1.5 rounded-lg transition-colors hover:bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-fg-tertiary mb-0.5 min-w-0",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${k.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:k.source==="channel"?"#":"1:1"}),c.jsx("span",{className:"truncate max-w-[9rem] text-fg-secondary font-medium",children:k.source==="channel"?k.channel?`#${k.channel}`:b("page.findServerResultsTitle"):k.sessionTitle||b("page.untitledSession")}),k.senderName&&c.jsx("span",{className:"truncate max-w-[6rem] shrink-0",children:k.senderName}),c.jsx("span",{className:"shrink-0 ml-auto tabular-nums",title:zm(k.createdAt,g.language),children:Xm(k.createdAt,b)})]}),c.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 break-words",children:k.text.length>200?k.text.slice(0,200)+"…":k.text})]},k.id))})]})]})}const jD=300,RD=48;function ED(s){const e=[];if(s.segments&&s.segments.length>0){for(const t of s.segments)if(t.type==="text")t.thinking&&e.push({field:"thinking",value:t.thinking}),t.content&&e.push({field:"text",value:t.content});else if(t.type==="tool"){const r=[t.tool,t.result,t.error].filter(i=>!!i);r.length>0&&e.push({field:"tool",value:r.join(`
58
- `)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function AD(s,e,t,r=RD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function MD(s,e,t={}){const r=t.limit??jD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of ED(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=AD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function LD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function ND(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const DD="markus.scrollDebug";let Sf=null,pv=!1;function ID(){if(!pv){try{Sf=typeof localStorage<"u"&&localStorage.getItem(DD)==="1"}catch{Sf=!1}pv=!0}return Sf===!0}function zi(s,e){ID()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function BD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function WD(s){return s.details?.agentId??s.agentId}function XD(s){const e=s.details??{};return[e.chatSessionId,e.sessionId].filter(t=>typeof t=="string"&&t.length>0)}function zD(s,e){const t=s.filter(n=>BD(n)&&WD(n)===e.agentId);if(!e.sessionId)return t;const r=[],i=[];for(const n of t)(XD(n).includes(e.sessionId)?r:i).push(n);return[...r,...i]}const gv={urgent:0,high:1,normal:2,low:3};function Ov(s){return gv[s??"normal"]??gv.normal}function qD(s){return[...s].sort((e,t)=>{const r=Ov(e.priority)-Ov(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function ZD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Mm(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function VD(s,e){return e?qD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&ZD(t)===e)):[]}const xv={sessionId:null,messageId:null};function FD(s){if(s.length===0)return xv;const e=new Set(s.map(Mm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Mm(n)))return xv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const $_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Lc(s){return s?$_[s]?.icon??"●":"●"}const UD=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries($_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),HD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function YD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of HD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function GD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function KD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const JD=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function bv(s){if(!s)return null;for(const e of JD){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const j_=16;function eI(s,e,t=j_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function tI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const sI=S.lazy(()=>Xv(()=>import("./index-DyYU0JDE.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),rh={mind:"mind",files:"files",tools:"tools",memory:"memory"},ag=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Lm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function rI(s,e){const{labelKey:t}=zh(s);return t?e(t):s}function Nm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function vv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Pt(["agent","common"]),u=qm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),k=S.useMemo(()=>ag.map(F=>({...F,label:d(`agent:tabs.${F.key}`)})),[d]),C=S.useMemo(()=>k.map(F=>({id:F.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=eC(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const F=T.current;if(!F)return;F.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),R(),te.externalAgents.list().then(X=>{const ae=X.agents.find(j=>j.markusAgentId===s);y(ae??null)}).catch(()=>{}),_t.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=zh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=F=>h??rh[F],B=F=>x||rh[F]?"overview":F,U=rh[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[B(m)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:E(m)}),B(m)==="deliverables"&&c.jsx(Rv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ns,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:rI(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Mr.navigate(Yt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),M&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:F}=await te.agents.getFilesMap(s),X={type:"agent",name:Bv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await Fm.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:F}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(F){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(F)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(F=>!x||F.key==="overview").map(F=>c.jsxs("button",{onClick:()=>O(F.key),"data-active":g===F.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===F.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:F.icon}),F.label]},F.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?_.onTouchStart:void 0,onTouchEnd:u?_.onTouchEnd:void 0,children:[B(g)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:h??U}),B(g)==="deliverables"&&c.jsx(Rv,{agentId:s})]}),v&&c.jsx(Wo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function iI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Um.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function fo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function yv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Bh,{agentId:s,activityId:e.id})})]})}function Sv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[k,C]=S.useState(!1),[P,_]=S.useState(!1),[T,R]=S.useState(()=>r0(a,n));S.useEffect(()=>{R(r0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const V=D.agents.find(se=>se.agentId===s.id);V&&l(V)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(V=>s.state.activeTaskIds?.includes(V.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,L,s.state.status]),S.useEffect(()=>{if(T!=="usage")return;let D=!1;return C(!0),te.system.storage().then(V=>{if(D)return;g(V.dataDir+"/agents/"+s.id);const se=V.agents.find(fe=>fe.id===s.id);se&&v(se)}).catch(()=>{}).finally(()=>{D||C(!1)}),()=>{D=!0}},[T,s.id]),S.useEffect(()=>{if(T!=="recent")return;let D=!1;return _(!0),te.agents.getActivities(s.id,{limit:H2}).then(V=>{D||d(V.activities)}).catch(()=>{}).finally(()=>{D||_(!1)}),()=>{D=!0}},[T,s.id]);const M=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},E=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),B=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(fs,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:B.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(fs,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:E.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:U,comms:F}=Y2(h),X=s0(U),ae=s0(F),j=s.state.activeTaskIds?.length??0,W=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,X.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:X.total}):null,ae.total>0?r("agent:profilePage.overview.a2aRuns",{count:ae.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Nm(z2(o,s.state.tokensUsedToday))}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(j),color:j>0?"blue":void 0}),i&&c.jsx("button",{onClick:M,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:ih(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(j>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Lm(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(iI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(fo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Nm(o.totalTokens)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.storage"),value:Tv(p.size)}),q2(p.subItems).map(D=>{const V=V2(D.name);return c.jsx(Ks,{label:V?r(V):D.name,value:Tv(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(fo,{children:[W&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:W}),X.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:X.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),ae.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:ae.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),X.total===0&&ae.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(fo,{children:c.jsx(wI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(fo,{children:c.jsx(lI,{agentId:s.id})}),T==="tools"&&c.jsx(fo,{children:c.jsx(fI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(fo,{children:[c.jsx(pI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(mI,{agentId:s.id})})]})]})}function nI(s,e){const t=s.split(`
58
+ `)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function AD(s,e,t,r=RD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function MD(s,e,t={}){const r=t.limit??jD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of ED(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=AD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function LD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function ND(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const DD="markus.scrollDebug";let Sf=null,pv=!1;function ID(){if(!pv){try{Sf=typeof localStorage<"u"&&localStorage.getItem(DD)==="1"}catch{Sf=!1}pv=!0}return Sf===!0}function zi(s,e){ID()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function BD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function WD(s){return s.details?.agentId??s.agentId}function XD(s){const e=s.details??{};return[e.chatSessionId,e.sessionId].filter(t=>typeof t=="string"&&t.length>0)}function zD(s,e){const t=s.filter(n=>BD(n)&&WD(n)===e.agentId);if(!e.sessionId)return t;const r=[],i=[];for(const n of t)(XD(n).includes(e.sessionId)?r:i).push(n);return[...r,...i]}const gv={urgent:0,high:1,normal:2,low:3};function Ov(s){return gv[s??"normal"]??gv.normal}function qD(s){return[...s].sort((e,t)=>{const r=Ov(e.priority)-Ov(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function ZD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Mm(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function VD(s,e){return e?qD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&ZD(t)===e)):[]}const xv={sessionId:null,messageId:null};function FD(s){if(s.length===0)return xv;const e=new Set(s.map(Mm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Mm(n)))return xv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const $_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Lc(s){return s?$_[s]?.icon??"●":"●"}const UD=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries($_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),HD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function YD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of HD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function GD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function KD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const JD=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function bv(s){if(!s)return null;for(const e of JD){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const j_=16;function eI(s,e,t=j_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function tI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const sI=S.lazy(()=>Xv(()=>import("./index-Ci5bUF3m.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),rh={mind:"mind",files:"files",tools:"tools",memory:"memory"},ag=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Lm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function rI(s,e){const{labelKey:t}=zh(s);return t?e(t):s}function Nm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function vv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Pt(["agent","common"]),u=qm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),k=S.useMemo(()=>ag.map(F=>({...F,label:d(`agent:tabs.${F.key}`)})),[d]),C=S.useMemo(()=>k.map(F=>({id:F.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=eC(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const F=T.current;if(!F)return;F.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),R(),te.externalAgents.list().then(X=>{const ae=X.agents.find(j=>j.markusAgentId===s);y(ae??null)}).catch(()=>{}),_t.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=zh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=F=>h??rh[F],B=F=>x||rh[F]?"overview":F,U=rh[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[B(m)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:E(m)}),B(m)==="deliverables"&&c.jsx(Rv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ns,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:rI(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Mr.navigate(Yt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),M&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:F}=await te.agents.getFilesMap(s),X={type:"agent",name:Bv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await Fm.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:F}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(F){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(F)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(F=>!x||F.key==="overview").map(F=>c.jsxs("button",{onClick:()=>O(F.key),"data-active":g===F.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===F.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:F.icon}),F.label]},F.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?_.onTouchStart:void 0,onTouchEnd:u?_.onTouchEnd:void 0,children:[B(g)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:h??U}),B(g)==="deliverables"&&c.jsx(Rv,{agentId:s})]}),v&&c.jsx(Wo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function iI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Um.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function fo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function yv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Bh,{agentId:s,activityId:e.id})})]})}function Sv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[k,C]=S.useState(!1),[P,_]=S.useState(!1),[T,R]=S.useState(()=>r0(a,n));S.useEffect(()=>{R(r0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const V=D.agents.find(se=>se.agentId===s.id);V&&l(V)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(V=>s.state.activeTaskIds?.includes(V.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,L,s.state.status]),S.useEffect(()=>{if(T!=="usage")return;let D=!1;return C(!0),te.system.storage().then(V=>{if(D)return;g(V.dataDir+"/agents/"+s.id);const se=V.agents.find(fe=>fe.id===s.id);se&&v(se)}).catch(()=>{}).finally(()=>{D||C(!1)}),()=>{D=!0}},[T,s.id]),S.useEffect(()=>{if(T!=="recent")return;let D=!1;return _(!0),te.agents.getActivities(s.id,{limit:H2}).then(V=>{D||d(V.activities)}).catch(()=>{}).finally(()=>{D||_(!1)}),()=>{D=!0}},[T,s.id]);const M=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},E=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),B=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(fs,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(fs,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:B.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(fs,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:E.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:U,comms:F}=Y2(h),X=s0(U),ae=s0(F),j=s.state.activeTaskIds?.length??0,W=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,X.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:X.total}):null,ae.total>0?r("agent:profilePage.overview.a2aRuns",{count:ae.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Nm(z2(o,s.state.tokensUsedToday))}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(j),color:j>0?"blue":void 0}),i&&c.jsx("button",{onClick:M,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:ih(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(j>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Lm(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(iI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(fo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Nm(o.totalTokens)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.storage"),value:Tv(p.size)}),q2(p.subItems).map(D=>{const V=V2(D.name);return c.jsx(Ks,{label:V?r(V):D.name,value:Tv(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(fo,{children:[W&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:W}),X.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:X.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),ae.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:ae.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),X.total===0&&ae.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(fo,{children:c.jsx(wI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(fo,{children:c.jsx(lI,{agentId:s.id})}),T==="tools"&&c.jsx(fo,{children:c.jsx(fI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(fo,{children:[c.jsx(pI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(mI,{agentId:s.id})})]})]})}function nI(s,e){const t=s.split(`
59
59
  `),r=e.split(`
60
60
  `),i=t.length,n=r.length,a=Array.from({length:i+1},()=>new Array(n+1).fill(0));for(let f=i-1;f>=0;f--)for(let p=n-1;p>=0;p--)a[f][p]=t[f]===r[p]?a[f+1][p+1]+1:Math.max(a[f+1][p],a[f][p+1]);const o=[];let l=0,h=0,d=1,u=1;for(;l<i||h<n;)l<i&&h<n&&t[l]===r[h]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,h++):h<n&&(l>=i||a[l][h+1]>=a[l+1][h])?(o.push({type:"add",content:r[h],lineNum:u++}),h++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function wv(s){return s.match(/\S+|\s+/g)??[""]}function _v({oldText:s,newText:e,mode:t}){const r=wv(s),i=wv(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=r[u]===i[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let h=0,d=0;for(;h<n||d<a;)h<n&&d<a&&r[h]===i[d]?(l.push({text:t==="remove"?r[h]:i[d],changed:!1}),h++,d++):d<a&&(h>=n||o[h][d+1]>=o[h+1][d])?(t==="add"&&l.push({text:i[d],changed:!0}),d++):(t==="remove"&&l.push({text:r[h],changed:!0}),h++);return c.jsx("span",{children:l.map((u,f)=>u.changed?c.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):c.jsx("span",{children:u.text},f))})}function oI({agent:s,template:e,templateId:t}){const{t:r}=Pt(["agent","common"]),i=S.useMemo(()=>nI(s,e),[s,e]),[n,a]=S.useState(!0),o=3,l=S.useMemo(()=>{const p=i.map((O,m)=>O.type!=="equal"?m:-1).filter(O=>O>=0);if(p.length===0)return[];const v=[];let b=Math.max(0,p[0]-o),g=Math.min(i.length-1,p[0]+o);for(let O=1;O<p.length;O++){const m=Math.max(0,p[O]-o),x=Math.min(i.length-1,p[O]+o);m<=g+1||(v.push({start:b,end:g}),b=m),g=x}return v.push({start:b,end:g}),v},[i]),h=(p,v,b)=>{const g=p.type==="add"?"+":p.type==="remove"?"-":" ",O=p.type==="add"?"bg-green-500/8":p.type==="remove"?"bg-red-500/8":"",m=p.type==="add"?"text-green-600/90":p.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=p.type==="add"?"text-green-500":p.type==="remove"?"text-red-500":"text-fg-muted",y=p.type==="remove"?p.oldLineNum:p.lineNum;let k=null;return p.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?k=c.jsx(_v,{oldText:p.content,newText:b[v+1].content,mode:"remove"}):p.type==="add"&&v>0&&b[v-1].type==="remove"&&(k=c.jsx(_v,{oldText:b[v-1].content,newText:p.content,mode:"add"})),c.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[c.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),c.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:g}),c.jsxs("span",{className:`flex-1 text-[11px] font-mono ${m} whitespace-pre-wrap break-words leading-[20px]`,children:[k??p.content,p.content===""&&" "]})]},v)},d=i.filter(p=>p.type==="add").length,u=i.filter(p=>p.type==="remove").length,f=n?l.flatMap(p=>{const v=[];for(let b=p.start;b<=p.end;b++)v.push({...i[b],_idx:b});return v}):i.map((p,v)=>({...p,_idx:v}));return c.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),c.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),c.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),c.jsx("button",{onClick:()=>a(p=>!p),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),c.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((p,v)=>{const b=v>0?f[v-1]:null,g=n&&b&&p._idx-b._idx>1;return c.jsxs("div",{children:[g&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),h(p,p._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function aI(s,e){const t=s.split(`
61
61
  `),r=e.split(`
@@ -72,7 +72,7 @@ ${he}
72
72
  `+ae.join(`
73
73
  ---
74
74
 
75
- `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Mr.navigate(Yt.TEAM,{agentId:s,prefillMessage:j})},L=async F=>{if(y?.file===F){k(null);return}try{const X=await te.agents.roleDiff(s,F);X.agentContent!=null&&X.templateContent!=null&&k({file:F,agent:X.agentContent,template:X.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const M={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=F=>{const X=M[F];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):F},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(F=>F.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[B&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(F=>F.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(fs,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(F=>{const X=T.some(ae=>ae.file===F.name);return c.jsxs("button",{onClick:()=>P(F.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===F.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[F.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},F.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[U&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-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(oI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(cI,{content:t.find(F=>F.name===a)?.content??"",editContent:l,setEditContent:F=>{h(F),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Wh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function cI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(sI,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function hI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function dI({tools:s}){const{t:e}=Pt(["agent","common"]),t=YD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(fs,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=nC(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=hI(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(oC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function uI({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(fs,{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(Wh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function fI({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(dI,{tools:s}):c.jsx(uI,{agent:e})]})}function mI({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,k]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(M=>{r(M),h(M.recentDailyLogs??""),u(M.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},_=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),R=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:L.map(M=>c.jsx("button",{onClick:()=>o(M.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===M.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:M.label},M.key))}),a==="entries"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Wh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((M,E)=>{const B=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(B?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${M.type==="fact"?"bg-blue-500/15 text-blue-600":M.type==="task"?"bg-green-500/15 text-green-600":M.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:M.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:M.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${M.importance>=7?"bg-red-500/15 text-red-500":M.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",M.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(M.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:M.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",M.type]}),M.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",M.importance]}),c.jsx("span",{children:new Date(M.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Wh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(M=>{const E=g===M.id,B=async()=>{if(E){O(null),x([]);return}O(M.id),k(!0);try{const U=await te.agents.getMemorySession(s,M.id);x(U.messages)}catch{x([])}k(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:M.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[M.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(M.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const U=new Map;for(const F of m)F.role==="tool"&&F.toolCallId&&U.set(F.toolCallId,F.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(F=>F.role!=="tool").map((F,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(F.role==="user"||F.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${F.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${F.role}`,{defaultValue:F.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[F.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.toolCalls&&F.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:F.toolCalls.map(ae=>{let j;try{j=JSON.parse(ae.arguments)}catch{}const W={tool:ae.name,status:"done",args:j,result:U.get(ae.id)};return c.jsx(sC,{entry:{type:"tool",info:W}},ae.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:M=>h(M.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:R?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:M=>u(M.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function pI({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>_t.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(fs,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ks,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(OI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(fs,{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(fs,{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(fs,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx($o,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(fs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Bh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(fs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function gI({taskId:s,isLive:e}){const{t}=Pt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0);if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(d=>{i(d.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const d=_t.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),u=_t.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{d(),u()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(d=>iC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Bh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Pt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0);if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?_t.on("agent:activity_log",d=>{const u=d.payload;if(u.agentId!==s||u.activityId!==e)return;const f={seq:u.seq,type:u.type,content:u.content,metadata:u.metadata,createdAt:u.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>rC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:l,isStreaming:t})})}function fs({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Ks({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const kv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Cv=5,Pv=1440;function OI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Pt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<Cv||m>Pv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=kv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),kv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Cv,max:Pv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Wh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Tv(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const Qv={0:"0",1:"1",2:"2",3:"3",4:"4"},$v={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},xI={pick:"bg-brand-500/20 text-brand-500",continue:"bg-gray-500/20 text-gray-500",preempt:"bg-amber-500/20 text-amber-500",merge:"bg-blue-500/20 text-blue-500",defer:"bg-purple-500/20 text-purple-500",delegate:"bg-green-500/20 text-green-500",drop:"bg-red-500/20 text-red-500"},bI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},vI=["all","interaction","task","notification","system"],yI={completed:"bg-green-500",processing:"bg-blue-400 animate-pulse",deferred:"bg-purple-400",merged:"bg-brand-400",queued:"bg-amber-400",dropped:"bg-red-500"},SI={pending:"text-gray-400",assigned:"text-blue-400",in_progress:"text-brand-400",completed:"text-green-400",failed:"text-red-400",cancelled:"text-gray-500",review:"text-amber-400",approved:"text-green-500",rejected:"text-red-500",draft:"text-gray-400"};function wf(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function jv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Lm(d,e),p=Lm(u,e),v=SI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=wf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function wI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Pt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[k,C]=S.useState(!1),[P,_]=S.useState(!0),[T,R]=S.useState(null),L=50,M=3,[E,B]=S.useState(null),U=S.useCallback(async(z=!0)=>{z&&d(!0);try{const re=u==="all"?void 0:u,Z=p==="all"?void 0:p,[A,J]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:re,status:Z})]);a(A),l(J),_((J.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),F=S.useCallback(async z=>{B(z);try{await te.agents.dropMailboxItem(s,z,"operator"),await U()}catch{}finally{B(null)}},[s,U]),X=S.useCallback(async()=>{if(!o)return;const z=u==="all"?void 0:u,re=p==="all"?void 0:p;try{const Z=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:re});l(A=>A?{...A,history:[...A.history,...Z.history]}:Z),_((Z.history?.length??0)>=L)}catch{}},[s,o,u,p]),ae=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await U()},[s,U]);S.useEffect(()=>{g(e??null),m(e??null),U()},[U,e]);const j=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(re=>re.id===O)){j.current=!1;const re=document.getElementById(`mbx-${O}`);if(re){setTimeout(()=>re.scrollIntoView({behavior:"smooth",block:"center"}),100);const Z=setTimeout(()=>m(null),3e3);return()=>clearTimeout(Z)}}else P&&!j.current&&(j.current=!0,(async()=>{let re=o?.history??[],Z=P;for(;Z;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:re.length}),J=[...re,...A.history];re=J,Z=(A.history?.length??0)>=L;const Y=A.history.some(oe=>oe.id===O);if(l(oe=>oe?{...oe,history:J}:A),_(Z),Y||!Z)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const re=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},Z=[_t.on("agent:mailbox",re),_t.on("agent:decision",re),_t.on("agent:attention",re),_t.on("agent:focus",re),_t.on("agent:update",re),_t.on("agent:triage",re)];return()=>{z&&clearTimeout(z),Z.forEach(A=>A())}},[s,U]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const W=n?.mailboxDepth??n?.queuedItems?.length??0,D=zh(t).running,V=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=V==="idle"&&o?.history?.some(z=>z.status==="processing"),fe=(n?.attentionState??"idle")==="idle"&&W>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[D?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${bI[V]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${V}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),D?n?.currentFocus?(()=>{const z=jv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Lc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:z.title}),z.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:z.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():fe?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:W,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:W})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{U()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),D&&se&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ae()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const z=n.queuedItems,re=z.length>M,Z=re&&!x?z.slice(0,M):z,A=z.reduce((J,Y)=>(J[Y.sourceType]=(J[Y.sourceType]??0)+1,J),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:z.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([J,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Lc(J)," ",Y]},J))})]}),c.jsxs("div",{className:"space-y-1",children:[Z.map((J,Y)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:Y+1}),c.jsx("span",{className:"text-sm",children:Lc(J.sourceType)}),c.jsx("span",{className:`text-[10px] ${$v[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[J.priority]??J.priority}`,{defaultValue:`P${J.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:J.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(J.queuedAt).toLocaleTimeString()})]},J.id)),re&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:z.length-M})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const z=eI(n.notebook,k);return c.jsx("section",{className:"bg-surface-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:j_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(re=>{const Z=tI(re.updatedAt),A=i(`agent:profilePage.relative.${Z.unit==="seconds"?"secondsAgo":Z.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:Z.count,hours:Z.count}),J=re.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-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:re.key}),c.jsxs("span",{className:`text-[10px] ${J}`,children:["[",re.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:re.text.length>500?re.text.slice(0,500)+"…":re.text})]},re.key)}),z.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:z.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-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] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Bh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const re=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,Z=J2(n.lastTriage);return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${re?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!re,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-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)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${Z.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-3 text-fg-tertiary"}`,children:Z.isBatch?i("agent:profilePage.mind.batchSize",{count:Z.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:vI.map(z=>{const re=o?.sourceTypeCounts,Z=z==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?(UD[z]??[]).reduce((A,J)=>A+(re[J]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(z),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===z?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[i(`agent:profilePage.mind.categoryFilters.${z}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(z=>{const re=o?.statusCounts,Z=z.key==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?.[z.key];return c.jsxs("button",{onClick:()=>v(z.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===z.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[z.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z.dot}`}),i(`agent:profilePage.mind.statusFilters.${z.key}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(z=>{const re=b===z.id,Z=Lc(z.sourceType),A=jv(z,i),J=KD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,oe=z.metadata?.senderRole,K=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${K?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>g(re?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:re?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${J==="stale"?"bg-amber-400/70":yI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:Z}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${re?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${$v[z.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[z.priority]??z.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${re?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(z.queuedAt).toLocaleString()}),z.completedAt&&c.jsxs("span",{children:["→ ",new Date(z.completedAt).toLocaleTimeString()]}),z.activity&&c.jsxs(c.Fragment,{children:[z.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Nm(z.activity.totalTokens)})}),z.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:z.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:z.sourceType}),r&&GD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:pe=>{pe.stopPropagation(),R(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),re&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[Y&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Y}),oe&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",oe,")"]})]}),z.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(z.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:z.payload.content}),z.decisions&&z.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:z.decisions.map(pe=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${xI[pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:pe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:pe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(pe.createdAt).toLocaleTimeString()})]},pe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===z.id,onClick:()=>{F(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),z.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:z.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${z.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:z.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),z.activity.type==="task"&&z.payload?.taskId?c.jsx(gI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Bh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):J==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):J==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):z.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},z.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:X,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Wo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const z=T;R(null),te.agents.cancelProcessing(s,{itemId:z}).then(()=>{let re=0;const Z=()=>{re+=1,U(),re<8&&window.setTimeout(Z,750)};Z()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=Pt(["agent","common"]),t=Xh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(K2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Mr.navigate(Yt.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=_t.on("deliverable:created",()=>l()),d=_t.on("deliverable:updated",()=>l()),u=_t.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=tC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=yO[h.status]??yO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const _I=S.lazy(()=>Xv(()=>import("./index-DyYU0JDE.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),lg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Ev={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Av({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState(!0),[p,v]=S.useState(null),[b,g]=S.useState("overview"),O=r&&i?i:b,[m,x]=S.useState(""),[y,k]=S.useState(""),[C,P]=S.useState(!1),[_,T]=S.useState(!1),[R,L]=S.useState(""),[M,E]=S.useState(""),B=S.useRef(null),U=S.useRef(null),F=S.useRef(null),X=S.useRef(null),[ae,j]=S.useState(!1),[W,D]=S.useState(!1),[V,se]=S.useState(""),[fe,z]=S.useState(""),[re,Z]=S.useState(!1),[A,J]=S.useState([]),Y=S.useRef(null),oe=S.useCallback(async()=>{try{const qe=(await te.teams.list()).teams.find(He=>He.id===s);qe&&l(qe);const Ue=await te.teams.status(s);J(Ue.agents)}catch{}finally{d(!1)}},[s]),K=S.useCallback(async()=>{f(!0);try{const G=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(G.content)}catch{x("")}try{const G=await te.teams.getFile(s,"NORMS.md");k(G.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),oe(),K()},[s,oe,K]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const pe=async(G,qe)=>{j(!0);try{await te.teams.updateFile(s,G,qe),G==="ANNOUNCEMENT.md"?(x(qe),P(!1)):(k(qe),T(!1))}catch{}j(!1)},je=async()=>{V.trim()&&(await te.teams.update(s,{name:V.trim()}),D(!1),oe())},we=async()=>{await te.teams.update(s,{description:fe}),Z(!1),oe()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(BC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ye=o.members.find(G=>G.agentRole==="manager"),Qe=A.filter(G=>G.status!=="offline").length,Ee=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ee?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ee?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ye?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(mt=>mt.id===G.id),Ue=Ev[qe?.status??"offline"]??"bg-gray-500",He=G.type==="agent";return c.jsxs("div",{onClick:()=>He&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ue}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),He&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Nc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Nc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ye=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Qe," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:G}=await te.teams.getFilesMap(o.id),qe=o.members.filter(He=>He.type==="agent"),Ue={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:qe.map(He=>({name:He.name,roleName:He.role,role:He.agentRole??"worker",count:1,skills:[]}))}};await Fm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ue,files:G}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(G){v({title:"Hub",message:`Failed to publish: ${G}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:lg.map(G=>c.jsxs("button",{onClick:()=>g(G.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===G.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[G.icon," ",a(G.labelKey)]},G.key))})]}),c.jsxs("div",{className:`${ye?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ye?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(mt=>mt.id===G.id),Ue=Ev[qe?.status??"offline"]??"bg-gray-500",He=G.type==="agent";return c.jsxs("div",{onClick:()=>He&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ue}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),He&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Nc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Nc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Wo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Nc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d,loading:u}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:u&&!s.trim()?c.jsx(qv,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_I,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Mv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const kI=["chat","overview","deliverables"],CI=["chat","overview","announcements","norms","settings"];function PI(s,e){if(s==="chat")return e("page.chatTitle");if(ag.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=lg.find(i=>i.key===s);return r?e(r.labelKey):s}function TI(s){if(s==="chat")return"💬";const e=ag.find(r=>r.key===s);if(e)return e.icon;const t=lg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ra(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Dm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Er{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>Er.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Dm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Er.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Er.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(Er.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Dm(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Er.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<=Er.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Er.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>Er.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const it=Er.NEW_CHAT_ID;function QI(s){const e=S.useRef(new Er),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,L)=>{e.current.addStreamSession(R,L)&&d()},[d]),p=S.useCallback((R,L)=>{e.current.removeStreamSession(R,L)&&d()},[d]),v=S.useCallback((R,L)=>e.current.setActiveSession(R,L),[]),b=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=S.useCallback((R,L,M)=>{const E=e.current.updateMessages(R,L,M);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=S.useCallback((R,L,M)=>{e.current.updateMessages(R,L,M).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const B=e.current.getMessages(R);B&&e.current.currentConvKey===R&&r([...B])}))},[]),m=S.useCallback((R,L,M)=>{const E=e.current.appendActivity(R,L,M);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=S.useCallback(R=>e.current.getPhase(R),[]),y=S.useCallback(R=>e.current.beginLoad(R),[]),k=S.useCallback(R=>{e.current.beginStream(R)},[]),C=S.useCallback(R=>{e.current.endStream(R)},[]),P=S.useCallback((R,L)=>{e.current.abortStream(R,L)&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),_=S.useCallback((R,L)=>{e.current.resetConv(R,L),e.current.deleteBuffer(R)},[]),T=S.useCallback(async(R,L,M)=>{e.current.loadingSession=R,e.current.beginLoad(L);try{const E=await M(),B=e.current.applyLoadResult(L,R,E.messages);return B.displayChanged&&B.newMessages&&r(B.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===L&&e.current.getPhase(L)!=="streaming"&&(r([]),e.current.completeLoad(L)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:u,saveSessionToCache:(R,L)=>e.current.saveToCache(),restoreSessionFromCache:(R,L)=>{const M=e.current.restoreFromCache(R,L);return r(M??[]),M},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,L)=>{const M=e.current.updateMessages(R,()=>L);M.displayChanged&&M.newMessages&&r(M.newMessages)}}}function _f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function $I(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Ee=>{if(Ee)for(const[ye,G]of e.current)G===Ee&&e.current.delete(ye)},i=Ee=>{if(Ee)for(const[ye,G]of t.current)G===Ee&&t.current.delete(ye)},n=Ee=>{const ye=e.current.get(Ee);ye&&(ye.abort(),e.current.delete(Ee));const G=t.current.get(Ee);G&&(G.abort(),t.current.delete(Ee))},a=Ee=>{const ye=e.current.get(it);ye&&e.current.size===1&&(e.current.delete(it),e.current.set(Ee,ye))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:L,decrementSending:M,loadAndDisplay:E,sessionSwitchSeqRef:B,setSending:U,setActivities:F,setInput:X,setChatContext:ae,setPendingImages:j,setMentionDropdown:W,setChatReplyTo:D,setActiveSessionId:V,setStoredActiveSession:se,setOpenSessionTabs:fe,setSessions:z,setLoadingChat:re,setWindowBounds:Z,makeConvKey:A,makeDmChannel:J,addRecentMsgId:Y,resumeChatScrollFollow:oe,loadSessions:K}=s,{t:pe}=s,je=S.useCallback(async(Ee,ye)=>{const G=B.current,qe=g.current===ye&&(b(ye)?.length??0)===0;qe&&re(!0);try{const{count:Ue,hasMore:He,oldestCursor:mt}=await E(Ee,ye,async()=>{const xt=await te.sessions.getMessages(Ee,50);return{messages:aC(xt.messages.map(nh).filter(vt=>vt.sender!=="agent"||vt.text||vt.segments&&vt.segments.length>0||vt.isStreaming)),hasMore:xt.hasMore,oldestCursor:xt.messages[0]?new Date(xt.messages[0].createdAt).toISOString():null}});return Z(Ee,{hasMore:He,oldestCursor:mt}),Ue}finally{qe&&g.current===ye&&B.current===G&&re(!1)}},[E,b,B]),we=()=>{const Ee=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ee){const ye=_f(f.current.activeSessionId,it);ye.kind==="cancel"&&te.agents.cancelProcessing(Ee,ye.target).catch(()=>{})}n(f.current.activeSessionId??it),Ee&&f.current.activeSessionId&&f.current.activeSessionId!==it&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ye=S.useCallback(async(Ee,ye,G)=>{if(!Ee||!ye||ye===it||l.current.has(ye))return;let qe=null;try{const Ue=e.current.get(ye);if(Ue&&!Ue.signal.aborted&&T(G)?.has(ye)){g.current===G&&U(!0);return}const He=()=>{lC({liveSessions:T(G),sessionId:ye,placeholderId:it})&&(P(G,ye),g.current===G&&(U(!1),O(G,de=>ou(de),ye)))},mt=`${Ee}:${ye}`,xt=o.current.get(mt)??0;if(Date.now()-xt<1500)return;o.current.set(mt,Date.now());let bt;const vt=await te.sessions.streamStatus(Ee,ye);vt.messageId&&(bt=vt.messageId);const Pe=b(G)??[],Et=vt.status==="streaming",Ft=cC(Pe,{expectedMessageId:vt.messageId,allowCurrentTurnPartial:Et}),Es=!!vt.active&&(vt.status==="done"||vt.status==="error")&&!!Ft?.isStreaming;if(KO({aborted:!1,sawTerminal:Es,serverStatus:JO(vt.status)})==="finalize"){He();return}o.current.set(mt,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),qe=new AbortController,t.current.set(ye,qe),y(G),U(!0),_(G,ye);const yt=Ft&&!Ft.isError&&Ft.sender==="agent"?Pe.findIndex(de=>de.id===Ft.id):-1,Bt=yt>=0?Pe[yt]:void 0,dt=hC(vt);if(!Bt&&!dt){He();return}const Ze=Bt?Bt.id:dt;if(!Bt)O(G,de=>[...de,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ye);else{const de=(Bt.segments??[]).filter(De=>De.type==="tool").map(De=>De.status==="stopped"||De.status==="running"?{...De,status:"running"}:De);O(G,De=>De.map(ve=>ve.id===Ze?{...ve,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:ve),ye)}const Xt=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=tt>=0?tt:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,text:(Ve.text??"")+de,segments:SO(Ve.segments??[],de),isStreaming:!0},ve},ye))},ot=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=tt>=0?tt:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,segments:wO(Ve.segments??[],de),isStreaming:!0},ve},ye))},At=de=>{if(g.current===G&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(G,{...de,phase:de.phase,ts:Date.now()},ye),de.phase==="start"){const De=`${de.tool}_${Date.now()}`,ve=new Date().toISOString(),tt=ze=>{const Ve=[...ze];for(let ee=Ve.length-1;ee>=0;ee--){const Te=Ve[ee];if(Te.type==="tool"&&Te.tool===de.tool&&(Te.status==="running"||Te.status==="stopped"))return Ve[ee]={...Te,status:"running",args:de.arguments??Te.args},Ve}return Ve.push({type:"tool",key:De,tool:de.tool,status:"running",args:de.arguments,createdAt:ve}),Ve};O(G,ze=>{const Ve=[...ze],ee=Ze?Ve.findIndex(_e=>_e.id===Ze):-1;if(ee<0)return ze;const Te=tt(Ve[ee].segments??[]),Se=Ve[ee].committedSegments,xe=Se&&tt(Se);return Ve[ee]={...Ve[ee],segments:Te,committedSegments:xe,isStreaming:!0},Ve},ye)}else if(de.phase==="end"){const De=new Date().toISOString(),ve=tt=>{const ze=[...tt];for(let Ve=ze.length-1;Ve>=0;Ve--){const ee=ze[Ve];if(ee.type==="tool"&&ee.tool===de.tool&&(ee.status==="running"||ee.status==="stopped")){ze[Ve]={...ee,status:de.success===!1?"error":"done",args:de.arguments??ee.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:De};break}}return ze};O(G,tt=>{const ze=[...tt],Ve=Ze?ze.findIndex(xe=>xe.id===Ze):-1;if(Ve<0)return tt;const ee=ve(ze[Ve].segments??[]),Te=ze[Ve].committedSegments,Se=Te&&ve(Te);return ze[Ve]={...ze[Ve],segments:ee,committedSegments:Se,isStreaming:!0},ze},ye)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const De=ve=>{const tt=[...ve];for(let ze=tt.length-1;ze>=0;ze--){const Ve=tt[ze];if(Ve.type==="tool"&&(Ve.tool==="spawn_subagent"||Ve.tool==="spawn_subagents")&&(Ve.status==="running"||Ve.status==="stopped")){tt[ze]={...Ve,status:"running",subagentLogs:_O(Ve.subagentLogs,de.subagentEvent)};break}}return tt};m(G,ve=>{const tt=[...ve],ze=Ze?tt.findIndex(Se=>Se.id===Ze):-1;if(ze<0)return ve;const Ve=De(tt[ze].segments??[]),ee=tt[ze].committedSegments,Te=ee&&De(ee);return tt[ze]={...tt[ze],segments:Ve,committedSegments:Te,isStreaming:!0},tt},ye)}}},ds=de=>{g.current===G&&(u.current=Date.now(),O(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(Ve=>Ve.id===Ze):-1;if(tt<0)return De;const ze=[...ve[tt].committedSegments??[]];if(de.type==="thinking_commit")ze.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")ze.push({type:"text",content:de.content,createdAt:de.createdAt});else return De;return ve[tt]={...ve[tt],committedSegments:ze,isStreaming:!0},ve},ye))},he=de=>{if(g.current!==G)return;u.current=Date.now();const De=(de.segments??[]).map((ve,tt)=>ve.type==="tool"?{type:"tool",key:`${ve.tool}_${tt}`,tool:ve.tool??"tool",status:ve.status==="error"?"error":ve.status==="running"||ve.status==="stopped"?"running":"done",args:ve.arguments,result:ve.result,error:ve.error,durationMs:ve.durationMs,createdAt:ve.createdAt,...ve.subagentLogs?.length?{subagentLogs:ve.subagentLogs}:{}}:{type:"text",content:ve.content??"",thinking:ve.thinking,createdAt:ve.createdAt});O(G,ve=>{const tt=[...ve],ze=Ze?tt.findIndex(Ve=>Ve.id===Ze):-1;return ze<0?ve:(tt[ze]={...tt[ze],text:de.content||tt[ze].text,segments:De,committedSegments:De,isStreaming:!0,isStopped:!1},tt)},ye);for(const ve of De)ve.type==="tool"&&x(G,{tool:ve.tool,phase:ve.status==="running"||ve.status==="stopped"?"start":"end",success:ve.status!=="error",arguments:ve.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,ts:Date.now()},ye)},ce=8;let $e=null;const Xe=de=>{g.current===G&&O(G,De=>{const ve=De.map((ze,Ve)=>({m:ze,j:Ve})).reverse().find(ze=>ze.m.sender==="agent"&&ze.m.isStreaming)?.j??-1;if(ve<0||De[ve].reconnecting===de)return De;const tt=[...De];return tt[ve]={...tt[ve],reconnecting:de},tt},ye)};for(let de=1;de<=ce;de++){if(qe.signal.aborted)return;try{$e=await te.sessions.reattachStream(Ee,ye,{onChunk:Xt,onThinking:ot,onActivity:At,onCommit:ds,onSnapshot:he},qe.signal,0)}catch(ve){if(qe.signal.aborted)throw ve;$e=null}if(!$e||!$e.attached){$e=null;break}if($e.terminal)break;Xe(!0);const De=await te.sessions.streamStatus(Ee,ye).catch(()=>null);if(De?.messageId&&(bt=De.messageId),!De||!De.active||De.status==="not_found"||De.status==="idle"){Xe(!1),$e=null;break}await new Promise(ve=>setTimeout(ve,Math.min(800*de,4e3))),Xe(!1)}if(!$e){k(G),P(G,ye),g.current===G&&(U(!1),bt&&Ze&&O(G,de=>Sa(de,Ze,bt),ye),je(ye,G).catch(()=>{}).finally(()=>{O(G,de=>ou(de,"done"),ye)})),i(qe);return}if(g.current===G){let de;O(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(Te=>Te.id===Ze):-1,ze=tt>=0?tt:ve.map((Te,Se)=>({m:Te,j:Se})).reverse().find(Te=>Te.m.sender==="agent"&&Te.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];if(!Ve.isStreaming)return De;de=Ve.id;const ee=$e.segments?.length?kO($e.segments,Ve.segments):void 0;return ve[ze]={...Ve,text:$e.content||Ve.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ee?{segments:ee,committedSegments:ee}:{}},ve},ye),de&&O(G,De=>Sa(De,de,$e.messageId),ye),U(!1)}k(G),P(G,ye),i(qe)}catch(Ue){const He=qe?[...t.current.values()].includes(qe):!1;i(qe),k(G);const mt=l.current.has(ye);if(mt&&P(G,ye),g.current===G&&(U(!1),He&&mt&&O(G,xt=>ou(xt),ye)),Ue instanceof Error&&Ue.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Qe=S.useCallback(async(Ee,ye)=>{const G=f.current,qe=!Ee&&G.chatContext.length>0?G.chatContext.map(rt=>rt.content).join(`
75
+ `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Mr.navigate(Yt.TEAM,{agentId:s,prefillMessage:j})},L=async F=>{if(y?.file===F){k(null);return}try{const X=await te.agents.roleDiff(s,F);X.agentContent!=null&&X.templateContent!=null&&k({file:F,agent:X.agentContent,template:X.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const M={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=F=>{const X=M[F];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):F},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(F=>F.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[B&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(F=>F.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(fs,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(F=>{const X=T.some(ae=>ae.file===F.name);return c.jsxs("button",{onClick:()=>P(F.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===F.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[F.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},F.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[U&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-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(oI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(cI,{content:t.find(F=>F.name===a)?.content??"",editContent:l,setEditContent:F=>{h(F),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Wh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function cI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(sI,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function hI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function dI({tools:s}){const{t:e}=Pt(["agent","common"]),t=YD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(fs,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=nC(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=hI(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(oC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function uI({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(fs,{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(Wh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function fI({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(dI,{tools:s}):c.jsx(uI,{agent:e})]})}function mI({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,k]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(M=>{r(M),h(M.recentDailyLogs??""),u(M.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},_=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),R=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:L.map(M=>c.jsx("button",{onClick:()=>o(M.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===M.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:M.label},M.key))}),a==="entries"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Wh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((M,E)=>{const B=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(B?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${M.type==="fact"?"bg-blue-500/15 text-blue-600":M.type==="task"?"bg-green-500/15 text-green-600":M.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:M.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:M.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${M.importance>=7?"bg-red-500/15 text-red-500":M.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",M.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(M.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:M.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",M.type]}),M.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",M.importance]}),c.jsx("span",{children:new Date(M.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Wh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(M=>{const E=g===M.id,B=async()=>{if(E){O(null),x([]);return}O(M.id),k(!0);try{const U=await te.agents.getMemorySession(s,M.id);x(U.messages)}catch{x([])}k(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:M.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[M.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(M.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const U=new Map;for(const F of m)F.role==="tool"&&F.toolCallId&&U.set(F.toolCallId,F.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(F=>F.role!=="tool").map((F,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(F.role==="user"||F.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${F.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${F.role}`,{defaultValue:F.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[F.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.toolCalls&&F.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:F.toolCalls.map(ae=>{let j;try{j=JSON.parse(ae.arguments)}catch{}const W={tool:ae.name,status:"done",args:j,result:U.get(ae.id)};return c.jsx(sC,{entry:{type:"tool",info:W}},ae.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:M=>h(M.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(fs,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:R?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:M=>u(M.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function pI({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>_t.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(fs,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ks,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(OI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(fs,{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(fs,{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(fs,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx($o,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(fs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Bh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(fs,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function gI({taskId:s,isLive:e}){const{t}=Pt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0);if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(d=>{i(d.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const d=_t.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),u=_t.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{d(),u()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(d=>iC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Bh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Pt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0);if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?_t.on("agent:activity_log",d=>{const u=d.payload;if(u.agentId!==s||u.activityId!==e)return;const f={seq:u.seq,type:u.type,content:u.content,metadata:u.metadata,createdAt:u.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>rC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:l,isStreaming:t})})}function fs({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Ks({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const kv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Cv=5,Pv=1440;function OI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Pt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<Cv||m>Pv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=kv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),kv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Cv,max:Pv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Wh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Tv(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const Qv={0:"0",1:"1",2:"2",3:"3",4:"4"},$v={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},xI={pick:"bg-brand-500/20 text-brand-500",continue:"bg-gray-500/20 text-gray-500",preempt:"bg-amber-500/20 text-amber-500",merge:"bg-blue-500/20 text-blue-500",defer:"bg-purple-500/20 text-purple-500",delegate:"bg-green-500/20 text-green-500",drop:"bg-red-500/20 text-red-500"},bI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},vI=["all","interaction","task","notification","system"],yI={completed:"bg-green-500",processing:"bg-blue-400 animate-pulse",deferred:"bg-purple-400",merged:"bg-brand-400",queued:"bg-amber-400",dropped:"bg-red-500"},SI={pending:"text-gray-400",assigned:"text-blue-400",in_progress:"text-brand-400",completed:"text-green-400",failed:"text-red-400",cancelled:"text-gray-500",review:"text-amber-400",approved:"text-green-500",rejected:"text-red-500",draft:"text-gray-400"};function wf(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function jv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Lm(d,e),p=Lm(u,e),v=SI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=wf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function wI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Pt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[k,C]=S.useState(!1),[P,_]=S.useState(!0),[T,R]=S.useState(null),L=50,M=3,[E,B]=S.useState(null),U=S.useCallback(async(z=!0)=>{z&&d(!0);try{const re=u==="all"?void 0:u,Z=p==="all"?void 0:p,[A,J]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:re,status:Z})]);a(A),l(J),_((J.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),F=S.useCallback(async z=>{B(z);try{await te.agents.dropMailboxItem(s,z,"operator"),await U()}catch{}finally{B(null)}},[s,U]),X=S.useCallback(async()=>{if(!o)return;const z=u==="all"?void 0:u,re=p==="all"?void 0:p;try{const Z=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:re});l(A=>A?{...A,history:[...A.history,...Z.history]}:Z),_((Z.history?.length??0)>=L)}catch{}},[s,o,u,p]),ae=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await U()},[s,U]);S.useEffect(()=>{g(e??null),m(e??null),U()},[U,e]);const j=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(re=>re.id===O)){j.current=!1;const re=document.getElementById(`mbx-${O}`);if(re){setTimeout(()=>re.scrollIntoView({behavior:"smooth",block:"center"}),100);const Z=setTimeout(()=>m(null),3e3);return()=>clearTimeout(Z)}}else P&&!j.current&&(j.current=!0,(async()=>{let re=o?.history??[],Z=P;for(;Z;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:re.length}),J=[...re,...A.history];re=J,Z=(A.history?.length??0)>=L;const Y=A.history.some(oe=>oe.id===O);if(l(oe=>oe?{...oe,history:J}:A),_(Z),Y||!Z)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const re=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},Z=[_t.on("agent:mailbox",re),_t.on("agent:decision",re),_t.on("agent:attention",re),_t.on("agent:focus",re),_t.on("agent:update",re),_t.on("agent:triage",re)];return()=>{z&&clearTimeout(z),Z.forEach(A=>A())}},[s,U]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const W=n?.mailboxDepth??n?.queuedItems?.length??0,D=zh(t).running,V=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=V==="idle"&&o?.history?.some(z=>z.status==="processing"),fe=(n?.attentionState??"idle")==="idle"&&W>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[D?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${bI[V]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${V}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),D?n?.currentFocus?(()=>{const z=jv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Lc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:z.title}),z.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:z.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():fe?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:W,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:W})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{U()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),D&&se&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ae()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const z=n.queuedItems,re=z.length>M,Z=re&&!x?z.slice(0,M):z,A=z.reduce((J,Y)=>(J[Y.sourceType]=(J[Y.sourceType]??0)+1,J),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:z.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([J,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Lc(J)," ",Y]},J))})]}),c.jsxs("div",{className:"space-y-1",children:[Z.map((J,Y)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:Y+1}),c.jsx("span",{className:"text-sm",children:Lc(J.sourceType)}),c.jsx("span",{className:`text-[10px] ${$v[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[J.priority]??J.priority}`,{defaultValue:`P${J.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:J.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(J.queuedAt).toLocaleTimeString()})]},J.id)),re&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:z.length-M})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const z=eI(n.notebook,k);return c.jsx("section",{className:"bg-surface-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:j_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(re=>{const Z=tI(re.updatedAt),A=i(`agent:profilePage.relative.${Z.unit==="seconds"?"secondsAgo":Z.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:Z.count,hours:Z.count}),J=re.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-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:re.key}),c.jsxs("span",{className:`text-[10px] ${J}`,children:["[",re.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:re.text.length>500?re.text.slice(0,500)+"…":re.text})]},re.key)}),z.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:z.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-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] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Bh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const re=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,Z=J2(n.lastTriage);return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${re?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!re,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-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)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${Z.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-3 text-fg-tertiary"}`,children:Z.isBatch?i("agent:profilePage.mind.batchSize",{count:Z.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:vI.map(z=>{const re=o?.sourceTypeCounts,Z=z==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?(UD[z]??[]).reduce((A,J)=>A+(re[J]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(z),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===z?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[i(`agent:profilePage.mind.categoryFilters.${z}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(z=>{const re=o?.statusCounts,Z=z.key==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?.[z.key];return c.jsxs("button",{onClick:()=>v(z.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===z.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[z.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z.dot}`}),i(`agent:profilePage.mind.statusFilters.${z.key}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(z=>{const re=b===z.id,Z=Lc(z.sourceType),A=jv(z,i),J=KD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,oe=z.metadata?.senderRole,K=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${K?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>g(re?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:re?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${J==="stale"?"bg-amber-400/70":yI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:Z}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${re?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${$v[z.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[z.priority]??z.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${re?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(z.queuedAt).toLocaleString()}),z.completedAt&&c.jsxs("span",{children:["→ ",new Date(z.completedAt).toLocaleTimeString()]}),z.activity&&c.jsxs(c.Fragment,{children:[z.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Nm(z.activity.totalTokens)})}),z.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:z.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:z.sourceType}),r&&GD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:pe=>{pe.stopPropagation(),R(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),re&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[Y&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Y}),oe&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",oe,")"]})]}),z.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(z.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:z.payload.content}),z.decisions&&z.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:z.decisions.map(pe=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${xI[pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:pe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:pe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(pe.createdAt).toLocaleTimeString()})]},pe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===z.id,onClick:()=>{F(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),z.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:z.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${z.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:z.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),z.activity.type==="task"&&z.payload?.taskId?c.jsx(gI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Bh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):J==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):J==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):z.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},z.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:X,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Wo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const z=T;R(null),te.agents.cancelProcessing(s,{itemId:z}).then(()=>{let re=0;const Z=()=>{re+=1,U(),re<8&&window.setTimeout(Z,750)};Z()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=Pt(["agent","common"]),t=Xh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(K2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Mr.navigate(Yt.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=_t.on("deliverable:created",()=>l()),d=_t.on("deliverable:updated",()=>l()),u=_t.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=tC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=yO[h.status]??yO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const _I=S.lazy(()=>Xv(()=>import("./index-Ci5bUF3m.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),lg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Ev={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Av({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState(!0),[p,v]=S.useState(null),[b,g]=S.useState("overview"),O=r&&i?i:b,[m,x]=S.useState(""),[y,k]=S.useState(""),[C,P]=S.useState(!1),[_,T]=S.useState(!1),[R,L]=S.useState(""),[M,E]=S.useState(""),B=S.useRef(null),U=S.useRef(null),F=S.useRef(null),X=S.useRef(null),[ae,j]=S.useState(!1),[W,D]=S.useState(!1),[V,se]=S.useState(""),[fe,z]=S.useState(""),[re,Z]=S.useState(!1),[A,J]=S.useState([]),Y=S.useRef(null),oe=S.useCallback(async()=>{try{const qe=(await te.teams.list()).teams.find(He=>He.id===s);qe&&l(qe);const Ue=await te.teams.status(s);J(Ue.agents)}catch{}finally{d(!1)}},[s]),K=S.useCallback(async()=>{f(!0);try{const G=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(G.content)}catch{x("")}try{const G=await te.teams.getFile(s,"NORMS.md");k(G.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),oe(),K()},[s,oe,K]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const pe=async(G,qe)=>{j(!0);try{await te.teams.updateFile(s,G,qe),G==="ANNOUNCEMENT.md"?(x(qe),P(!1)):(k(qe),T(!1))}catch{}j(!1)},je=async()=>{V.trim()&&(await te.teams.update(s,{name:V.trim()}),D(!1),oe())},we=async()=>{await te.teams.update(s,{description:fe}),Z(!1),oe()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(BC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ye=o.members.find(G=>G.agentRole==="manager"),Qe=A.filter(G=>G.status!=="offline").length,Ee=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ee?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ee?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ye?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(mt=>mt.id===G.id),Ue=Ev[qe?.status??"offline"]??"bg-gray-500",He=G.type==="agent";return c.jsxs("div",{onClick:()=>He&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ue}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),He&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Nc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Nc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ye=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Qe," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:G}=await te.teams.getFilesMap(o.id),qe=o.members.filter(He=>He.type==="agent"),Ue={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:qe.map(He=>({name:He.name,roleName:He.role,role:He.agentRole??"worker",count:1,skills:[]}))}};await Fm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ue,files:G}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(G){v({title:"Hub",message:`Failed to publish: ${G}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:lg.map(G=>c.jsxs("button",{onClick:()=>g(G.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===G.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[G.icon," ",a(G.labelKey)]},G.key))})]}),c.jsxs("div",{className:`${ye?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ye?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(mt=>mt.id===G.id),Ue=Ev[qe?.status??"offline"]??"bg-gray-500",He=G.type==="agent";return c.jsxs("div",{onClick:()=>He&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ue}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),He&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Nc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Nc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Wo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Nc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d,loading:u}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:u&&!s.trim()?c.jsx(qv,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_I,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Mv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const kI=["chat","overview","deliverables"],CI=["chat","overview","announcements","norms","settings"];function PI(s,e){if(s==="chat")return e("page.chatTitle");if(ag.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=lg.find(i=>i.key===s);return r?e(r.labelKey):s}function TI(s){if(s==="chat")return"💬";const e=ag.find(r=>r.key===s);if(e)return e.icon;const t=lg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ra(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Dm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Er{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>Er.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Dm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Er.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Er.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(Er.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Dm(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Er.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<=Er.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Er.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>Er.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const it=Er.NEW_CHAT_ID;function QI(s){const e=S.useRef(new Er),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,L)=>{e.current.addStreamSession(R,L)&&d()},[d]),p=S.useCallback((R,L)=>{e.current.removeStreamSession(R,L)&&d()},[d]),v=S.useCallback((R,L)=>e.current.setActiveSession(R,L),[]),b=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=S.useCallback((R,L,M)=>{const E=e.current.updateMessages(R,L,M);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=S.useCallback((R,L,M)=>{e.current.updateMessages(R,L,M).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const B=e.current.getMessages(R);B&&e.current.currentConvKey===R&&r([...B])}))},[]),m=S.useCallback((R,L,M)=>{const E=e.current.appendActivity(R,L,M);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=S.useCallback(R=>e.current.getPhase(R),[]),y=S.useCallback(R=>e.current.beginLoad(R),[]),k=S.useCallback(R=>{e.current.beginStream(R)},[]),C=S.useCallback(R=>{e.current.endStream(R)},[]),P=S.useCallback((R,L)=>{e.current.abortStream(R,L)&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),_=S.useCallback((R,L)=>{e.current.resetConv(R,L),e.current.deleteBuffer(R)},[]),T=S.useCallback(async(R,L,M)=>{e.current.loadingSession=R,e.current.beginLoad(L);try{const E=await M(),B=e.current.applyLoadResult(L,R,E.messages);return B.displayChanged&&B.newMessages&&r(B.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===L&&e.current.getPhase(L)!=="streaming"&&(r([]),e.current.completeLoad(L)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:u,saveSessionToCache:(R,L)=>e.current.saveToCache(),restoreSessionFromCache:(R,L)=>{const M=e.current.restoreFromCache(R,L);return r(M??[]),M},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,L)=>{const M=e.current.updateMessages(R,()=>L);M.displayChanged&&M.newMessages&&r(M.newMessages)}}}function _f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function $I(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Ee=>{if(Ee)for(const[ye,G]of e.current)G===Ee&&e.current.delete(ye)},i=Ee=>{if(Ee)for(const[ye,G]of t.current)G===Ee&&t.current.delete(ye)},n=Ee=>{const ye=e.current.get(Ee);ye&&(ye.abort(),e.current.delete(Ee));const G=t.current.get(Ee);G&&(G.abort(),t.current.delete(Ee))},a=Ee=>{const ye=e.current.get(it);ye&&e.current.size===1&&(e.current.delete(it),e.current.set(Ee,ye))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:L,decrementSending:M,loadAndDisplay:E,sessionSwitchSeqRef:B,setSending:U,setActivities:F,setInput:X,setChatContext:ae,setPendingImages:j,setMentionDropdown:W,setChatReplyTo:D,setActiveSessionId:V,setStoredActiveSession:se,setOpenSessionTabs:fe,setSessions:z,setLoadingChat:re,setWindowBounds:Z,makeConvKey:A,makeDmChannel:J,addRecentMsgId:Y,resumeChatScrollFollow:oe,loadSessions:K}=s,{t:pe}=s,je=S.useCallback(async(Ee,ye)=>{const G=B.current,qe=g.current===ye&&(b(ye)?.length??0)===0;qe&&re(!0);try{const{count:Ue,hasMore:He,oldestCursor:mt}=await E(Ee,ye,async()=>{const xt=await te.sessions.getMessages(Ee,50);return{messages:aC(xt.messages.map(nh).filter(vt=>vt.sender!=="agent"||vt.text||vt.segments&&vt.segments.length>0||vt.isStreaming)),hasMore:xt.hasMore,oldestCursor:xt.messages[0]?new Date(xt.messages[0].createdAt).toISOString():null}});return Z(Ee,{hasMore:He,oldestCursor:mt}),Ue}finally{qe&&g.current===ye&&B.current===G&&re(!1)}},[E,b,B]),we=()=>{const Ee=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ee){const ye=_f(f.current.activeSessionId,it);ye.kind==="cancel"&&te.agents.cancelProcessing(Ee,ye.target).catch(()=>{})}n(f.current.activeSessionId??it),Ee&&f.current.activeSessionId&&f.current.activeSessionId!==it&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ye=S.useCallback(async(Ee,ye,G)=>{if(!Ee||!ye||ye===it||l.current.has(ye))return;let qe=null;try{const Ue=e.current.get(ye);if(Ue&&!Ue.signal.aborted&&T(G)?.has(ye)){g.current===G&&U(!0);return}const He=()=>{lC({liveSessions:T(G),sessionId:ye,placeholderId:it})&&(P(G,ye),g.current===G&&(U(!1),O(G,de=>ou(de),ye)))},mt=`${Ee}:${ye}`,xt=o.current.get(mt)??0;if(Date.now()-xt<1500)return;o.current.set(mt,Date.now());let bt;const vt=await te.sessions.streamStatus(Ee,ye);vt.messageId&&(bt=vt.messageId);const Pe=b(G)??[],Et=vt.status==="streaming",Ft=cC(Pe,{expectedMessageId:vt.messageId,allowCurrentTurnPartial:Et}),Es=!!vt.active&&(vt.status==="done"||vt.status==="error")&&!!Ft?.isStreaming;if(KO({aborted:!1,sawTerminal:Es,serverStatus:JO(vt.status)})==="finalize"){He();return}o.current.set(mt,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),qe=new AbortController,t.current.set(ye,qe),y(G),U(!0),_(G,ye);const yt=Ft&&!Ft.isError&&Ft.sender==="agent"?Pe.findIndex(de=>de.id===Ft.id):-1,Bt=yt>=0?Pe[yt]:void 0,dt=hC(vt);if(!Bt&&!dt){He();return}const Ze=Bt?Bt.id:dt;if(!Bt)O(G,de=>[...de,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ye);else{const de=(Bt.segments??[]).filter(De=>De.type==="tool").map(De=>De.status==="stopped"||De.status==="running"?{...De,status:"running"}:De);O(G,De=>De.map(ve=>ve.id===Ze?{...ve,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:ve),ye)}const Xt=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=tt>=0?tt:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,text:(Ve.text??"")+de,segments:SO(Ve.segments??[],de),isStreaming:!0},ve},ye))},ot=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=tt>=0?tt:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,segments:wO(Ve.segments??[],de),isStreaming:!0},ve},ye))},At=de=>{if(g.current===G&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(G,{...de,phase:de.phase,ts:Date.now()},ye),de.phase==="start"){const De=`${de.tool}_${Date.now()}`,ve=new Date().toISOString(),tt=ze=>{const Ve=[...ze];for(let ee=Ve.length-1;ee>=0;ee--){const Te=Ve[ee];if(Te.type==="tool"&&Te.tool===de.tool&&(Te.status==="running"||Te.status==="stopped"))return Ve[ee]={...Te,status:"running",args:de.arguments??Te.args},Ve}return Ve.push({type:"tool",key:De,tool:de.tool,status:"running",args:de.arguments,createdAt:ve}),Ve};O(G,ze=>{const Ve=[...ze],ee=Ze?Ve.findIndex(_e=>_e.id===Ze):-1;if(ee<0)return ze;const Te=tt(Ve[ee].segments??[]),Se=Ve[ee].committedSegments,xe=Se&&tt(Se);return Ve[ee]={...Ve[ee],segments:Te,committedSegments:xe,isStreaming:!0},Ve},ye)}else if(de.phase==="end"){const De=new Date().toISOString(),ve=tt=>{const ze=[...tt];for(let Ve=ze.length-1;Ve>=0;Ve--){const ee=ze[Ve];if(ee.type==="tool"&&ee.tool===de.tool&&(ee.status==="running"||ee.status==="stopped")){ze[Ve]={...ee,status:de.success===!1?"error":"done",args:de.arguments??ee.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:De};break}}return ze};O(G,tt=>{const ze=[...tt],Ve=Ze?ze.findIndex(xe=>xe.id===Ze):-1;if(Ve<0)return tt;const ee=ve(ze[Ve].segments??[]),Te=ze[Ve].committedSegments,Se=Te&&ve(Te);return ze[Ve]={...ze[Ve],segments:ee,committedSegments:Se,isStreaming:!0},ze},ye)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const De=ve=>{const tt=[...ve];for(let ze=tt.length-1;ze>=0;ze--){const Ve=tt[ze];if(Ve.type==="tool"&&(Ve.tool==="spawn_subagent"||Ve.tool==="spawn_subagents")&&(Ve.status==="running"||Ve.status==="stopped")){tt[ze]={...Ve,status:"running",subagentLogs:_O(Ve.subagentLogs,de.subagentEvent)};break}}return tt};m(G,ve=>{const tt=[...ve],ze=Ze?tt.findIndex(Se=>Se.id===Ze):-1;if(ze<0)return ve;const Ve=De(tt[ze].segments??[]),ee=tt[ze].committedSegments,Te=ee&&De(ee);return tt[ze]={...tt[ze],segments:Ve,committedSegments:Te,isStreaming:!0},tt},ye)}}},ds=de=>{g.current===G&&(u.current=Date.now(),O(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(Ve=>Ve.id===Ze):-1;if(tt<0)return De;const ze=[...ve[tt].committedSegments??[]];if(de.type==="thinking_commit")ze.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")ze.push({type:"text",content:de.content,createdAt:de.createdAt});else return De;return ve[tt]={...ve[tt],committedSegments:ze,isStreaming:!0},ve},ye))},he=de=>{if(g.current!==G)return;u.current=Date.now();const De=(de.segments??[]).map((ve,tt)=>ve.type==="tool"?{type:"tool",key:`${ve.tool}_${tt}`,tool:ve.tool??"tool",status:ve.status==="error"?"error":ve.status==="running"||ve.status==="stopped"?"running":"done",args:ve.arguments,result:ve.result,error:ve.error,durationMs:ve.durationMs,createdAt:ve.createdAt,...ve.subagentLogs?.length?{subagentLogs:ve.subagentLogs}:{}}:{type:"text",content:ve.content??"",thinking:ve.thinking,createdAt:ve.createdAt});O(G,ve=>{const tt=[...ve],ze=Ze?tt.findIndex(Ve=>Ve.id===Ze):-1;return ze<0?ve:(tt[ze]={...tt[ze],text:de.content||tt[ze].text,segments:De,committedSegments:De,isStreaming:!0,isStopped:!1},tt)},ye);for(const ve of De)ve.type==="tool"&&x(G,{tool:ve.tool,phase:ve.status==="running"||ve.status==="stopped"?"start":"end",success:ve.status!=="error",arguments:ve.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,ts:Date.now()},ye)},ce=8;let $e=null;const Xe=de=>{g.current===G&&O(G,De=>{const ve=De.map((ze,Ve)=>({m:ze,j:Ve})).reverse().find(ze=>ze.m.sender==="agent"&&ze.m.isStreaming)?.j??-1;if(ve<0||De[ve].reconnecting===de)return De;const tt=[...De];return tt[ve]={...tt[ve],reconnecting:de},tt},ye)};for(let de=1;de<=ce;de++){if(qe.signal.aborted)return;try{$e=await te.sessions.reattachStream(Ee,ye,{onChunk:Xt,onThinking:ot,onActivity:At,onCommit:ds,onSnapshot:he},qe.signal,0)}catch(ve){if(qe.signal.aborted)throw ve;$e=null}if(!$e||!$e.attached){$e=null;break}if($e.terminal)break;Xe(!0);const De=await te.sessions.streamStatus(Ee,ye).catch(()=>null);if(De?.messageId&&(bt=De.messageId),!De||!De.active||De.status==="not_found"||De.status==="idle"){Xe(!1),$e=null;break}await new Promise(ve=>setTimeout(ve,Math.min(800*de,4e3))),Xe(!1)}if(!$e){k(G),P(G,ye),g.current===G&&(U(!1),bt&&Ze&&O(G,de=>Sa(de,Ze,bt),ye),je(ye,G).catch(()=>{}).finally(()=>{O(G,de=>ou(de,"done"),ye)})),i(qe);return}if(g.current===G){let de;O(G,De=>{const ve=[...De],tt=Ze?ve.findIndex(Te=>Te.id===Ze):-1,ze=tt>=0?tt:ve.map((Te,Se)=>({m:Te,j:Se})).reverse().find(Te=>Te.m.sender==="agent"&&Te.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];if(!Ve.isStreaming)return De;de=Ve.id;const ee=$e.segments?.length?kO($e.segments,Ve.segments):void 0;return ve[ze]={...Ve,text:$e.content||Ve.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ee?{segments:ee,committedSegments:ee}:{}},ve},ye),de&&O(G,De=>Sa(De,de,$e.messageId),ye),U(!1)}k(G),P(G,ye),i(qe)}catch(Ue){const He=qe?[...t.current.values()].includes(qe):!1;i(qe),k(G);const mt=l.current.has(ye);if(mt&&P(G,ye),g.current===G&&(U(!1),He&&mt&&O(G,xt=>ou(xt),ye)),Ue instanceof Error&&Ue.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Qe=S.useCallback(async(Ee,ye)=>{const G=f.current,qe=!Ee&&G.chatContext.length>0?G.chatContext.map(rt=>rt.content).join(`
76
76
 
77
77
  `)+`
78
78