@markus-global/cli 0.12.0-rc.0 → 0.12.0-rc.1

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 (66) hide show
  1. package/dist/markus.mjs +9 -8
  2. package/dist/web-ui/assets/{AsyncState-BebkDWbq.js → AsyncState-Brx503Qq.js} +1 -1
  3. package/dist/web-ui/assets/{CommentInput-BRZWIC3U.js → CommentInput-CyyImwaF.js} +1 -1
  4. package/dist/web-ui/assets/{ContentRenderer-PGP8H_Zz.js → ContentRenderer-CpiisvVQ.js} +2 -2
  5. package/dist/web-ui/assets/{DeliverableShareModal-CcigVYGz.js → DeliverableShareModal-BbvcR0LN.js} +1 -1
  6. package/dist/web-ui/assets/{Deliverables-CQwXaCA4.js → Deliverables-DIeYy6k7.js} +1 -1
  7. package/dist/web-ui/assets/{Notifications-BvHJCIRG.js → Notifications-BoPgYIh8.js} +1 -1
  8. package/dist/web-ui/assets/{Search-BA-aXh7i.js → Search-Bc44e8vT.js} +1 -1
  9. package/dist/web-ui/assets/{SendToChat-CAfyKhpq.js → SendToChat-BHNwDw6Q.js} +1 -1
  10. package/dist/web-ui/assets/{Settings-icFp6tNI.js → Settings-5tk3XjBZ.js} +1 -1
  11. package/dist/web-ui/assets/{Store-DKwOcmMu.js → Store-CMxzEtXt.js} +1 -1
  12. package/dist/web-ui/assets/{Switch-C7lFnHA7.js → Switch-C1h7-ixU.js} +1 -1
  13. package/dist/web-ui/assets/{Team-DyqXLZ-X.js → Team-Dcl-5Zvh.js} +4 -4
  14. package/dist/web-ui/assets/{Work-BXGrda4S.js → Work-Dj9tQYXg.js} +1 -1
  15. package/dist/web-ui/assets/{arc-Dnk6N-Zc.js → arc-BA1zZ3ag.js} +1 -1
  16. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CV8JIXXD.js → architectureDiagram-3BPJPVTR-DTUETQs3.js} +1 -1
  17. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-D9pKmrXH.js → blockDiagram-GPEHLZMM-D5dvIq_3.js} +1 -1
  18. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-Q26HvIpY.js → c4Diagram-AAUBKEIU-CBurhkOF.js} +1 -1
  19. package/dist/web-ui/assets/channel-CYxqacYz.js +1 -0
  20. package/dist/web-ui/assets/{chunk-2J33WTMH-BSjFVwnx.js → chunk-2J33WTMH-JDr6ZP1p.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-4BX2VUAB-BZXv4MQp.js → chunk-4BX2VUAB-CsXt6Gd5.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-55IACEB6-CeKd3oeJ.js → chunk-55IACEB6-BPhC3YgG.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-727SXJPM-DP1tSQo5.js → chunk-727SXJPM-BgceLEQx.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-AQP2D5EJ-DqEncn7j.js → chunk-AQP2D5EJ-Bq58a84v.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-FMBD7UC4-tuDUJ9Xx.js → chunk-FMBD7UC4-DyMa3olF.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-ND2GUHAM-DoC8aLWB.js → chunk-ND2GUHAM-BsgTeDYu.js} +1 -1
  27. package/dist/web-ui/assets/{chunk-QZHKN3VN-74zpvcgs.js → chunk-QZHKN3VN-BQpJPCpr.js} +1 -1
  28. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-mygctjMz.js +1 -0
  29. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-mygctjMz.js +1 -0
  30. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DjYUalC1.js → cose-bilkent-S5V4N54A-BCbssvKI.js} +1 -1
  31. package/dist/web-ui/assets/{dagre-BM42HDAG-oSewacE8.js → dagre-BM42HDAG-CT9IdAY4.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-2AECGRRQ-C1fiWe46.js → diagram-2AECGRRQ-x2pwUpLt.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-5GNKFQAL-9G_q6hCa.js → diagram-5GNKFQAL-d9_JOrSK.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-KO2AKTUF-CSm-lJp-.js → diagram-KO2AKTUF-CAVFWSkN.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-LMA3HP47-BTAORcHx.js → diagram-LMA3HP47-DQEHXvkq.js} +1 -1
  36. package/dist/web-ui/assets/{diagram-OG6HWLK6-DbcCkDfo.js → diagram-OG6HWLK6-BW62W4O-.js} +1 -1
  37. package/dist/web-ui/assets/{docx-preview-DjqdA44x.js → docx-preview-pqFDBX8M.js} +1 -1
  38. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DFa-B8-u.js → erDiagram-TEJ5UH35-yYImCEy2.js} +1 -1
  39. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-WCTnaK9M.js → flowDiagram-I6XJVG4X-Cpk1pKF0.js} +1 -1
  40. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DbW1CoJJ.js → ganttDiagram-6RSMTGT7-BnwH90c8.js} +1 -1
  41. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-1faDfO29.js → gitGraphDiagram-PVQCEYII-ELEziEhc.js} +1 -1
  42. package/dist/web-ui/assets/{index-B8h1PPzP.js → index-Dt7RN5t2.js} +5 -5
  43. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DfXKP4tQ.js → infoDiagram-5YYISTIA-48XZ0hV0.js} +1 -1
  44. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-D6FOsFQ5.js → ishikawaDiagram-YF4QCWOH-B0wQJGwe.js} +1 -1
  45. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-DXpxntIF.js → journeyDiagram-JHISSGLW-BNsrI94Q.js} +1 -1
  46. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Dt7FBCF3.js → kanban-definition-UN3LZRKU-Cp8eSqCe.js} +1 -1
  47. package/dist/web-ui/assets/{mermaid.core-sTcSUoRD.js → mermaid.core-BYCWrkC-.js} +5 -5
  48. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CvOU23ga.js → mindmap-definition-RKZ34NQL-Ccay8RYS.js} +1 -1
  49. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-DUedtXVj.js → pieDiagram-4H26LBE5-BUzaEdin.js} +1 -1
  50. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CqpHHRca.js → quadrantDiagram-W4KKPZXB-BtM1AkZX.js} +1 -1
  51. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CKZYvVDJ.js → requirementDiagram-4Y6WPE33-eqO2tGIB.js} +1 -1
  52. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-gZ0nzDfs.js → sankeyDiagram-5OEKKPKP-M6qPg2gI.js} +1 -1
  53. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-DN3XdBkW.js → sequenceDiagram-3UESZ5HK-DtIYVpzR.js} +1 -1
  54. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BvtafGxO.js → stateDiagram-AJRCARHV-CLVsjtbI.js} +1 -1
  55. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-BfZl6BED.js +1 -0
  56. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-BrR919lp.js → timeline-definition-PNZ67QCA-CUwncHES.js} +1 -1
  57. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-B7CTm4yM.js → vennDiagram-CIIHVFJN-KDkzNQIk.js} +1 -1
  58. package/dist/web-ui/assets/{wardley-L42UT6IY-CyqFngx_.js → wardley-L42UT6IY-BqliL5Bv.js} +1 -1
  59. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-BCqEPBJ5.js → wardleyDiagram-YWT4CUSO-B4qeGz2Q.js} +1 -1
  60. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BmT6Cmz-.js → xychartDiagram-2RQKCTM6-3877u0ek.js} +1 -1
  61. package/dist/web-ui/index.html +1 -1
  62. package/package.json +1 -1
  63. package/dist/web-ui/assets/channel-BZs6ereM.js +0 -1
  64. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C9JIxJeJ.js +0 -1
  65. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C9JIxJeJ.js +0 -1
  66. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-B2nWDV5R.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B8h1PPzP.js","assets/index-DD3NMntN.css"])))=>i.map(i=>d[i]);
2
- import{r as S,k as Xm,u as jt,C as Iv,j as c,q as jo,af as zm,ag as qm,w as vt,l as te,ah as qk,a as Zm,b as Vm,P as Gt,c as zh,M as Zk,A as $s,n as Er,J as Xo,i as Fm,ai as Vk,aj as Fk,ak as Uk,al as Hk,am as Yk,an as vO,ao as cc,o as yO,O as Gk,D as Kk,h as Um,d as Jk,ap as Bv,aq as oh,ar as eC,as as SO,at as tC,V as sC,$ as Wv,L as rC,au as iC,av as nC,_ as Xv,aw as oC,ax as ah,ay as aC,az as cu,aA as lC,aB as wO,aC as _O,aD as kO,aE as wa,aF as CO,aG as cC,aH as PO,aI as An,aJ as Bc,aK as Wc,aL as TO,aM as hC,aN as dC,aO as uC,aP as fC,aQ as QO,s as $O,m as jO,aR as mC,aS as pC,aT as hu,aU as RO,aV as gC,aW as du,aX as uu,aY as OC,G as fu,aZ as xC,a_ as EO,a$ as hc,b0 as AO,b1 as bC,b2 as vC,b3 as yC,b4 as MO,b5 as SC,b6 as wC,b7 as _C,b8 as LO,b9 as kC,ba as CC,bb as PC,bc as TC,bd as QC,be as NO,bf as $C,bg as jC,p as RC,bh as EC,bi as AC,bj as MC}from"./index-B8h1PPzP.js";import{P as zv,E as LC,L as qv,S as NC}from"./AsyncState-BebkDWbq.js";import{p as DC,r as DO}from"./CommentInput-BRZWIC3U.js";import{ContentRenderer as Pf,resolveFormat as IC}from"./ContentRenderer-PGP8H_Zz.js";import{a as BC,c as WC,D as XC}from"./DeliverableShareModal-CcigVYGz.js";import{i as zC,S as IO}from"./Switch-C7lFnHA7.js";function ho(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-Dt7RN5t2.js","assets/index-DD3NMntN.css"])))=>i.map(i=>d[i]);
2
+ import{r as S,k as Xm,u as jt,C as Iv,j as c,q as jo,af as zm,ag as qm,w as vt,l as te,ah as qk,a as Zm,b as Vm,P as Gt,c as zh,M as Zk,A as $s,n as Er,J as Xo,i as Fm,ai as Vk,aj as Fk,ak as Uk,al as Hk,am as Yk,an as vO,ao as cc,o as yO,O as Gk,D as Kk,h as Um,d as Jk,ap as Bv,aq as oh,ar as eC,as as SO,at as tC,V as sC,$ as Wv,L as rC,au as iC,av as nC,_ as Xv,aw as oC,ax as ah,ay as aC,az as cu,aA as lC,aB as wO,aC as _O,aD as kO,aE as wa,aF as CO,aG as cC,aH as PO,aI as An,aJ as Bc,aK as Wc,aL as TO,aM as hC,aN as dC,aO as uC,aP as fC,aQ as QO,s as $O,m as jO,aR as mC,aS as pC,aT as hu,aU as RO,aV as gC,aW as du,aX as uu,aY as OC,G as fu,aZ as xC,a_ as EO,a$ as hc,b0 as AO,b1 as bC,b2 as vC,b3 as yC,b4 as MO,b5 as SC,b6 as wC,b7 as _C,b8 as LO,b9 as kC,ba as CC,bb as PC,bc as TC,bd as QC,be as NO,bf as $C,bg as jC,p as RC,bh as EC,bi as AC,bj as MC}from"./index-Dt7RN5t2.js";import{P as zv,E as LC,L as qv,S as NC}from"./AsyncState-Brx503Qq.js";import{p as DC,r as DO}from"./CommentInput-CyyImwaF.js";import{ContentRenderer as Pf,resolveFormat as IC}from"./ContentRenderer-CpiisvVQ.js";import{a as BC,c as WC,D as XC}from"./DeliverableShareModal-BbvcR0LN.js";import{i as zC,S as IO}from"./Switch-C1h7-ixU.js";function ho(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 BO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const qC=(s,e)=>Math.abs(s-e)<1.01,ZC=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},WO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},VC=s=>s,FC=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},UC=(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(WO(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(WO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},XO={passive:!0},zO=typeof window>"u"?!0:"onscrollend"in window,HC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&zO?()=>{}:ZC(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,XO);const h=s.options.useScrollendEvent&&zO;return h&&t.addEventListener("scrollend",l,XO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},YC=(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"]},GC=(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 KC{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:VC,rangeExtractor:FC,onChange:()=>{},measureElement:YC,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=ho(()=>(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=ho(()=>[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=ho(()=>[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=ho(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?JC({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ho(()=>{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=ho(()=>[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 BO(r[Zv(0,r.length-1,i=>BO(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&&qC(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 JC({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 qO=typeof document<"u"?S.useLayoutEffect:S.useEffect;function e2({useFlushSync:s=!0,...e}){const t=S.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Xm.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=S.useState(()=>new KC(r));return i.setOptions(r),qO(()=>i._didMount(),[]),qO(()=>i._willUpdate()),i}function t2(s){return e2({observeElementRect:UC,observeElementOffset:HC,scrollToFn:GC,...s})}function s2({approval:s,submitting:e,readOnly:t,onClose:r,onDecision:i}){const{t:n}=jt(["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 Xm.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(jo,{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 r2({notification:s,agentName:e,acknowledging:t,index:r=0,total:i=1,onClose:n,onAcknowledge:a}){const{t:o,i18n:l}=jt(["team","common"]);Iv(!0);const h=zm(s.createdAt,o),d=qm(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 Xm.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(jo,{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,mu=400,i2=4,n2=350;function Fv(s){return Math.max(0,s.scrollHeight-s.clientHeight)}function VO(s){return Fv(s)>1}function Xc(s){return Fv(s)-s.scrollTop}function o2(s){return Xc(s)<=Vv}function a2(s,e){return Math.abs(e)<=Math.abs(s)?"none":e<0?"up":e>0?"down":"none"}const l2=new Set(["ArrowUp","PageUp","Home"]),c2=new Set(["ArrowDown","PageDown","End"]);function h2(s){return l2.has(s)?"up":c2.has(s)?"down":"none"}function d2(s,e){return s==null?"none":e>s+1?"up":e<s-1?"down":"none"}function u2(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 f2(s){return!s.takeover&&!s.gestureActive}function m2(s,e){return e&&s==="up"}function uo(s,e){return`${s||"_"}::${e??""}`}function p2(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 g2(s,e){if(o2(e))return{kind:"bottom"};const t=p2(s,e.scrollTop);return t?{kind:"row",id:t.id,delta:e.scrollTop-t.start}:{kind:"bottom"}}function O2(s,e){return s+e}const x2=12;function FO(s,e=x2){return{kind:"row",id:s,delta:-e}}function UO(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 b2(s,e,t,r){const i=s.find(n=>n.id===t);return i?O2(i.start-e.scrollTop,r):null}class v2{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 HO=new v2,YO={jump:3,prepend:2,restore:1};function y2(s,e){return!s||s.key!==e.key?!0:YO[e.priority]>=YO[s.priority]}const S2=1e4,GO=300;function w2(s,e){return e-s>S2}function KO(s,e){return s&&e===!0}function _2(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 pu(s){return s!=="prepend"}class k2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(e&&(this.entries.delete(e),t!==""))for(this.entries.set(e,t);this.entries.size>this.capacity;){const r=this.entries.keys().next().value;if(r===void 0)break;this.entries.delete(r)}}get(e){const t=this.peek(e);return t===""?"":(this.entries.delete(e),this.entries.set(e,t),t)}peek(e){return e?this.entries.get(e)??"":""}size(){return this.entries.size}clear(){this.entries.clear()}}const _a=new k2;function JO(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function e0(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function t0(s,e){return!!s&&!!e&&s.has(e)}function C2(s){return s.msgIsStreaming&&s.liveStreamForView}const P2=10*6e4;class T2{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=P2){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 fs=new T2;function Hm(){return S.useSyncExternalStore(fs.subscribe,fs.getRevision,fs.getRevision)}function Uv(s){return S.useSyncExternalStore(fs.subscribe,fs.getRevision,fs.getRevision),fs.isAgentStreaming(s)}function Q2(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 s0=!1;function $2(){s0||(s0=!0,vt.on("session:stream_state",s=>{const e=Q2(s);if(!e)return;const t=Date.parse(s.timestamp??"")||Date.now();fs.applyServerState(e.agentId,e.sessionId,e.streaming,t)}))}async function j2(s,e){if(!(!s||e.length===0)){try{const t=await te.sessions.streamStatusBatch(s,e);fs.reconcileFromServer(s,t.streaming??{},t.at)}catch{}fs.prune()}}function R2(s,e){return!s||s.mode!=="direct"||e.chatMode!=="direct"||!s.sessionId&&!s.preferMain?!1:!!s.agentId&&s.agentId===e.agentId}function Fa({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 yo({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 E2({onClose:s,onCreate:e}){const{t}=jt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("");return c.jsx(Fa,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(yo,{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(yo,{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(qk,{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 A2({onClose:s,onAdd:e}){const{t}=jt(["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(Fa,{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(Fa,{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(yo,{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(yo,{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(yo,{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 M2({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=jt(["team","common"]);return c.jsx(Fa,{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 L2({onClose:s,onConnected:e}){const{t}=jt(["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(Fa,{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(yo,{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 N2(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 D2(s,e){return s&&typeof s.tokensUsedToday=="number"&&Number.isFinite(s.tokensUsedToday)?s.tokensUsedToday:typeof e=="number"&&Number.isFinite(e)?e:0}function I2(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 B2=new Set(["workspace","sessions","tool-outputs","daily-logs","role","subagent-logs","worktrees"]);function W2(s){return B2.has(s)?`agent:profilePage.overview.storageBuckets.${s}`:null}const Tf={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 qh(s){const e=s?Tf[s]:void 0;return e||{...Tf.offline,labelKey:null}}const X2=Tf.working;function Ol(s,e){const t=qh(s);return!e||!t.running||t.tone==="danger"||t.tone==="busy"?t:X2}const z2=5;function r0(s,e=z2){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 q2=100;function Z2(s){const e=Array.isArray(s)?s:[];return{heartbeats:e.filter(t=>t.type==="heartbeat"),comms:e.filter(t=>t.type==="a2a")}}const Ym=["files","mind","recent","tools","memory","usage"],V2=Ym[0];function i0(s,e){return e?"mind":Ym.find(r=>r===s)??V2}function F2(s){return s?"right-panel":"page"}function U2(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 dc=new Map;function H2({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=jt(["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($s,{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 Y2=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:Z}){const{t:X}=jt(["team","common"]),ce=Zm(),j=Vm(Gt.TEAM),W=zh(),D=e?.role==="owner"||e?.role==="admin",F=S.useMemo(()=>new Set(a.map(q=>q.markusAgentId).filter(Boolean)),[a]);Hm();const se=fs.streamingAgentIds(),[me,z]=S.useState([]),[ne,V]=S.useState(new Set),[A,K]=S.useState(!1),[Y,le]=S.useState(!1),[G,be]=S.useState(null),[je,we]=S.useState(!1),[Ue,Qe]=S.useState(!1),[Ye,Ot]=S.useState(null),[Oe,pe]=S.useState(null),[ee,Ze]=S.useState(null),[rt,kt]=S.useState(!1),[Ct,Bt]=S.useState(""),[pt,Pt]=S.useState(null),[Ae,Wt]=S.useState(null),[ut,ks]=S.useState(null),[At,Ne]=S.useState(!1),Jt=S.useRef(null),[at,ft]=S.useState(null),Tt=S.useRef(null),yt=S.useRef(null),[ae,re]=S.useState(null),Xe=(q,fe="success")=>{re({message:q,type:fe}),setTimeout(()=>re(null),3e3)},[de,Se]=S.useState(null),[_e,Ie]=S.useState(!1),Fe=S.useRef(!1);S.useEffect(()=>{if(B)return;te.governance.getSystemStatus().then(ve=>{Fe.current=!0,Se(ve.globalPaused)}).catch(()=>{Fe.current=!0,Se(!1)});const q=vt.on("system:pause-all",()=>{Fe.current&&Se(!0)}),fe=vt.on("system:resume-all",()=>{Fe.current&&Se(!1)});return()=>{q(),fe()}},[]),S.useEffect(()=>{if(!B)return;const q=setTimeout(()=>{const fe=yt.current,ve=Tt.current;fe&&ve&&ve.scrollTo({top:fe.offsetTop-ve.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(q)},[B]);const ze=S.useCallback(()=>{de!==null&&$e({title:X(de?"modals.resumeAll.title":"modals.pauseAll.title"),message:X(de?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:X(de?"chat.resume":"chat.pause"),onConfirm:async()=>{Ie(!0);try{de?(await te.governance.resumeAll(),Se(!1)):(await te.governance.pauseAll(),Se(!0))}catch{}Ie(!1)}})},[de]),[J,$e]=S.useState(null),Te=(q,fe,ve,Be,He)=>{$e({title:q,message:fe,onConfirm:ve,confirmLabel:Be,checkboxes:He})},[ge,Pe]=S.useState(null),[Ve,it]=S.useState(null),bt=S.useRef(null),mt=S.useRef(null),[nt,xt]=S.useState(!1),[Zn,on]=S.useState(null),[he,Rt]=S.useState(""),ye=S.useCallback((q,fe=176,ve=220)=>{const Be=window.innerWidth,He=window.innerHeight,Ge=8;let gt=q.clientX,wt=q.clientY;return gt+fe>Be-Ge&&(gt=Math.max(Ge,Be-fe-Ge)),wt+ve>He-Ge&&(wt=Math.max(Ge,He-ve-Ge)),gt=Math.max(Ge,Math.min(gt,Be-fe-Ge)),wt=Math.max(Ge,Math.min(wt,He-ve-Ge)),{x:gt,y:wt}},[]),[Bs,lt]=S.useState(dc),Ws=S.useMemo(()=>t.map(q=>q.id).sort().join(","),[t]);S.useEffect(()=>{if(!t.length||!j)return;let q=!1;(async()=>{const wt=[];await Promise.allSettled(t.map(async ot=>{if(!dc.has(ot.id))try{const{sessions:Ft}=await te.sessions.listByAgent(ot.id,1);if(!Ft.length)return;const{messages:bs}=await te.sessions.getMessages(Ft[0].id,1);if(bs.length){const vs=bs[0],Xt=vs.metadata?.segments;let Cs=vs.content;if(Xt&&Xt.length>0){const es=[...Xt].reverse().find(Or=>Or.type==="text");es&&es.type==="text"&&(Cs=es.content)}const Us=Cs.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);Us&&wt.push([ot.id,Us])}}catch{}})),!q&&wt.length&&lt(ot=>{const Ft=new Map(ot);for(const[bs,vs]of wt)Ft.set(bs,vs);return dc=Ft,Ft})})();const ve=new Set(t.map(wt=>wt.id)),Be=wt=>Vk(wt).replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),He=(wt,ot)=>{if(!wt||!ot||!ve.has(wt))return;const Ft=Be(ot);Ft&&lt(bs=>{const vs=new Map(bs);return vs.set(wt,Ft),dc=vs,vs})},Ge=vt.on("chat:proactive_message",wt=>{const ot=wt.payload;He(ot.agentId??"",ot.message??"")}),gt=vt.on("chat:message",wt=>{const ot=wt.payload,Ft=ot.senderId??ot.agentId??"",bs=ot.text??ot.message??"";He(Ft,bs)});return()=>{q=!0,Ge(),gt()}},[Ws,j]);const St=S.useCallback(()=>{B||te.teams.list().then(q=>z(q.ungrouped)).catch(()=>{})},[B]);S.useEffect(()=>{St()},[St]),S.useEffect(()=>{if(!j)return;const q=vt.on("team:update",St),fe=vt.on("agent:removed",St);return()=>{q(),fe()}},[St,j]),S.useEffect(()=>{if(!Oe&&!ee&&!pt&&!At&&!ut)return;const q=()=>{pe(null),Ze(null),Pt(null),ks(null),Ne(!1)},fe=setTimeout(()=>document.addEventListener("click",q),0);return()=>{clearTimeout(fe),document.removeEventListener("click",q)}},[Oe,ee,pt,At,ut]);const an=(q,fe)=>{Te(`${X("common:delete")} "${fe}"?`,X("modals.deleteTeam.message"),async ve=>{const Be=ve?.deleteMembers??!0,He=ve?.purgeFiles??!1;await te.teams.delete(q,Be,{purgeFiles:He}),O(),St(),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}])},Uo=async(q,fe)=>{try{const Be=await(fe==="start"?te.teams.startAll:te.teams.stopAll)(q),He=Be.success?.length??0,Ge=Be.failed?.length??0;Ge>0?Xe(X("batchAction.failed",{action:X(`batchAction.operation.${fe}`),ok:He,fail:Ge}),"error"):He>0&&Xe(X("batchAction.succeeded",{count:He,action:X(`batchAction.past.${fe}`)}),"success"),m()}catch(ve){Xe(X("batchAction.failedToRun",{action:X(`batchAction.operation.${fe}`),error:ve instanceof Error?ve.message:String(ve)}),"error")}},ln=async(q,fe,ve)=>{await te.teams.update(q,{managerId:fe,managerType:ve}),O()},Tl=async q=>{if(!he.trim()){on(null);return}await te.teams.update(q,{name:he.trim()}),on(null),O()},Ql=async(q,fe)=>{fe==="offline"?await te.agents.start(q):await te.agents.stop(q),m()},gs=(q,fe)=>{Te(X("modals.removeFromTeam.title"),X("modals.removeFromTeam.message"),async()=>{await te.teams.removeMember(q,fe),O(),St()},X("common:remove"))},is=(q,fe,ve,Be)=>{Te(`${X("common:remove")} "${fe}"?`,X(ve==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async He=>{if(ve==="agent"&&Be){const Ge=o.find(gt=>gt.type==="team"&&gt.teamId===Be);Ge?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+Ge.channelKey)}if(ve==="agent"){const Ge=He?.purgeFiles??!1;await te.agents.remove(q,{purgeFiles:Ge})}else await te.users.remove(q);m(),O(),x?.(),St(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("common:remove"),ve==="agent"?[{id:"purgeFiles",label:X("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},Os=q=>{if(q.isOrgSecretary||q.protected)return!0;if(q.teamId)return!1;const fe=(q.role??"").toLowerCase().trim(),ve=(q.name??"").trim();return ve==="Secretary"||ve==="秘书"||fe==="secretary"||fe.startsWith("secretary")},pr=(q,fe,ve)=>{const Be=t.find(He=>He.id===fe);Be&&Os(Be)||(mt.current={x:q.clientX,y:q.clientY},bt.current=setTimeout(()=>{Pe({agentId:fe,fromTeamId:ve}),xt(!0)},200))},Ho=q=>{if(!mt.current||!bt.current)return;const fe=Math.abs(q.clientX-mt.current.x),ve=Math.abs(q.clientY-mt.current.y);(fe>5||ve>5)&&(nt||(clearTimeout(bt.current),bt.current=null))},$l=async()=>{if(bt.current&&(clearTimeout(bt.current),bt.current=null),mt.current=null,nt&&ge&&Ve){const q=Ve==="_ungrouped"?void 0:Ve;try{if(ge.fromTeamId&&ge.fromTeamId!==q&&await te.teams.removeMember(ge.fromTeamId,ge.agentId),q&&q!==ge.fromTeamId){const fe=t.find(ve=>ve.id===ge.agentId);await te.teams.addMember(q,ge.agentId,"agent")}O(),m(),St()}catch(fe){Xe(X("batchAction.moveFailed",{error:fe instanceof Error?fe.message:String(fe)}),"error")}}Pe(null),it(null),xt(!1)},Br=S.useMemo(()=>new Map(r.map(q=>[q.id,q])),[r]),xs=S.useMemo(()=>{const q=new Map,fe=[];for(const ve of t)if(ve.teamId&&Br.has(ve.teamId)){const Be=q.get(ve.teamId)??[];Be.push(ve),q.set(ve.teamId,Be)}else fe.push(ve);return{byTeam:q,ungrouped:fe}},[t,Br]),Vn=(q,fe)=>{const ve=l==="direct"&&h===q.id,Be=F.has(q.id),He=q.status==="offline",Ge=Ol(q.status,!He&&se.has(q.id)),gt=Ge.tone==="busy",wt=Ge.dotClass,Ft=(void 0)?.managerId===q.id,bs=q.role?.toLowerCase().replace(/[-_]/g," ").trim(),vs=q.name.toLowerCase().trim(),Xt=bs&&bs!==vs,Cs=Bs.get(q.id)||q.currentActivity?.label?.slice(0,60)||"",Us=gt?X("common:status.working"):q.status==="error"?X("common:status.error"):X(He?"common:status.offline":"common:status.online");return c.jsx("div",{className:`relative mb-0.5 ${nt&&ge?.agentId===q.id?"opacity-40":""}`,onPointerDown:es=>pr(es,q.id,fe),onPointerMove:Ho,onPointerUp:$l,children:c.jsxs("button",{"data-l1-nav-id":`agent:${q.id}`,onClick:()=>{nt||f(q.id)},onContextMenu:es=>{if(!D)return;es.preventDefault();const Or=ye(es);kt(!1),Bt(""),Ze({agentId:q.id,teamId:fe,...Or})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ce?"":"touch-none"} ${He?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Qi(ve)}`,children:[c.jsx($s,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:He?"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}),Xt&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",q.role,")"]}),Ft&&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"})}),Be&&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"}),He&&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:Cs||" "})]}),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:Us,onClick:es=>{es.stopPropagation(),k(q.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${wt}`}),ce&&D&&c.jsx("span",{role:"button",tabIndex:0,onClick:es=>{if(es.stopPropagation(),ee?.agentId===q.id)Ze(null);else{const Or=ye(es);kt(!1),Bt(""),Ze({agentId:q.id,teamId:fe,...Or})}},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)},jl=(q,fe,ve,Be)=>{const He=nt&&Ve===q&&ge?.fromTeamId!==q,Ge=at===q,gt=g===q,wt=P?(xs.byTeam.get(q)??[]).reduce((Ut,ai)=>Ut+(P.get(ai.id)??0),0):0,Ft=o.find(Ut=>Ut.type==="team"&&Ut.teamId===q)?.channelKey??Hv(q),bs=_?_[Ft]??0:0,vs=wt+bs,Xt=xs.byTeam.get(q)??[],Cs=Xt.filter(Ut=>Ut.status==="offline").length,Us=Xt.length,es=Us>0&&Cs===Us,Or=Cs>0&&!es,Fn=es?"bg-gray-500":Or?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":q,className:`mb-0.5 rounded-lg transition-all duration-500 ${He?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Ge?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{nt&&it(q)},onPointerLeave:()=>{nt&&Ve===q&&it(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:Ut=>{if(!D||!fe)return;Ut.preventDefault();const ai=ye(Ut);pe({teamId:q,...ai})},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(gt)}`,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:[fe?.avatarUrl?c.jsx("img",{src:fe.avatarUrl,alt:Be,className:"w-full h-full rounded-full object-cover",onError:Ut=>{Ut.target.style.display="none",Ut.target.nextElementSibling?.classList.remove("hidden")}}):null,c.jsxs("svg",{className:`w-3 h-3 ${fe?.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"})]}),Us>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 ${Fn}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[Zn===q?c.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:he,onChange:Ut=>Rt(Ut.target.value),onBlur:()=>Tl(q),onKeyDown:Ut=>{Ut.key==="Enter"&&Tl(q),Ut.key==="Escape"&&on(null)},onClick:Ut=>Ut.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Be}),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:ve}),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")}),Or&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Cs,"/",Us]})]})]}),vs>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:vs}),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&&fe&&c.jsx("button",{onClick:Ut=>{if(Ut.stopPropagation(),Oe?.teamId===q)pe(null);else{const ai=ye(Ut);pe({teamId:q,...ai})}},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"})]})})]}),He&&nt&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:X("chat.dropHere")})]},q)},ns=S.useMemo(()=>{const q=new Map,fe=[],ve=[],Be=[];for(const He of o)if(He.channelKey.startsWith("dm:a2a:"))Be.push(He);else if(He.type==="custom")ve.push(He);else if(He.teamId){const Ge=q.get(He.teamId)??[];Ge.push(He),q.set(He.teamId,Ge)}else{const Ge=r.find(gt=>He.name.toLowerCase().includes(gt.name.toLowerCase())||gt.name.toLowerCase().includes(He.name.toLowerCase()));if(Ge){const gt=q.get(Ge.id)??[];gt.push(He),q.set(Ge.id,gt)}else fe.push(He)}return{byTeam:q,unmatched:fe,custom:ve,dmChannels:Be}},[o,r]),Cr=S.useMemo(()=>{const q=new Map;let fe=0;for(const He of xs.ungrouped)q.set(He.id,fe++);for(const He of r)for(const Ge of xs.byTeam.get(He.id)??[])q.set(Ge.id,fe++);const ve=Number.MAX_SAFE_INTEGER,Be=He=>{const Ge=He.split(":");return Ge.length<4?[]:[Ge[2],Ge[3]].map(gt=>q.get(gt)??ve).sort((gt,wt)=>gt-wt)};return[...ns.dmChannels].sort((He,Ge)=>{const gt=Be(He.channelKey),wt=Be(Ge.channelKey),ot=gt[0]??ve,Ft=gt[1]??ve,bs=wt[0]??ve,vs=wt[1]??ve;return ot!==bs?ot-bs:Ft!==vs?Ft-vs:He.channelKey.localeCompare(Ge.channelKey)})},[ns.dmChannels,xs,r]),[cn,$t]=S.useState(!1),gr=l==="channel"&&ns.dmChannels.some(q=>q.channelKey===d);S.useEffect(()=>{gr&&$t(!0)},[gr]);const Rl=S.useMemo(()=>{const q=[];e&&q.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const ve of i)ve.id!==e?.id&&q.push({kind:"dm",id:`dm:${ve.id}`,userId:ve.id});for(const ve of ns.custom)q.push({kind:"channel",id:`channel:${ve.channelKey}`,channelKey:ve.channelKey});for(const ve of ns.unmatched)q.push({kind:"channel",id:`channel:${ve.channelKey}`,channelKey:ve.channelKey});const fe=xs.ungrouped.length>0?xs.ungrouped:r.length===0?t:[];for(const ve of fe)q.push({kind:"agent",id:`agent:${ve.id}`,agentId:ve.id});for(const ve of r)q.push({kind:"team",id:`team:${ve.id}`,teamId:ve.id});if(cn)for(const ve of Cr)q.push({kind:"channel",id:`channel:${ve.channelKey}`,channelKey:ve.channelKey});return q},[e,i,ns,xs,r,t,cn]),El=S.useRef(Rl);El.current=Rl;const Al=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||ce||!j||L)return;const q=fe=>{const ve=W?.keyboardPane??"content";if(ve==="l0"||ve==="l2"||fe.metaKey||fe.ctrlKey||fe.altKey||Fm(fe.target))return;const Be=fe.key.length===1?fe.key.toLowerCase():fe.key;if(Be==="h"||Be==="ArrowLeft"){if(ve!=="l1")return;fe.preventDefault(),fe.stopPropagation(),W?.setL0FocusPageId(Gt.TEAM),W?.setLeftCollapsed(!1),W?.setKeyboardPane("l0");return}if(Be==="l"||Be==="ArrowRight"){if(ve!=="l1")return;fe.preventDefault(),fe.stopPropagation(),Z&&W?.setKeyboardPane("l2");return}if(ve!=="l1"&&!(U&&(Be==="j"||Be==="k"||Be==="ArrowDown"||Be==="ArrowUp")))return;const He=Be==="j"||Be==="ArrowDown"?1:Be==="k"||Be==="ArrowUp"?-1:0;if(!He)return;fe.preventDefault(),fe.stopPropagation(),W?.setKeyboardPane("l1");const Ge=El.current;if(Ge.length===0)return;let gt=-1;if(l==="dm"){const ot=u||e?.id;ot&&(gt=Ge.findIndex(Ft=>Ft.kind==="dm"&&Ft.userId===ot))}else l==="direct"?gt=Ge.findIndex(ot=>ot.kind==="agent"&&ot.agentId===h):l==="channel"&&(gt=Ge.findIndex(ot=>ot.kind==="channel"&&ot.channelKey===d),gt<0&&g&&(gt=Ge.findIndex(ot=>ot.kind==="team"&&ot.teamId===g)));gt<0&&(gt=He>0?-1:0);const wt=Math.max(0,Math.min(Ge.length-1,gt+He));Al(Ge[wt])};return document.addEventListener("keydown",q,!0),()=>document.removeEventListener("keydown",q,!0)},[B,ce,j,L,W,U,Z,l,u,e?.id,h,d,g,Al]);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:[ce&&c.jsx(Zk,{}),!ce&&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:Jt,children:[c.jsxs("button",{onClick:()=>Ne(!At),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 ${At?"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"})})]}),At&&c.jsxs("div",{ref:q=>{if(!q)return;const fe=q.getBoundingClientRect(),ve=window.innerWidth,Be=8;fe.right>ve-Be&&(q.style.left="auto",q.style.right="0"),fe.left<Be&&(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:()=>{Ne(!1),Ot("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:()=>{Ne(!1),Ot("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:()=>{Ne(!1),le(!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:()=>{Ne(!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")})]}),de!==null&&c.jsxs("button",{onClick:()=>{Ne(!1),ze()},disabled:_e,className:`w-full text-left px-4 py-2.5 text-xs hover:bg-surface-elevated border-t border-border-default transition-colors disabled:opacity-50 ${de?"text-green-600":"text-red-500"}`,children:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:de?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(de?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:Tt,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children: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($s,{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 fe=e?.id?`dm:${[e.id,q.id].sort().join(":")}`:"",ve=fe&&_?_[fe]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${q.id}`,onClick:()=>v(q.id),onContextMenu:Be=>{if(!D||q.id===e?.id)return;Be.preventDefault();const He=ye(Be);Pt({userId:q.id,...He})},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($s,{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})]}),ve>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:ve}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},q.id)})]}),ns.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")}),ns.custom.map(q=>{const fe=l==="channel"&&d===q.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),onContextMenu:ve=>{ve.preventDefault();const Be=ye(ve);ks({gcId:q.id,...Be})},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(fe)}`,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,fe)=>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"})]},fe))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:X("chat.noAgentsYet")}):null,ns.unmatched.map(q=>{const fe=_?.[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")})]}),fe>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:fe}):q.memberCount!==void 0&&q.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:q.memberCount}):null]},q.id)}),xs.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")}),xs.ungrouped.map(q=>Vn(q))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:yt,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 fe=xs.byTeam.get(q.id)??[],ve=q.members?.length||fe.length;return jl(q.id,q,ve,q.name)})]}),r.length===0&&xs.ungrouped.length===0&&t.length>0&&t.map(q=>Vn(q)),Cr.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>$t(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 ${cn?"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:Cr.length})]}),cn&&Cr.map(q=>{const fe=l==="channel"&&d===q.channelKey,ve=_?.[q.channelKey]??0,Be=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(fe)}`,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:Be}),ve>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:ve})]},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"})}),Oe&&(()=>{const q=xs.byTeam.get(Oe.teamId)??[],fe=q.some(Be=>Be.status==="offline"),ve=q.some(Be=>Be.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:Oe.x,top:Oe.y},onClick:Be=>Be.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const Be=Br.get(Oe.teamId);Be&&(on(Oe.teamId),Rt(Be.name)),pe(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")]}),fe&&c.jsxs("button",{onClick:()=>{Uo(Oe.teamId,"start"),pe(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")]}),ve&&c.jsxs("button",{onClick:()=>{Uo(Oe.teamId,"stop"),pe(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:()=>{pe(null),Er.navigate(Gt.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[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")]}),me.length>0&&c.jsxs("button",{onClick:()=>{pe(null),be(Oe.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[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 Be=Br.get(Oe.teamId);Be&&an(Oe.teamId,Be.name),pe(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")]})]})})(),ee&&(()=>{const q=t.find(Ge=>Ge.id===ee.agentId);if(!q||!D)return null;const ve=(ee.teamId?Br.get(ee.teamId):void 0)?.managerId===q.id,Be=q.id===e?.id,He=Os(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:ee.x,top:ee.y,maxHeight:Math.max(160,window.innerHeight-ee.y-8)},onClick:Ge=>Ge.stopPropagation(),children:[He&&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:()=>{Ze(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:()=>{Ql(q.id,"offline"),Ze(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:()=>{Ql(q.id,q.status??"idle"),Ze(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")]}),!He&&ee.teamId&&!ve&&c.jsxs("button",{onClick:()=>{ln(ee.teamId,q.id,"agent"),Ze(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")]}),!He&&ee.teamId&&c.jsxs("button",{onClick:()=>{gs(ee.teamId,q.id),Ze(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")]}),!He&&(()=>{const Ge=r.filter(ot=>ot.id!==ee.teamId);if(Ge.length===0)return null;const gt=Ct.trim().toLowerCase(),wt=gt?Ge.filter(ot=>ot.name.toLowerCase().includes(gt)):Ge;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>kt(ot=>!ot),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 ${rt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),rt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:ot=>ot.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:Ct,onChange:ot=>Bt(ot.target.value),onKeyDown:ot=>ot.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:wt.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:X("contextMenu.moveToEmpty")}):wt.map(ot=>c.jsx("button",{type:"button",onClick:async()=>{ee.teamId&&await te.teams.removeMember(ee.teamId,q.id),await te.teams.addMember(ot.id,q.id,"agent"),O(),m(),St(),Ze(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:ot.name,children:ot.name},ot.id))})]})]})})(),!He&&!Be&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{is(q.id,q.name,"agent",ee.teamId),Ze(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")]})]})]})})(),pt&&(()=>{const q=i.find(fe=>fe.id===pt.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:pt.x,top:pt.y},onClick:fe=>fe.stopPropagation(),children:c.jsxs("button",{onClick:()=>{is(q.id,q.name,"human"),Pt(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(E2,{onClose:()=>K(!1),onCreate:async(q,fe)=>{try{const{team:ve}=await te.teams.create(q,fe);K(!1),O(),ft(ve.id),setTimeout(()=>{document.querySelector(`[data-team-id="${ve.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>ft(null),3e3)}catch(ve){Xe(X("chat.failedToCreateTeam",{message:ve instanceof Error?ve.message:String(ve)}),"error")}}}),Y&&c.jsx(A2,{onClose:()=>{le(!1),x?.()},onAdd:async(q,fe,ve)=>{const{inviteToken:Be}=await te.users.create(q,fe,void 0,ve);return x?.(),{inviteToken:Be}}}),G!==null&&c.jsx(M2,{teamId:G,ungrouped:me,onClose:()=>be(null),onAdd:async(q,fe)=>{await te.teams.addMember(G,q,fe),be(null),O(),St()}}),je&&c.jsx(L2,{onClose:()=>we(!1),onConnected:()=>{we(!1),m(),O()}}),ut&&(()=>{const q=o.find(fe=>fe.id===ut.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:ut.x,top:ut.y},onClick:fe=>fe.stopPropagation(),children:[q.type==="custom"&&c.jsxs("button",{onClick:()=>{ks(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()=>{ks(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})(),Ue&&c.jsx(H2,{agents:t,humans:i,authUser:e,onClose:()=>Qe(!1),onCreate:async(q,fe,ve,Be)=>{await te.groupChats.create({name:q,memberIds:fe,memberTypes:ve,memberNames:Be,creatorId:e?.id,creatorName:e?.name}),Qe(!1),y()}}),Ye&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>Ot(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(Ye==="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=Ye;Ot(null);const fe=t.find(ve=>ve.role==="secretary")??t.find(ve=>ve.name?.toLowerCase().includes("secretary"));fe?(f(fe.id),Er.navigate(Gt.TEAM,{agentId:fe.id,prefillMessage:X(q==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):q==="agent"?Er.navigate(Gt.STORE):K(!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=Ye;Ot(null),q==="agent"?Er.navigate(Gt.STORE):K(!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(Ye==="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:()=>Ot(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")})})]})}),J&&c.jsx(Xo,{title:J.title,message:J.message,confirmLabel:J.confirmLabel,checkboxes:J.checkboxes,onConfirm:q=>{J.onConfirm(q),$e(null)},onCancel:()=>$e(null)}),ae&&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 ${ae.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:ae.message})]})});function n0({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}=jt(["team","common"]),C=zh(),P=Vm(Gt.TEAM),_=r?.role==="owner"||r?.role==="admin";Hm();const T=S.useMemo(()=>e.filter(Y=>Y.teamId===s.id),[e,s.id]),R=S.useMemo(()=>{const Y=new Set((s.members??[]).filter(le=>le.type==="human").map(le=>le.id));return t.filter(le=>Y.has(le.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 le of T)Y.push({kind:"agent",id:`agent:${le.id}`,agentId:le.id});for(const le of R)Y.push({kind:"dm",id:`dm:${le.id}`,userId:le.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=le=>{if((C?.keyboardPane??"content")!=="l2"||le.metaKey||le.ctrlKey||le.altKey||Fm(le.target))return;const be=le.key.length===1?le.key.toLowerCase():le.key;if(be==="h"||be==="ArrowLeft"){le.preventDefault(),le.stopPropagation(),C?.setKeyboardPane("l1");return}if(be==="l"||be==="ArrowRight"){le.preventDefault(),le.stopPropagation();return}const je=be==="j"||be==="ArrowDown"?1:be==="k"||be==="ArrowUp"?-1:0;if(!je)return;le.preventDefault(),le.stopPropagation();const we=E.current;if(we.length===0)return;let Ue=-1;n==="channel"?Ue=we.findIndex(Ye=>Ye.kind==="channel"&&Ye.channelKey===o):n==="direct"?Ue=we.findIndex(Ye=>Ye.kind==="agent"&&Ye.agentId===a):n==="dm"&&l&&(Ue=we.findIndex(Ye=>Ye.kind==="dm"&&Ye.userId===l)),Ue<0&&(Ue=je>0?-1:0);const Qe=Math.max(0,Math.min(we.length-1,Ue+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",[Z,X]=S.useState(null),[ce,j]=S.useState(!1),[W,D]=S.useState(""),[F,se]=S.useState(null),me=(Y,le,G,be,je)=>{se({title:Y,message:le,onConfirm:G,confirmLabel:be,checkboxes:je})},z=S.useCallback((Y,le=176,G=220)=>{const be=window.innerWidth,je=window.innerHeight,we=8;let Ue=Y.clientX,Qe=Y.clientY;return Ue+le>be-we&&(Ue=Math.max(we,be-le-we)),Qe+G>je-we&&(Qe=Math.max(we,je-G-we)),Ue=Math.max(we,Math.min(Ue,be-le-we)),Qe=Math.max(we,Math.min(Qe,je-G-we)),{x:Ue,y:Qe}},[]);S.useEffect(()=>{if(!Z)return;const Y=()=>X(null),le=setTimeout(()=>document.addEventListener("click",Y),0);return()=>{clearTimeout(le),document.removeEventListener("click",Y)}},[Z]);const ne=S.useCallback(async(Y,le)=>{le==="offline"?await te.agents.start(Y):await te.agents.stop(Y),b()},[b]),V=S.useCallback(async Y=>{await te.teams.update(s.id,{managerId:Y,managerType:"agent"}),g()},[s.id,g]),A=S.useCallback(async Y=>{await te.teams.removeMember(s.id,Y),g(),b()},[s.id,g,b]),K=S.useCallback(async(Y,le)=>{await te.teams.removeMember(s.id,Y),await te.teams.addMember(le,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 le=n==="direct"&&a===Y.id,G=s.managerId===Y.id,be=Y.status==="offline",je=Ol(Y.status,fs.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 Ue=z(we);j(!1),D(""),X({agentId:Y.id,...Ue})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${be?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${U(le)}`,children:[c.jsx($s,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:be?"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}),G&&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"})}),be&&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 le=Y.id===r?.id,G=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(G)}`,children:[c.jsx($s,{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,le?` (${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"})}),Z&&(()=>{const Y=T.find(G=>G.id===Z.agentId);if(!Y||!_)return null;const le=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:Z.x,top:Z.y,maxHeight:Math.max(160,window.innerHeight-Z.y-8)},onClick:G=>G.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:()=>{ne(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:()=>{ne(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")]}),!le&&c.jsxs("button",{onClick:()=>{V(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 G=h.filter(we=>we.id!==s.id);if(G.length===0)return null;const be=W.trim().toLowerCase(),je=be?G.filter(we=>we.name.toLowerCase().includes(be)):G;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 ${ce?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ce&&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:()=>{K(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:()=>{me(`${k("common:remove")} "${Y.name}"?`,k("modals.removeAgent.message"),async G=>{const be=G?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await te.agents.remove(Y.id,{purgeFiles:be}),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")]})]})})(),F&&c.jsx(Xo,{title:F.title,message:F.message,confirmLabel:F.confirmLabel,checkboxes:F.checkboxes,onConfirm:Y=>{F.onConfirm(Y),se(null)},onCancel:()=>se(null)})]})}function Qf(){return Qf=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},Qf.apply(null,arguments)}function G2(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 $f=[],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:$f).push(t=t+s[e])})();function K2(s){if(s<768)return!1;for(let e=0,t=$f.length;;){let r=e+t>>1;if(s<$f[r])t=r;else if(s>=Yv[r])e=r+1;else return!0;if(e==t)return!1}}function o0(s){return s>=127462&&s<=127487}const a0=8205;function J2(s,e,t=!0,r=!0){return(t?Gv:eP)(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=gu(s,e);for(e+=l0(r);e<s.length;){let i=gu(s,e);if(r==a0||i==a0||t&&K2(i))e+=l0(i),r=i;else if(o0(i)){let n=0,a=e-2;for(;a>=0&&o0(gu(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function eP(s,e,t){for(;e>1;){let r=Gv(s,e-2,t);if(r<e)return r;e--}return 0}function gu(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 l0(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]=Ro(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),Yr.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]=Ro(this,e,t);let r=[];return this.decompose(e,t,r,0),Yr.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 Da(this),n=new Da(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 Da(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 ls(e):Yr.from(ls.split(e,[]))}};class ls extends Lt{constructor(e,t=tP(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 sP(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new ls(c0(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=zc(n.text,a.text.slice(),0,n.length);if(o.length<=32)r.push(new ls(o,a.length+n.length));else{let l=o.length>>1;r.push(new ls(o.slice(0,l)),new ls(o.slice(l)))}}else r.push(n)}replace(e,t,r){if(!(r instanceof ls))return super.replace(e,t,r);[e,t]=Ro(this,e,t);let i=zc(this.text,zc(r.text,c0(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new ls(i,n):Yr.from(ls.split(i,[]),n)}sliceString(e,t=this.length,r=`
@@ -55,7 +55,7 @@ ${ae}
55
55
  `)})},[i,s]);S.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const ae=navigator.platform.toUpperCase().includes("MAC"),re=Xe=>{if(!(ae?Xe.metaKey&&!Xe.ctrlKey:Xe.ctrlKey&&!Xe.metaKey)||!Xe.shiftKey||Xe.altKey||Xe.key.toLowerCase()!=="a")return;const Se=K.current?.getSelection()?.trim();Se&&(Xe.preventDefault(),ee(Se))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[s.kind,i,ee]);const rt=S.useCallback(ae=>{if(!ae.text.trim()||!i)return;const re=ne.current?.querySelector("iframe")?.getBoundingClientRect(),Xe=(re?.left??0)+ae.rect.x+ae.rect.width/2,de=(re?.top??0)+ae.rect.y;B({x:Xe,y:de,text:ae.text,htmlMeta:{xpath:ae.xpath,cssSelector:ae.cssSelector}})},[i]);S.useEffect(()=>{const ae=ne.current;if(!ae||!i)return;const re=()=>{requestAnimationFrame(()=>{const de=window.getSelection(),Se=de?.toString().trim();if(!Se||!de?.rangeCount){B(null);return}const _e=de.getRangeAt(0);if(!ae.contains(_e.commonAncestorContainer)){B(null);return}const Ie=_e.getBoundingClientRect();B({x:Ie.left+Ie.width/2,y:Ie.top,text:Se})})},Xe=de=>{const Se=document.getElementById("right-panel-selection-toolbar");Se&&Se.contains(de.target)||B(null)};return ae.addEventListener("mouseup",re),document.addEventListener("mousedown",Xe),()=>{ae.removeEventListener("mouseup",re),document.removeEventListener("mousedown",Xe)}},[i,x.mode]);const kt=()=>{te.files.reveal(je||G).catch(()=>{})},Ct=()=>{navigator.clipboard?.writeText(je||G).then(()=>{_(!0),setTimeout(()=>_(!1),1500)}).catch(()=>{})},Bt=S.useMemo(()=>{if(!i)return null;const ae=je||G;if(s.kind==="deliverable"){const re=s.deliverable;if(!re.id&&!re.reference)return null;const Xe=be||re.title||re.reference||re.id;return{label:`📄 ${Xe.length>40?`${Xe.slice(0,24)}…${Xe.slice(-12)}`:Xe}`,content:["[deliverable]",re.id?`ID: ${re.id}`:"",re.title?`Title: ${re.title}`:"",re.reference?`Reference: ${re.reference}`:"",re.taskId?`Task: ${re.taskId}`:"",re.projectId?`Project: ${re.projectId}`:""].filter(Boolean).join(`
56
56
  `)}}if(s.kind==="file"){if(!ae||fo(ae))return null;const re=be||ae.split(/[/\\]/).pop()||ae;return{label:`📄 ${re.length>40?`${re.slice(0,24)}…${re.slice(-12)}`:re}`,content:["[file]",`Path: ${ae}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
57
57
  `)}}return null},[i,s,je,G,be,x]),[pt,Pt]=S.useState(!1),Ae=S.useCallback(()=>{Bt&&(i?.(Bt),Pt(!0),setTimeout(()=>Pt(!1),1200))},[Bt,i]),Wt=S.useCallback(async()=>{if(s.kind==="deliverable"){Er.navigate(Gt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let re=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const Xe=await window.markusDesktop.browser.getState(s.browserId);if(Xe.ok){if(Xe.directoryPath){await te.system.openPath(Xe.directoryPath).catch(()=>te.files.reveal(Xe.directoryPath));return}Xe.url&&Xe.url!=="about:blank"&&(re=Xe.url)}}catch{}if(!re||re==="about:blank")return;if(/^https?:\/\//i.test(re)||/^file:\/\//i.test(re)){cc(re);return}await te.system.openPath(re).catch(()=>cc(pv(re)));return}if(s.kind!=="file")return;const ae=s.path;if(ae){if(/^https?:\/\//i.test(ae)||/^file:\/\//i.test(ae)){cc(ae);return}await te.system.openPath(ae).catch(()=>cc(pv(ae)))}},[s]),ut=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,ks=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),At=!!G&&!fo(G)&&(s.kind==="file"||s.kind==="deliverable"),Ne=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!G&&!fo(G)&&!s.deliverable.artifactType&&BC(s.deliverable.format),Jt=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,at=S.useCallback(ae=>{M(ae)},[]),ft=S.useMemo(()=>WC(yO,Um.getUrl()),[]),Tt=s.kind==="deliverable"?s.deliverable.id:null;S.useEffect(()=>{if(!Tt||!yO())return;let ae=!1;const re=async()=>{try{const de=await ft.listMine();if(ae)return;const Se=s.kind==="deliverable"?s.deliverable:null;if(!Se)return;const _e=Se.hubShareId&&de.find(ze=>ze.id===Se.hubShareId)||de.find(ze=>ze.localId===Se.id);if(!_e)return;M(ze=>ze&&ze.id===_e.id&&ze.status===_e.status?ze:_e);const Ie={hubShareId:Se.hubShareId??_e.id??null,shareStatus:_e.status??null,shareUrl:_e.url??null,shareVisibility:Se.shareVisibility??_e.visibility??null};(Se.shareStatus!==Ie.shareStatus||Se.hubShareId!==Ie.hubShareId||Se.shareUrl!==Ie.shareUrl||Se.shareVisibility!==Ie.shareVisibility)&&Se.id&&te.deliverables.update(Se.id,Ie).catch(ze=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ze)})}catch{}};re();const Xe=setInterval(re,3e4);return()=>{ae=!0,clearInterval(Xe)}},[ft,Tt,s]);const yt=Jt?.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:V,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:ae=>{const re=ae.currentTarget;re.scrollWidth<=re.clientWidth||Math.abs(ae.deltaY)<=Math.abs(ae.deltaX)||(re.scrollLeft+=ae.deltaY,ae.preventDefault())},children:[n?.map(ae=>{const re=ae.id===a,Xe=ae.payload.kind==="url"?ae.payload.pageId:void 0,de=ae.payload.kind==="terminal"?ae.payload.terminalId:void 0,Se=Xe!=null?U[Xe]:de?X[de]:void 0,_e=Se?`${ae.title} — ${m("common:browserTabControlledBy",{name:Se.agentName})}`:ae.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${re?Se?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Se?"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":re,ref:re?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:_e,onPointerDown:Ie=>{Ie.button===0&&(ae.id!==a&&!le()||o?.(ae.id))},onClick:()=>{ae.id!==a&&!le()||o?.(ae.id)},children:[Se&&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:Se.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:Se.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:ae.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:Ie=>{Ie.button===0&&(Ie.preventDefault(),Ie.stopPropagation(),!(ae.id===a&&!le())&&l(ae.id))},onClick:Ie=>{Ie.preventDefault(),Ie.stopPropagation(),!(ae.id===a&&!le())&&l(ae.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${re?"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"})]})})]},ae.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(pD,{scrollRef:V,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:G||be,children:be}),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:Ot,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:()=>me(ae=>!ae),"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:()=>{Ze()},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"})})}),Bt&&c.jsx("button",{type:"button",onClick:Ae,title:pt?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 ${pt?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:pt?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"})]})}),Ne&&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 ${yt==="published"?"text-green-500 hover:text-green-400":yt==="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"})]}),(yt==="published"||yt==="pending_review"||yt==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${yt==="published"?"bg-green-500":yt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),ut&&c.jsx("button",{type:"button",onClick:()=>{Wt()},title:ks,"aria-label":ks,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"})]})}),At&&c.jsx("button",{onClick:Ct,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"})]})}),At&&c.jsx("button",{onClick:kt,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:()=>{le()&&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(bD(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?` · ${wf(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?` · ${wf(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?` · ${wf(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:ne,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(Gk,{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 ae=G?G.replace(/[/\\][^/\\]+$/,""):void 0,re=G&&!fo(G)?G:"",Xe=x.format;return re&&(Xe==="code"||Xe==="json"||Xe==="text")?c.jsx("div",{ref:ne,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(x_,{path:re,initialContent:x.content,language:rg(re,Xe),onDirtyChange:W})}):re&&(Xe==="markdown"||Xe==="html")?c.jsx("div",{ref:ne,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(D4,{path:re,content:x.content,format:Xe,basePath:ae,onHtmlSelection:rt,onDirtyChange:W})}):c.jsx("div",{ref:ne,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(Pf,{content:x.content,format:Xe,className:"text-fg-secondary text-sm",onHtmlSelection:rt,basePath:ae})})})(),x.mode==="artifact"&&c.jsx("div",{ref:ne,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(Pf,{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(sD,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?ae=>f(x.browserId,ae):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(uD,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:K,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:ae=>{if(!ae||!i){B(null);return}B({x:ae.x,y:ae.y,text:ae.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(Kk,{path:x.path,entries:x.entries,onNavigate:ae=>C(ae),onOpenFile:ae=>C(ae),onReveal:kt,onCopyPath:Ct}),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:kt,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:kt,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:Ct,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"})})]})]})]},`${Ue}#${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:ae=>{ae.preventDefault(),ae.stopPropagation(),ee(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&&Jt&&c.jsx(XC,{item:Jt,onClose:()=>R(!1),onShared:at})]})}function yD({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=jt(["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($s,{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 SD={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},wD={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 _D({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 kD({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}=jt(["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 ${wD[k.field]}`,children:b(SD[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(_D,{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:qm(k.createdAt,g.language),children:zm(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 CD=300,PD=48;function TD(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 QD(s,e,t,r=PD){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 $D(s,e,t={}){const r=t.limit??CD,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 TD(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=QD(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 jD(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 RD(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 ED="markus.scrollDebug";let _f=null,gv=!1;function AD(){if(!gv){try{_f=typeof localStorage<"u"&&localStorage.getItem(ED)==="1"}catch{_f=!1}gv=!0}return _f===!0}function Wi(s,e){AD()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function MD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function LD(s,e){return s.filter(t=>{if(!MD(t)||(t.details?.agentId??t.agentId)!==e.agentId)return!1;const i=t.details?.sessionId;return!(i&&e.sessionId&&i!==e.sessionId)})}const Ov={urgent:0,high:1,normal:2,low:3};function xv(s){return Ov[s??"normal"]??Ov.normal}function ND(s){return[...s].sort((e,t)=>{const r=xv(e.priority)-xv(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function DD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Nm(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 ID(s,e){return e?ND(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&DD(t)===e)):[]}const bv={sessionId:null,messageId:null};function BD(s){if(s.length===0)return bv;const e=new Set(s.map(Nm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Nm(n)))return bv;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 WD=[{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_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 XD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of WD){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 zD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function qD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const $_=16;function ZD(s,e,t=$_){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 VD(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 FD=S.lazy(()=>Xv(()=>import("./index-B8h1PPzP.js").then(s=>s.bl),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),nh={mind:"mind",files:"files",tools:"tools",memory:"memory"},cg=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Dm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function UD(s,e){const{labelKey:t}=qh(s);return t?e(t):s}function Im(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}=jt(["agent","common"]),u=Zm(),[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(()=>cg.map(Z=>({...Z,label:d(`agent:tabs.${Z.key}`)})),[d]),C=S.useMemo(()=>k.map(Z=>({id:Z.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=Jk(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const Z=T.current;if(!Z)return;Z.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 ce=X.agents.find(j=>j.markusAgentId===s);y(ce??null)}).catch(()=>{}),vt.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=qh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=Z=>h??nh[Z],B=Z=>x||nh[Z]?"overview":Z,U=nh[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($s,{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:UD(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:()=>Er.navigate(Gt.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:Z}=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 Um.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:Z}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(Z){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(Z)}),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(Z=>!x||Z.key==="overview").map(Z=>c.jsxs("button",{onClick:()=>O(Z.key),"data-active":g===Z.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===Z.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:Z.icon}),Z.label]},Z.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(Xo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function HD({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:Ym.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 mo({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(Wh,{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(()=>i0(a,n));S.useEffect(()=>{R(i0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const F=D.agents.find(se=>se.agentId===s.id);F&&l(F)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(F=>s.state.activeTaskIds?.includes(F.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(F=>{if(D)return;g(F.dataDir+"/agents/"+s.id);const se=F.agents.find(me=>me.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:q2}).then(F=>{D||d(F.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(us,{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(us,{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(us,{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(us,{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(us,{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:Z}=Z2(h),X=r0(U),ce=r0(Z),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,ce.total>0?r("agent:profilePage.overview.a2aRuns",{count:ce.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:Im(D2(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:oh(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:Dm(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(HD,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(mo,{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:Im(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)}),I2(p.subItems).map(D=>{const F=W2(D.name);return c.jsx(Ks,{label:F?r(F):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(mo,{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))})]}),ce.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:ce.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&&ce.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(mo,{children:c.jsx(pI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(mo,{children:c.jsx(JD,{agentId:s.id})}),T==="tools"&&c.jsx(mo,{children:c.jsx(iI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(mo,{children:[c.jsx(oI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(nI,{agentId:s.id})})]})]})}function YD(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 QD(s,e,t,r=PD){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 $D(s,e,t={}){const r=t.limit??CD,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 TD(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=QD(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 jD(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 RD(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 ED="markus.scrollDebug";let _f=null,gv=!1;function AD(){if(!gv){try{_f=typeof localStorage<"u"&&localStorage.getItem(ED)==="1"}catch{_f=!1}gv=!0}return _f===!0}function Wi(s,e){AD()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function MD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function LD(s,e){return s.filter(t=>{if(!MD(t)||(t.details?.agentId??t.agentId)!==e.agentId)return!1;const i=t.details?.sessionId;return!(i&&e.sessionId&&i!==e.sessionId)})}const Ov={urgent:0,high:1,normal:2,low:3};function xv(s){return Ov[s??"normal"]??Ov.normal}function ND(s){return[...s].sort((e,t)=>{const r=xv(e.priority)-xv(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function DD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Nm(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 ID(s,e){return e?ND(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&DD(t)===e)):[]}const bv={sessionId:null,messageId:null};function BD(s){if(s.length===0)return bv;const e=new Set(s.map(Nm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Nm(n)))return bv;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 WD=[{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_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 XD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of WD){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 zD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function qD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const $_=16;function ZD(s,e,t=$_){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 VD(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 FD=S.lazy(()=>Xv(()=>import("./index-Dt7RN5t2.js").then(s=>s.bl),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),nh={mind:"mind",files:"files",tools:"tools",memory:"memory"},cg=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Dm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function UD(s,e){const{labelKey:t}=qh(s);return t?e(t):s}function Im(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}=jt(["agent","common"]),u=Zm(),[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(()=>cg.map(Z=>({...Z,label:d(`agent:tabs.${Z.key}`)})),[d]),C=S.useMemo(()=>k.map(Z=>({id:Z.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=Jk(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const Z=T.current;if(!Z)return;Z.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 ce=X.agents.find(j=>j.markusAgentId===s);y(ce??null)}).catch(()=>{}),vt.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=qh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=Z=>h??nh[Z],B=Z=>x||nh[Z]?"overview":Z,U=nh[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($s,{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:UD(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:()=>Er.navigate(Gt.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:Z}=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 Um.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:Z}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(Z){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(Z)}),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(Z=>!x||Z.key==="overview").map(Z=>c.jsxs("button",{onClick:()=>O(Z.key),"data-active":g===Z.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===Z.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:Z.icon}),Z.label]},Z.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(Xo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function HD({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:Ym.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 mo({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(Wh,{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(()=>i0(a,n));S.useEffect(()=>{R(i0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const F=D.agents.find(se=>se.agentId===s.id);F&&l(F)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(F=>s.state.activeTaskIds?.includes(F.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(F=>{if(D)return;g(F.dataDir+"/agents/"+s.id);const se=F.agents.find(me=>me.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:q2}).then(F=>{D||d(F.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(us,{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(us,{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(us,{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(us,{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(us,{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:Z}=Z2(h),X=r0(U),ce=r0(Z),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,ce.total>0?r("agent:profilePage.overview.a2aRuns",{count:ce.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:Im(D2(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:oh(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:Dm(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(HD,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(mo,{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:Im(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)}),I2(p.subItems).map(D=>{const F=W2(D.name);return c.jsx(Ks,{label:F?r(F):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(mo,{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))})]}),ce.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:ce.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&&ce.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(mo,{children:c.jsx(pI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(mo,{children:c.jsx(JD,{agentId:s.id})}),T==="tools"&&c.jsx(mo,{children:c.jsx(iI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(mo,{children:[c.jsx(oI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(nI,{agentId:s.id})})]})]})}function YD(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 GD({agent:s,template:e,templateId:t}){const{t:r}=jt(["agent","common"]),i=S.useMemo(()=>YD(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 KD(s,e){const t=s.split(`
61
61
  `),r=e.split(`
@@ -72,7 +72,7 @@ ${ae}
72
72
  `+ce.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.";Er.navigate(Gt.TEAM,{agentId:s,prefillMessage:j})},L=async Z=>{if(y?.file===Z){k(null);return}try{const X=await te.agents.roleDiff(s,Z);X.agentContent!=null&&X.templateContent!=null&&k({file:Z,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=Z=>{const X=M[Z];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):Z},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(Z=>Z.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(Z=>Z.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(us,{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(Z=>{const X=T.some(ce=>ce.file===Z.name);return c.jsxs("button",{onClick:()=>P(Z.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===Z.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[Z.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.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(GD,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(eI,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{h(Z),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(Xh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function eI({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(FD,{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 tI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function sI({tools:s}){const{t:e}=jt(["agent","common"]),t=XD(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(us,{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=iC(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=tI(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(nC,{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 rI({agent:s}){const{t:e}=jt(["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(us,{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(Xh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function iI({tools:s,agent:e}){const{t}=jt(["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(sI,{tools:s}):c.jsx(rI,{agent:e})]})}function nI({agentId:s}){const{t:e}=jt(["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(us,{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(us,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Xh,{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(us,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Xh,{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 Z of m)Z.role==="tool"&&Z.toolCallId&&U.set(Z.toolCallId,Z.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(Z=>Z.role!=="tool").map((Z,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.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 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(jo,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[Z.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(jo,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(ce=>{let j;try{j=JSON.parse(ce.arguments)}catch{}const W={tool:ce.name,status:"done",args:j,result:U.get(ce.id)};return c.jsx(tC,{entry:{type:"tool",info:W}},ce.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(us,{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(us,{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 oI({agentId:s,initialData:e}){const{t}=jt(["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(()=>vt.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(us,{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(lI,{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(us,{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(us,{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(us,{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(jo,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(us,{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(Wh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(us,{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 aI({taskId:s,isLive:e}){const{t}=jt("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=vt.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=vt.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=>rC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Wh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=jt("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?vt.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=>sC(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 us({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 lI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=jt(["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 Xh({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"},cI={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"},hI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Dc={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},dI=["all","interaction","task","notification","system"],uI={interaction:["human_chat","a2a_message","mention"],task:["task_status_update","task_comment","requirement_comment","review_request","session_reply"],notification:["requirement_update"],system:["system_event","heartbeat","daily_report","memory_consolidation"]},fI={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"},mI={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 kf(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=Dm(d,e),p=Dm(u,e),v=mI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=kf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=kf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=kf(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 pI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=jt(["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 ne=u==="all"?void 0:u,V=p==="all"?void 0:p,[A,K]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:ne,status:V})]);a(A),l(K),_((K.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),Z=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,ne=p==="all"?void 0:p;try{const V=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:ne});l(A=>A?{...A,history:[...A.history,...V.history]}:V),_((V.history?.length??0)>=L)}catch{}},[s,o,u,p]),ce=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(ne=>ne.id===O)){j.current=!1;const ne=document.getElementById(`mbx-${O}`);if(ne){setTimeout(()=>ne.scrollIntoView({behavior:"smooth",block:"center"}),100);const V=setTimeout(()=>m(null),3e3);return()=>clearTimeout(V)}}else P&&!j.current&&(j.current=!0,(async()=>{let ne=o?.history??[],V=P;for(;V;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:ne.length}),K=[...ne,...A.history];ne=K,V=(A.history?.length??0)>=L;const Y=A.history.some(le=>le.id===O);if(l(le=>le?{...le,history:K}:A),_(V),Y||!V)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const ne=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},V=[vt.on("agent:mailbox",ne),vt.on("agent:decision",ne),vt.on("agent:attention",ne),vt.on("agent:focus",ne),vt.on("agent:update",ne),vt.on("agent:triage",ne)];return()=>{z&&clearTimeout(z),V.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=qh(t).running,F=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=F==="idle"&&o?.history?.some(z=>z.status==="processing"),me=(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 ${hI[F]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${F}`)}):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:[Dc[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")]})]})})():me?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…"})}):F==="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:()=>{ce()},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,ne=z.length>M,V=ne&&!x?z.slice(0,M):z,A=z.reduce((K,Y)=>(K[Y.sourceType]=(K[Y.sourceType]??0)+1,K),{});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(([K,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Dc[K]??"●"," ",Y]},K))})]}),c.jsxs("div",{className:"space-y-1",children:[V.map((K,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:Dc[K.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${$v[K.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[K.priority]??K.priority}`,{defaultValue:`P${K.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:K.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(K.queuedAt).toLocaleTimeString()})]},K.id)),ne&&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=ZD(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:$_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(ne=>{const V=VD(ne.updatedAt),A=i(`agent:profilePage.relative.${V.unit==="seconds"?"secondsAgo":V.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:V.count,hours:V.count}),K=ne.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:ne.key}),c.jsxs("span",{className:`text-[10px] ${K}`,children:["[",ne.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:ne.text.length>500?ne.text.slice(0,500)+"…":ne.text})]},ne.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(Wh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const ne=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,V=U2(n.lastTriage);return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${ne?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!ne,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 ${V.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-3 text-fg-tertiary"}`,children:V.isBatch?i("agent:profilePage.mind.batchSize",{count:V.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:dI.map(z=>{const ne=o?.sourceTypeCounts,V=z==="all"?ne?Object.values(ne).reduce((A,K)=>A+K,0):void 0:ne?(uI[z]??[]).reduce((A,K)=>A+(ne[K]??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}`),V!=null&&V>0&&c.jsx("span",{className:"ml-1 opacity-60",children:V})]},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 ne=o?.statusCounts,V=z.key==="all"?ne?Object.values(ne).reduce((A,K)=>A+K,0):void 0:ne?.[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}`),V!=null&&V>0&&c.jsx("span",{className:"ml-1 opacity-60",children:V})]},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 ne=b===z.id,V=Dc[z.sourceType]??"●",A=jv(z,i),K=qD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,le=z.metadata?.senderRole,G=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${G?"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(ne?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:ne?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${K==="stale"?"bg-amber-400/70":fI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:V}),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 ${ne?"":"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 ${ne?"":"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:Im(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&&zD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:be=>{be.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")]})]}),ne&&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}),le&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",le,")"]})]}),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(be=>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 ${cI[be.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:be.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:be.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(be.createdAt).toLocaleTimeString()})]},be.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:()=>{Z(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(aI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Wh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):K==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):K==="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(Xo,{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 ne=0;const V=()=>{ne+=1,U(),ne<8&&window.setTimeout(V,750)};V()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=jt(["agent","common"]),t=zh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(F2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Er.navigate(Gt.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=vt.on("deliverable:created",()=>l()),d=vt.on("deliverable:updated",()=>l()),u=vt.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=eC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=SO[h.status]??SO.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 gI=S.lazy(()=>Xv(()=>import("./index-B8h1PPzP.js").then(s=>s.bl),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),hg=[{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}=jt("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),Z=S.useRef(null),X=S.useRef(null),[ce,j]=S.useState(!1),[W,D]=S.useState(!1),[F,se]=S.useState(""),[me,z]=S.useState(""),[ne,V]=S.useState(!1),[A,K]=S.useState([]),Y=S.useRef(null),le=S.useCallback(async()=>{try{const pe=(await te.teams.list()).teams.find(Ze=>Ze.id===s);pe&&l(pe);const ee=await te.teams.status(s);K(ee.agents)}catch{}finally{d(!1)}},[s]),G=S.useCallback(async()=>{f(!0);try{const Oe=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(Oe.content)}catch{x("")}try{const Oe=await te.teams.getFile(s,"NORMS.md");k(Oe.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),le(),G()},[s,le,G]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const be=async(Oe,pe)=>{j(!0);try{await te.teams.updateFile(s,Oe,pe),Oe==="ANNOUNCEMENT.md"?(x(pe),P(!1)):(k(pe),T(!1))}catch{}j(!1)},je=async()=>{F.trim()&&(await te.teams.update(s,{name:F.trim()}),D(!1),le())},we=async()=>{await te.teams.update(s,{description:me}),V(!1),le()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(LC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ue=o.members.find(Oe=>Oe.agentRole==="manager"),Qe=A.filter(Oe=>Oe.status!=="offline").length,Ye=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ye?"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:Ue?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const pe=A.find(rt=>rt.id===Oe.id),ee=Ev[pe?.status??"offline"]??"bg-gray-500",Ze=Oe.type==="agent";return c.jsxs("div",{onClick:()=>Ze&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ze&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx($s,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${ee}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:pe?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),Ze&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ce,onSave:()=>be("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Ic,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:Z,saving:ce,onSave:()=>be("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:F,onChange:Oe=>se(Oe.target.value),onKeyDown:Oe=>Oe.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"}),ne?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:me,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick: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:()=>V(!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??""),V(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const Ot=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${Ot?"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:Oe}=await te.teams.getFilesMap(o.id),pe=o.members.filter(Ze=>Ze.type==="agent"),ee={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:pe.map(Ze=>({name:Ze.name,roleName:Ze.role,role:Ze.agentRole??"worker",count:1,skills:[]}))}};await Um.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:ee,files:Oe}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Oe){v({title:"Hub",message:`Failed to publish: ${Oe}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:hg.map(Oe=>c.jsxs("button",{onClick:()=>g(Oe.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===Oe.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Oe.icon," ",a(Oe.labelKey)]},Oe.key))})]}),c.jsxs("div",{className:`${Ot?"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:Ue?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const pe=A.find(rt=>rt.id===Oe.id),ee=Ev[pe?.status??"offline"]??"bg-gray-500",Ze=Oe.type==="agent";return c.jsxs("div",{onClick:()=>Ze&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ze&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx($s,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${ee}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:pe?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),Ze&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ce,onSave:()=>be("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Ic,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:Z,saving:ce,onSave:()=>be("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:F,onChange:Oe=>se(Oe.target.value),onKeyDown:Oe=>Oe.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"}),ne?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:me,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick: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:()=>V(!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??""),V(!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(Xo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Ic({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(gI,{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 OI=["chat","overview","deliverables"],xI=["chat","overview","announcements","norms","settings"];function bI(s,e){if(s==="chat")return e("page.chatTitle");if(cg.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=hg.find(i=>i.key===s);return r?e(r.labelKey):s}function vI(s){if(s==="chat")return"💬";const e=cg.find(r=>r.key===s);if(e)return e.icon;const t=hg.find(r=>r.key===s);return t?t.icon:""}function Xi(s){return s!=="chat"}function Ea(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const yI=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class jr{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>jr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){const r=this.view.get(e);if(r!==t&&(r===void 0||r===jr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(jr.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(jr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){yI(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(jr.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<=jr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=jr.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>jr.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 et=jr.NEW_CHAT_ID;function SI(s){const e=S.useRef(new jr),[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 Cf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function wI(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Oe=>{if(Oe)for(const[pe,ee]of e.current)ee===Oe&&e.current.delete(pe)},i=Oe=>{if(Oe)for(const[pe,ee]of t.current)ee===Oe&&t.current.delete(pe)},n=Oe=>{const pe=e.current.get(Oe);pe&&(pe.abort(),e.current.delete(Oe));const ee=t.current.get(Oe);ee&&(ee.abort(),t.current.delete(Oe))},a=Oe=>{const pe=e.current.get(et);pe&&e.current.size===1&&(e.current.delete(et),e.current.set(Oe,pe))},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,thinkingTimeoutRef:B,sessionSwitchSeqRef:U,setSending:Z,setActivities:X,setInput:ce,setChatContext:j,setPendingImages:W,setMentionDropdown:D,setChatReplyTo:F,setActiveSessionId:se,setStoredActiveSession:me,setOpenSessionTabs:z,setSessions:ne,setLoadingChat:V,setWindowBounds:A,setThinkingAgents:K,makeConvKey:Y,makeDmChannel:le,addRecentMsgId:G,resumeChatScrollFollow:be,loadSessions:je}=s,{t:we}=s,Ue=S.useCallback(async(Oe,pe)=>{const ee=U.current,Ze=g.current===pe&&(b(pe)?.length??0)===0;Ze&&V(!0);try{const{count:rt,hasMore:kt,oldestCursor:Ct}=await E(Oe,pe,async()=>{const Bt=await te.sessions.getMessages(Oe,50);return{messages:oC(Bt.messages.map(ah).filter(Pt=>Pt.sender!=="agent"||Pt.text||Pt.segments&&Pt.segments.length>0||Pt.isStreaming)),hasMore:Bt.hasMore,oldestCursor:Bt.messages[0]?new Date(Bt.messages[0].createdAt).toISOString():null}});return A(Oe,{hasMore:kt,oldestCursor:Ct}),rt}finally{Ze&&g.current===pe&&U.current===ee&&V(!1)}},[E,b,U]),Qe=()=>{const Oe=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Oe){const pe=Cf(f.current.activeSessionId,et);pe.kind==="cancel"&&te.agents.cancelProcessing(Oe,pe.target).catch(()=>{})}n(f.current.activeSessionId??et),Oe&&f.current.activeSessionId&&f.current.activeSessionId!==et&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ye=S.useCallback(async(Oe,pe,ee)=>{if(!Oe||!pe||pe===et||l.current.has(pe))return;let Ze=null;try{const rt=e.current.get(pe);if(rt&&!rt.signal.aborted&&T(ee)?.has(pe)){g.current===ee&&Z(!0);return}const kt=()=>{aC({liveSessions:T(ee),sessionId:pe,placeholderId:et})&&(P(ee,pe),g.current===ee&&(Z(!1),O(ee,de=>cu(de),pe)))},Ct=`${Oe}:${pe}`,Bt=o.current.get(Ct)??0;if(Date.now()-Bt<1500)return;o.current.set(Ct,Date.now());let pt;const Pt=await te.sessions.streamStatus(Oe,pe);Pt.messageId&&(pt=Pt.messageId);const Ae=b(ee)??[],Wt=Pt.status==="streaming",ut=lC(Ae,{expectedMessageId:Pt.messageId,allowCurrentTurnPartial:Wt}),ks=!!Pt.active&&(Pt.status==="done"||Pt.status==="error")&&!!ut?.isStreaming;if(JO({aborted:!1,sawTerminal:ks,serverStatus:e0(Pt.status)})==="finalize"){kt();return}o.current.set(Ct,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),Ze=new AbortController,t.current.set(pe,Ze),y(ee),Z(!0),_(ee,pe);let Ne=ut?.id;if(!ut||ut.isError)Ne=`reattach_${Date.now()}`,O(ee,de=>[...de,{id:Ne,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],pe);else{const de=(ut.segments??[]).filter(Se=>Se.type==="tool").map(Se=>Se.status==="stopped"||Se.status==="running"?{...Se,status:"running"}:Se);O(ee,Se=>Se.map(_e=>_e.id===ut.id?{..._e,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:_e),pe)}const Jt=de=>{g.current===ee&&(u.current=Date.now(),m(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(J=>J.id===Ne):-1,Fe=Ie>=0?Ie:_e.map((J,$e)=>({m:J,j:$e})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];return _e[Fe]={...ze,text:(ze.text??"")+de,segments:wO(ze.segments??[],de),isStreaming:!0},_e},pe))},at=de=>{g.current===ee&&(u.current=Date.now(),m(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(J=>J.id===Ne):-1,Fe=Ie>=0?Ie:_e.map((J,$e)=>({m:J,j:$e})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];return _e[Fe]={...ze,segments:_O(ze.segments??[],de),isStreaming:!0},_e},pe))},ft=de=>{if(g.current===ee&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(ee,{...de,phase:de.phase,ts:Date.now()},pe),de.phase==="start"){const Se=`${de.tool}_${Date.now()}`,_e=new Date().toISOString(),Ie=Fe=>{const ze=[...Fe];for(let J=ze.length-1;J>=0;J--){const $e=ze[J];if($e.type==="tool"&&$e.tool===de.tool&&($e.status==="running"||$e.status==="stopped"))return ze[J]={...$e,status:"running",args:de.arguments??$e.args},ze}return ze.push({type:"tool",key:Se,tool:de.tool,status:"running",args:de.arguments,createdAt:_e}),ze};O(ee,Fe=>{const ze=[...Fe],J=Ne?ze.findIndex(Pe=>Pe.id===Ne):-1;if(J<0)return Fe;const $e=Ie(ze[J].segments??[]),Te=ze[J].committedSegments,ge=Te&&Ie(Te);return ze[J]={...ze[J],segments:$e,committedSegments:ge,isStreaming:!0},ze},pe)}else if(de.phase==="end"){const Se=new Date().toISOString(),_e=Ie=>{const Fe=[...Ie];for(let ze=Fe.length-1;ze>=0;ze--){const J=Fe[ze];if(J.type==="tool"&&J.tool===de.tool&&(J.status==="running"||J.status==="stopped")){Fe[ze]={...J,status:de.success===!1?"error":"done",args:de.arguments??J.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:Se};break}}return Fe};O(ee,Ie=>{const Fe=[...Ie],ze=Ne?Fe.findIndex(ge=>ge.id===Ne):-1;if(ze<0)return Ie;const J=_e(Fe[ze].segments??[]),$e=Fe[ze].committedSegments,Te=$e&&_e($e);return Fe[ze]={...Fe[ze],segments:J,committedSegments:Te,isStreaming:!0},Fe},pe)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const Se=_e=>{const Ie=[..._e];for(let Fe=Ie.length-1;Fe>=0;Fe--){const ze=Ie[Fe];if(ze.type==="tool"&&(ze.tool==="spawn_subagent"||ze.tool==="spawn_subagents")&&(ze.status==="running"||ze.status==="stopped")){Ie[Fe]={...ze,status:"running",subagentLogs:kO(ze.subagentLogs,de.subagentEvent)};break}}return Ie};m(ee,_e=>{const Ie=[..._e],Fe=Ne?Ie.findIndex(Te=>Te.id===Ne):-1;if(Fe<0)return _e;const ze=Se(Ie[Fe].segments??[]),J=Ie[Fe].committedSegments,$e=J&&Se(J);return Ie[Fe]={...Ie[Fe],segments:ze,committedSegments:$e,isStreaming:!0},Ie},pe)}}},Tt=de=>{g.current===ee&&(u.current=Date.now(),O(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(ze=>ze.id===Ne):-1;if(Ie<0)return Se;const Fe=[..._e[Ie].committedSegments??[]];if(de.type==="thinking_commit")Fe.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")Fe.push({type:"text",content:de.content,createdAt:de.createdAt});else return Se;return _e[Ie]={..._e[Ie],committedSegments:Fe,isStreaming:!0},_e},pe))},yt=de=>{if(g.current!==ee)return;u.current=Date.now();const Se=(de.segments??[]).map((_e,Ie)=>_e.type==="tool"?{type:"tool",key:`${_e.tool}_${Ie}`,tool:_e.tool??"tool",status:_e.status==="error"?"error":_e.status==="running"||_e.status==="stopped"?"running":"done",args:_e.arguments,result:_e.result,error:_e.error,durationMs:_e.durationMs,createdAt:_e.createdAt,..._e.subagentLogs?.length?{subagentLogs:_e.subagentLogs}:{}}:{type:"text",content:_e.content??"",thinking:_e.thinking,createdAt:_e.createdAt});O(ee,_e=>{const Ie=[..._e],Fe=Ne?Ie.findIndex(ze=>ze.id===Ne):-1;return Fe<0?_e:(Ie[Fe]={...Ie[Fe],text:de.content||Ie[Fe].text,segments:Se,committedSegments:Se,isStreaming:!0,isStopped:!1},Ie)},pe);for(const _e of Se)_e.type==="tool"&&x(ee,{tool:_e.tool,phase:_e.status==="running"||_e.status==="stopped"?"start":"end",success:_e.status!=="error",arguments:_e.args,result:_e.result,error:_e.error,durationMs:_e.durationMs,ts:Date.now()},pe)},ae=8;let re=null;const Xe=de=>{g.current===ee&&O(ee,Se=>{const _e=Se.map((Fe,ze)=>({m:Fe,j:ze})).reverse().find(Fe=>Fe.m.sender==="agent"&&Fe.m.isStreaming)?.j??-1;if(_e<0||Se[_e].reconnecting===de)return Se;const Ie=[...Se];return Ie[_e]={...Ie[_e],reconnecting:de},Ie},pe)};for(let de=1;de<=ae;de++){if(Ze.signal.aborted)return;try{re=await te.sessions.reattachStream(Oe,pe,{onChunk:Jt,onThinking:at,onActivity:ft,onCommit:Tt,onSnapshot:yt},Ze.signal,0)}catch(_e){if(Ze.signal.aborted)throw _e;re=null}if(!re||!re.attached){re=null;break}if(re.terminal)break;Xe(!0);const Se=await te.sessions.streamStatus(Oe,pe).catch(()=>null);if(Se?.messageId&&(pt=Se.messageId),!Se||!Se.active||Se.status==="not_found"||Se.status==="idle"){Xe(!1),re=null;break}await new Promise(_e=>setTimeout(_e,Math.min(800*de,4e3))),Xe(!1)}if(!re){k(ee),P(ee,pe),g.current===ee&&(Z(!1),pt&&Ne&&O(ee,de=>wa(de,Ne,pt),pe),Ue(pe,ee).catch(()=>{}).finally(()=>{O(ee,de=>cu(de,"done"),pe)})),i(Ze);return}if(g.current===ee){let de;O(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex($e=>$e.id===Ne):-1,Fe=Ie>=0?Ie:_e.map(($e,Te)=>({m:$e,j:Te})).reverse().find($e=>$e.m.sender==="agent"&&$e.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];if(!ze.isStreaming)return Se;de=ze.id;const J=re.segments?.length?CO(re.segments,ze.segments):void 0;return _e[Fe]={...ze,text:re.content||ze.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...J?{segments:J,committedSegments:J}:{}},_e},pe),de&&O(ee,Se=>wa(Se,de,re.messageId),pe),Z(!1)}k(ee),P(ee,pe),i(Ze)}catch(rt){const kt=Ze?[...t.current.values()].includes(Ze):!1;i(Ze),k(ee);const Ct=l.current.has(pe);if(Ct&&P(ee,pe),g.current===ee&&(Z(!1),kt&&Ct&&O(ee,Bt=>cu(Bt),pe)),rt instanceof Error&&rt.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Ot=S.useCallback(async(Oe,pe)=>{const ee=f.current,Ze=!Oe&&ee.chatContext.length>0?ee.chatContext.map(At=>At.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.";Er.navigate(Gt.TEAM,{agentId:s,prefillMessage:j})},L=async Z=>{if(y?.file===Z){k(null);return}try{const X=await te.agents.roleDiff(s,Z);X.agentContent!=null&&X.templateContent!=null&&k({file:Z,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=Z=>{const X=M[Z];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):Z},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(Z=>Z.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(Z=>Z.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(us,{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(Z=>{const X=T.some(ce=>ce.file===Z.name);return c.jsxs("button",{onClick:()=>P(Z.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===Z.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[Z.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.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(GD,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(eI,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{h(Z),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(Xh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function eI({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(FD,{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 tI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function sI({tools:s}){const{t:e}=jt(["agent","common"]),t=XD(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(us,{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=iC(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=tI(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(nC,{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 rI({agent:s}){const{t:e}=jt(["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(us,{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(Xh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function iI({tools:s,agent:e}){const{t}=jt(["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(sI,{tools:s}):c.jsx(rI,{agent:e})]})}function nI({agentId:s}){const{t:e}=jt(["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(us,{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(us,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Xh,{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(us,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Xh,{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 Z of m)Z.role==="tool"&&Z.toolCallId&&U.set(Z.toolCallId,Z.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(Z=>Z.role!=="tool").map((Z,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.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 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(jo,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[Z.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(jo,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(ce=>{let j;try{j=JSON.parse(ce.arguments)}catch{}const W={tool:ce.name,status:"done",args:j,result:U.get(ce.id)};return c.jsx(tC,{entry:{type:"tool",info:W}},ce.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(us,{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(us,{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 oI({agentId:s,initialData:e}){const{t}=jt(["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(()=>vt.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(us,{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(lI,{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(us,{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(us,{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(us,{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(jo,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(us,{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(Wh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(us,{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 aI({taskId:s,isLive:e}){const{t}=jt("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=vt.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=vt.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=>rC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Wh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=jt("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?vt.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=>sC(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 us({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 lI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=jt(["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 Xh({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"},cI={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"},hI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Dc={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},dI=["all","interaction","task","notification","system"],uI={interaction:["human_chat","a2a_message","mention"],task:["task_status_update","task_comment","requirement_comment","review_request","session_reply"],notification:["requirement_update"],system:["system_event","heartbeat","daily_report","memory_consolidation"]},fI={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"},mI={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 kf(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=Dm(d,e),p=Dm(u,e),v=mI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=kf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=kf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=kf(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 pI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=jt(["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 ne=u==="all"?void 0:u,V=p==="all"?void 0:p,[A,K]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:ne,status:V})]);a(A),l(K),_((K.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),Z=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,ne=p==="all"?void 0:p;try{const V=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:ne});l(A=>A?{...A,history:[...A.history,...V.history]}:V),_((V.history?.length??0)>=L)}catch{}},[s,o,u,p]),ce=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(ne=>ne.id===O)){j.current=!1;const ne=document.getElementById(`mbx-${O}`);if(ne){setTimeout(()=>ne.scrollIntoView({behavior:"smooth",block:"center"}),100);const V=setTimeout(()=>m(null),3e3);return()=>clearTimeout(V)}}else P&&!j.current&&(j.current=!0,(async()=>{let ne=o?.history??[],V=P;for(;V;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:ne.length}),K=[...ne,...A.history];ne=K,V=(A.history?.length??0)>=L;const Y=A.history.some(le=>le.id===O);if(l(le=>le?{...le,history:K}:A),_(V),Y||!V)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const ne=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},V=[vt.on("agent:mailbox",ne),vt.on("agent:decision",ne),vt.on("agent:attention",ne),vt.on("agent:focus",ne),vt.on("agent:update",ne),vt.on("agent:triage",ne)];return()=>{z&&clearTimeout(z),V.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=qh(t).running,F=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=F==="idle"&&o?.history?.some(z=>z.status==="processing"),me=(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 ${hI[F]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${F}`)}):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:[Dc[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")]})]})})():me?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…"})}):F==="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:()=>{ce()},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,ne=z.length>M,V=ne&&!x?z.slice(0,M):z,A=z.reduce((K,Y)=>(K[Y.sourceType]=(K[Y.sourceType]??0)+1,K),{});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(([K,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Dc[K]??"●"," ",Y]},K))})]}),c.jsxs("div",{className:"space-y-1",children:[V.map((K,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:Dc[K.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${$v[K.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[K.priority]??K.priority}`,{defaultValue:`P${K.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:K.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(K.queuedAt).toLocaleTimeString()})]},K.id)),ne&&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=ZD(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:$_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(ne=>{const V=VD(ne.updatedAt),A=i(`agent:profilePage.relative.${V.unit==="seconds"?"secondsAgo":V.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:V.count,hours:V.count}),K=ne.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:ne.key}),c.jsxs("span",{className:`text-[10px] ${K}`,children:["[",ne.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:ne.text.length>500?ne.text.slice(0,500)+"…":ne.text})]},ne.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(Wh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const ne=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,V=U2(n.lastTriage);return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${ne?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!ne,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 ${V.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-3 text-fg-tertiary"}`,children:V.isBatch?i("agent:profilePage.mind.batchSize",{count:V.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:dI.map(z=>{const ne=o?.sourceTypeCounts,V=z==="all"?ne?Object.values(ne).reduce((A,K)=>A+K,0):void 0:ne?(uI[z]??[]).reduce((A,K)=>A+(ne[K]??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}`),V!=null&&V>0&&c.jsx("span",{className:"ml-1 opacity-60",children:V})]},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 ne=o?.statusCounts,V=z.key==="all"?ne?Object.values(ne).reduce((A,K)=>A+K,0):void 0:ne?.[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}`),V!=null&&V>0&&c.jsx("span",{className:"ml-1 opacity-60",children:V})]},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 ne=b===z.id,V=Dc[z.sourceType]??"●",A=jv(z,i),K=qD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,le=z.metadata?.senderRole,G=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${G?"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(ne?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:ne?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${K==="stale"?"bg-amber-400/70":fI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:V}),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 ${ne?"":"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 ${ne?"":"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:Im(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&&zD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:be=>{be.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")]})]}),ne&&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}),le&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",le,")"]})]}),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(be=>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 ${cI[be.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:be.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:be.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(be.createdAt).toLocaleTimeString()})]},be.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:()=>{Z(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(aI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Wh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):K==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):K==="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(Xo,{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 ne=0;const V=()=>{ne+=1,U(),ne<8&&window.setTimeout(V,750)};V()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=jt(["agent","common"]),t=zh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(F2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Er.navigate(Gt.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=vt.on("deliverable:created",()=>l()),d=vt.on("deliverable:updated",()=>l()),u=vt.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=eC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=SO[h.status]??SO.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 gI=S.lazy(()=>Xv(()=>import("./index-Dt7RN5t2.js").then(s=>s.bl),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),hg=[{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}=jt("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),Z=S.useRef(null),X=S.useRef(null),[ce,j]=S.useState(!1),[W,D]=S.useState(!1),[F,se]=S.useState(""),[me,z]=S.useState(""),[ne,V]=S.useState(!1),[A,K]=S.useState([]),Y=S.useRef(null),le=S.useCallback(async()=>{try{const pe=(await te.teams.list()).teams.find(Ze=>Ze.id===s);pe&&l(pe);const ee=await te.teams.status(s);K(ee.agents)}catch{}finally{d(!1)}},[s]),G=S.useCallback(async()=>{f(!0);try{const Oe=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(Oe.content)}catch{x("")}try{const Oe=await te.teams.getFile(s,"NORMS.md");k(Oe.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),le(),G()},[s,le,G]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const be=async(Oe,pe)=>{j(!0);try{await te.teams.updateFile(s,Oe,pe),Oe==="ANNOUNCEMENT.md"?(x(pe),P(!1)):(k(pe),T(!1))}catch{}j(!1)},je=async()=>{F.trim()&&(await te.teams.update(s,{name:F.trim()}),D(!1),le())},we=async()=>{await te.teams.update(s,{description:me}),V(!1),le()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(LC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ue=o.members.find(Oe=>Oe.agentRole==="manager"),Qe=A.filter(Oe=>Oe.status!=="offline").length,Ye=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ye?"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:Ue?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const pe=A.find(rt=>rt.id===Oe.id),ee=Ev[pe?.status??"offline"]??"bg-gray-500",Ze=Oe.type==="agent";return c.jsxs("div",{onClick:()=>Ze&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ze&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx($s,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${ee}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:pe?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),Ze&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ce,onSave:()=>be("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Ic,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:Z,saving:ce,onSave:()=>be("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:F,onChange:Oe=>se(Oe.target.value),onKeyDown:Oe=>Oe.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"}),ne?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:me,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick: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:()=>V(!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??""),V(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const Ot=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${Ot?"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:Oe}=await te.teams.getFilesMap(o.id),pe=o.members.filter(Ze=>Ze.type==="agent"),ee={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:pe.map(Ze=>({name:Ze.name,roleName:Ze.role,role:Ze.agentRole??"worker",count:1,skills:[]}))}};await Um.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:ee,files:Oe}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(Oe){v({title:"Hub",message:`Failed to publish: ${Oe}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:hg.map(Oe=>c.jsxs("button",{onClick:()=>g(Oe.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===Oe.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[Oe.icon," ",a(Oe.labelKey)]},Oe.key))})]}),c.jsxs("div",{className:`${Ot?"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:Ue?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(Oe=>{const pe=A.find(rt=>rt.id===Oe.id),ee=Ev[pe?.status??"offline"]??"bg-gray-500",Ze=Oe.type==="agent";return c.jsxs("div",{onClick:()=>Ze&&n?.(Oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ze&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx($s,{name:Oe.name,avatarUrl:Oe.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:Oe.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${ee}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:pe?.status??"offline"}),Oe.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[Oe.role," · ",Oe.type]})]}),Ze&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},Oe.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ce,onSave:()=>be("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Ic,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:Z,saving:ce,onSave:()=>be("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:F,onChange:Oe=>se(Oe.target.value),onKeyDown:Oe=>Oe.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"}),ne?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:me,onChange:Oe=>z(Oe.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick: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:()=>V(!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??""),V(!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(Xo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Ic({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(gI,{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 OI=["chat","overview","deliverables"],xI=["chat","overview","announcements","norms","settings"];function bI(s,e){if(s==="chat")return e("page.chatTitle");if(cg.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=hg.find(i=>i.key===s);return r?e(r.labelKey):s}function vI(s){if(s==="chat")return"💬";const e=cg.find(r=>r.key===s);if(e)return e.icon;const t=hg.find(r=>r.key===s);return t?t.icon:""}function Xi(s){return s!=="chat"}function Ea(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const yI=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class jr{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>jr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){const r=this.view.get(e);if(r!==t&&(r===void 0||r===jr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(jr.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(jr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){yI(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(jr.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<=jr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=jr.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>jr.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 et=jr.NEW_CHAT_ID;function SI(s){const e=S.useRef(new jr),[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 Cf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function wI(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Oe=>{if(Oe)for(const[pe,ee]of e.current)ee===Oe&&e.current.delete(pe)},i=Oe=>{if(Oe)for(const[pe,ee]of t.current)ee===Oe&&t.current.delete(pe)},n=Oe=>{const pe=e.current.get(Oe);pe&&(pe.abort(),e.current.delete(Oe));const ee=t.current.get(Oe);ee&&(ee.abort(),t.current.delete(Oe))},a=Oe=>{const pe=e.current.get(et);pe&&e.current.size===1&&(e.current.delete(et),e.current.set(Oe,pe))},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,thinkingTimeoutRef:B,sessionSwitchSeqRef:U,setSending:Z,setActivities:X,setInput:ce,setChatContext:j,setPendingImages:W,setMentionDropdown:D,setChatReplyTo:F,setActiveSessionId:se,setStoredActiveSession:me,setOpenSessionTabs:z,setSessions:ne,setLoadingChat:V,setWindowBounds:A,setThinkingAgents:K,makeConvKey:Y,makeDmChannel:le,addRecentMsgId:G,resumeChatScrollFollow:be,loadSessions:je}=s,{t:we}=s,Ue=S.useCallback(async(Oe,pe)=>{const ee=U.current,Ze=g.current===pe&&(b(pe)?.length??0)===0;Ze&&V(!0);try{const{count:rt,hasMore:kt,oldestCursor:Ct}=await E(Oe,pe,async()=>{const Bt=await te.sessions.getMessages(Oe,50);return{messages:oC(Bt.messages.map(ah).filter(Pt=>Pt.sender!=="agent"||Pt.text||Pt.segments&&Pt.segments.length>0||Pt.isStreaming)),hasMore:Bt.hasMore,oldestCursor:Bt.messages[0]?new Date(Bt.messages[0].createdAt).toISOString():null}});return A(Oe,{hasMore:kt,oldestCursor:Ct}),rt}finally{Ze&&g.current===pe&&U.current===ee&&V(!1)}},[E,b,U]),Qe=()=>{const Oe=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Oe){const pe=Cf(f.current.activeSessionId,et);pe.kind==="cancel"&&te.agents.cancelProcessing(Oe,pe.target).catch(()=>{})}n(f.current.activeSessionId??et),Oe&&f.current.activeSessionId&&f.current.activeSessionId!==et&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ye=S.useCallback(async(Oe,pe,ee)=>{if(!Oe||!pe||pe===et||l.current.has(pe))return;let Ze=null;try{const rt=e.current.get(pe);if(rt&&!rt.signal.aborted&&T(ee)?.has(pe)){g.current===ee&&Z(!0);return}const kt=()=>{aC({liveSessions:T(ee),sessionId:pe,placeholderId:et})&&(P(ee,pe),g.current===ee&&(Z(!1),O(ee,de=>cu(de),pe)))},Ct=`${Oe}:${pe}`,Bt=o.current.get(Ct)??0;if(Date.now()-Bt<1500)return;o.current.set(Ct,Date.now());let pt;const Pt=await te.sessions.streamStatus(Oe,pe);Pt.messageId&&(pt=Pt.messageId);const Ae=b(ee)??[],Wt=Pt.status==="streaming",ut=lC(Ae,{expectedMessageId:Pt.messageId,allowCurrentTurnPartial:Wt}),ks=!!Pt.active&&(Pt.status==="done"||Pt.status==="error")&&!!ut?.isStreaming;if(JO({aborted:!1,sawTerminal:ks,serverStatus:e0(Pt.status)})==="finalize"){kt();return}o.current.set(Ct,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),Ze=new AbortController,t.current.set(pe,Ze),y(ee),Z(!0),_(ee,pe);let Ne=ut?.id;if(!ut||ut.isError)Ne=`reattach_${Date.now()}`,O(ee,de=>[...de,{id:Ne,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],pe);else{const de=(ut.segments??[]).filter(Se=>Se.type==="tool").map(Se=>Se.status==="stopped"||Se.status==="running"?{...Se,status:"running"}:Se);O(ee,Se=>Se.map(_e=>_e.id===ut.id?{..._e,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:_e),pe)}const Jt=de=>{g.current===ee&&(u.current=Date.now(),m(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(J=>J.id===Ne):-1,Fe=Ie>=0?Ie:_e.map((J,$e)=>({m:J,j:$e})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];return _e[Fe]={...ze,text:(ze.text??"")+de,segments:wO(ze.segments??[],de),isStreaming:!0},_e},pe))},at=de=>{g.current===ee&&(u.current=Date.now(),m(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(J=>J.id===Ne):-1,Fe=Ie>=0?Ie:_e.map((J,$e)=>({m:J,j:$e})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];return _e[Fe]={...ze,segments:_O(ze.segments??[],de),isStreaming:!0},_e},pe))},ft=de=>{if(g.current===ee&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(ee,{...de,phase:de.phase,ts:Date.now()},pe),de.phase==="start"){const Se=`${de.tool}_${Date.now()}`,_e=new Date().toISOString(),Ie=Fe=>{const ze=[...Fe];for(let J=ze.length-1;J>=0;J--){const $e=ze[J];if($e.type==="tool"&&$e.tool===de.tool&&($e.status==="running"||$e.status==="stopped"))return ze[J]={...$e,status:"running",args:de.arguments??$e.args},ze}return ze.push({type:"tool",key:Se,tool:de.tool,status:"running",args:de.arguments,createdAt:_e}),ze};O(ee,Fe=>{const ze=[...Fe],J=Ne?ze.findIndex(Pe=>Pe.id===Ne):-1;if(J<0)return Fe;const $e=Ie(ze[J].segments??[]),Te=ze[J].committedSegments,ge=Te&&Ie(Te);return ze[J]={...ze[J],segments:$e,committedSegments:ge,isStreaming:!0},ze},pe)}else if(de.phase==="end"){const Se=new Date().toISOString(),_e=Ie=>{const Fe=[...Ie];for(let ze=Fe.length-1;ze>=0;ze--){const J=Fe[ze];if(J.type==="tool"&&J.tool===de.tool&&(J.status==="running"||J.status==="stopped")){Fe[ze]={...J,status:de.success===!1?"error":"done",args:de.arguments??J.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:Se};break}}return Fe};O(ee,Ie=>{const Fe=[...Ie],ze=Ne?Fe.findIndex(ge=>ge.id===Ne):-1;if(ze<0)return Ie;const J=_e(Fe[ze].segments??[]),$e=Fe[ze].committedSegments,Te=$e&&_e($e);return Fe[ze]={...Fe[ze],segments:J,committedSegments:Te,isStreaming:!0},Fe},pe)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const Se=_e=>{const Ie=[..._e];for(let Fe=Ie.length-1;Fe>=0;Fe--){const ze=Ie[Fe];if(ze.type==="tool"&&(ze.tool==="spawn_subagent"||ze.tool==="spawn_subagents")&&(ze.status==="running"||ze.status==="stopped")){Ie[Fe]={...ze,status:"running",subagentLogs:kO(ze.subagentLogs,de.subagentEvent)};break}}return Ie};m(ee,_e=>{const Ie=[..._e],Fe=Ne?Ie.findIndex(Te=>Te.id===Ne):-1;if(Fe<0)return _e;const ze=Se(Ie[Fe].segments??[]),J=Ie[Fe].committedSegments,$e=J&&Se(J);return Ie[Fe]={...Ie[Fe],segments:ze,committedSegments:$e,isStreaming:!0},Ie},pe)}}},Tt=de=>{g.current===ee&&(u.current=Date.now(),O(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex(ze=>ze.id===Ne):-1;if(Ie<0)return Se;const Fe=[..._e[Ie].committedSegments??[]];if(de.type==="thinking_commit")Fe.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")Fe.push({type:"text",content:de.content,createdAt:de.createdAt});else return Se;return _e[Ie]={..._e[Ie],committedSegments:Fe,isStreaming:!0},_e},pe))},yt=de=>{if(g.current!==ee)return;u.current=Date.now();const Se=(de.segments??[]).map((_e,Ie)=>_e.type==="tool"?{type:"tool",key:`${_e.tool}_${Ie}`,tool:_e.tool??"tool",status:_e.status==="error"?"error":_e.status==="running"||_e.status==="stopped"?"running":"done",args:_e.arguments,result:_e.result,error:_e.error,durationMs:_e.durationMs,createdAt:_e.createdAt,..._e.subagentLogs?.length?{subagentLogs:_e.subagentLogs}:{}}:{type:"text",content:_e.content??"",thinking:_e.thinking,createdAt:_e.createdAt});O(ee,_e=>{const Ie=[..._e],Fe=Ne?Ie.findIndex(ze=>ze.id===Ne):-1;return Fe<0?_e:(Ie[Fe]={...Ie[Fe],text:de.content||Ie[Fe].text,segments:Se,committedSegments:Se,isStreaming:!0,isStopped:!1},Ie)},pe);for(const _e of Se)_e.type==="tool"&&x(ee,{tool:_e.tool,phase:_e.status==="running"||_e.status==="stopped"?"start":"end",success:_e.status!=="error",arguments:_e.args,result:_e.result,error:_e.error,durationMs:_e.durationMs,ts:Date.now()},pe)},ae=8;let re=null;const Xe=de=>{g.current===ee&&O(ee,Se=>{const _e=Se.map((Fe,ze)=>({m:Fe,j:ze})).reverse().find(Fe=>Fe.m.sender==="agent"&&Fe.m.isStreaming)?.j??-1;if(_e<0||Se[_e].reconnecting===de)return Se;const Ie=[...Se];return Ie[_e]={...Ie[_e],reconnecting:de},Ie},pe)};for(let de=1;de<=ae;de++){if(Ze.signal.aborted)return;try{re=await te.sessions.reattachStream(Oe,pe,{onChunk:Jt,onThinking:at,onActivity:ft,onCommit:Tt,onSnapshot:yt},Ze.signal,0)}catch(_e){if(Ze.signal.aborted)throw _e;re=null}if(!re||!re.attached){re=null;break}if(re.terminal)break;Xe(!0);const Se=await te.sessions.streamStatus(Oe,pe).catch(()=>null);if(Se?.messageId&&(pt=Se.messageId),!Se||!Se.active||Se.status==="not_found"||Se.status==="idle"){Xe(!1),re=null;break}await new Promise(_e=>setTimeout(_e,Math.min(800*de,4e3))),Xe(!1)}if(!re){k(ee),P(ee,pe),g.current===ee&&(Z(!1),pt&&Ne&&O(ee,de=>wa(de,Ne,pt),pe),Ue(pe,ee).catch(()=>{}).finally(()=>{O(ee,de=>cu(de,"done"),pe)})),i(Ze);return}if(g.current===ee){let de;O(ee,Se=>{const _e=[...Se],Ie=Ne?_e.findIndex($e=>$e.id===Ne):-1,Fe=Ie>=0?Ie:_e.map(($e,Te)=>({m:$e,j:Te})).reverse().find($e=>$e.m.sender==="agent"&&$e.m.isStreaming)?.j??-1;if(Fe<0)return Se;const ze=_e[Fe];if(!ze.isStreaming)return Se;de=ze.id;const J=re.segments?.length?CO(re.segments,ze.segments):void 0;return _e[Fe]={...ze,text:re.content||ze.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...J?{segments:J,committedSegments:J}:{}},_e},pe),de&&O(ee,Se=>wa(Se,de,re.messageId),pe),Z(!1)}k(ee),P(ee,pe),i(Ze)}catch(rt){const kt=Ze?[...t.current.values()].includes(Ze):!1;i(Ze),k(ee);const Ct=l.current.has(pe);if(Ct&&P(ee,pe),g.current===ee&&(Z(!1),kt&&Ct&&O(ee,Bt=>cu(Bt),pe)),rt instanceof Error&&rt.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Ot=S.useCallback(async(Oe,pe)=>{const ee=f.current,Ze=!Oe&&ee.chatContext.length>0?ee.chatContext.map(At=>At.content).join(`
76
76
 
77
77
  `)+`
78
78