@markus-global/cli 0.8.5 → 0.9.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/commands/model.d.ts.map +1 -1
  2. package/dist/commands/model.js +9 -2
  3. package/dist/commands/model.js.map +1 -1
  4. package/dist/commands/start.d.ts.map +1 -1
  5. package/dist/commands/start.js +227 -181
  6. package/dist/commands/start.js.map +1 -1
  7. package/dist/markus-browser-extension.zip +0 -0
  8. package/dist/markus.mjs +13015 -6404
  9. package/dist/web-ui/assets/ChatHelpers-Cb26xxzl.js +3 -0
  10. package/dist/web-ui/assets/CommentInput-CmSnFGbv.js +1 -0
  11. package/dist/web-ui/assets/ContentRenderer-CFJndxtW.js +82 -0
  12. package/dist/web-ui/assets/Deliverables-CL88tGZv.js +6 -0
  13. package/dist/web-ui/assets/Notifications-BX3Fx5j5.js +1 -0
  14. package/dist/web-ui/assets/Search-YJ4NBHyk.js +1 -0
  15. package/dist/web-ui/assets/Settings-B8xQ3rEN.js +8 -0
  16. package/dist/web-ui/assets/Store-WYrzY0Mr.js +1 -0
  17. package/dist/web-ui/assets/Team-DwRSN0-a.js +39 -0
  18. package/dist/web-ui/assets/Work-BZV40eAE.css +1 -0
  19. package/dist/web-ui/assets/Work-DNGfvBLY.js +11 -0
  20. package/dist/web-ui/assets/{arc-BdRlL2iO.js → arc-BfS9Mvj7.js} +1 -1
  21. package/dist/web-ui/assets/architectureDiagram-3BPJPVTR-CFNOE9Ft.js +36 -0
  22. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BpzalW_a.js → blockDiagram-GPEHLZMM-gD6Hylng.js} +2 -2
  23. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BCAI0V-n.js → c4Diagram-AAUBKEIU-8QoBVsn5.js} +2 -2
  24. package/dist/web-ui/assets/channel-1ow_lsxl.js +1 -0
  25. package/dist/web-ui/assets/{chunk-2J33WTMH-Dg7rYV2F.js → chunk-2J33WTMH--5nv1yIK.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-4BX2VUAB-NjIIklhn.js → chunk-4BX2VUAB-DMHNCjRo.js} +1 -1
  27. package/dist/web-ui/assets/chunk-55IACEB6-DoagUtYg.js +1 -0
  28. package/dist/web-ui/assets/{chunk-727SXJPM-D4yVMcHy.js → chunk-727SXJPM-sOd6G91V.js} +1 -1
  29. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BZ2R83hR.js → chunk-AQP2D5EJ-BA1hEJE7.js} +1 -1
  30. package/dist/web-ui/assets/{chunk-FMBD7UC4-dKKoHR7V.js → chunk-FMBD7UC4-D-4YgaFe.js} +1 -1
  31. package/dist/web-ui/assets/chunk-ND2GUHAM-CaESAIrE.js +1 -0
  32. package/dist/web-ui/assets/{chunk-QZHKN3VN-QK1OECHO.js → chunk-QZHKN3VN-k2TrAqxw.js} +1 -1
  33. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-zJLmwj73.js +1 -0
  34. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-zJLmwj73.js +1 -0
  35. package/dist/web-ui/assets/cose-bilkent-S5V4N54A-BWzmZrwb.js +1 -0
  36. package/dist/web-ui/assets/dagre-BM42HDAG-DESAnnYv.js +4 -0
  37. package/dist/web-ui/assets/diagram-2AECGRRQ-BYqdvN4F.js +43 -0
  38. package/dist/web-ui/assets/diagram-5GNKFQAL-CjpQ4xfS.js +10 -0
  39. package/dist/web-ui/assets/{diagram-KO2AKTUF-BAPzH4PL.js → diagram-KO2AKTUF-CfsDLuOy.js} +2 -2
  40. package/dist/web-ui/assets/diagram-LMA3HP47-BZdG-8fy.js +24 -0
  41. package/dist/web-ui/assets/diagram-OG6HWLK6-jCwDnemx.js +24 -0
  42. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-C5lPAlAw.js → erDiagram-TEJ5UH35-BwJwkebk.js} +7 -7
  43. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-B3yPTMtT.js → flowDiagram-I6XJVG4X-DbFMgK3R.js} +2 -2
  44. package/dist/web-ui/assets/ganttDiagram-6RSMTGT7-BxVoytl3.js +292 -0
  45. package/dist/web-ui/assets/gitGraphDiagram-PVQCEYII-CEgYJOJY.js +106 -0
  46. package/dist/web-ui/assets/index-D_HH4ju2.js +666 -0
  47. package/dist/web-ui/assets/index-YDpknaqo.css +1 -0
  48. package/dist/web-ui/assets/infoDiagram-5YYISTIA-DQWzABtc.js +2 -0
  49. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BRM-2a0M.js → ishikawaDiagram-YF4QCWOH-DzmIWtTU.js} +2 -2
  50. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-ETvNwLl4.js → journeyDiagram-JHISSGLW-BoiaqjiH.js} +2 -2
  51. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-D066SbN9.js → kanban-definition-UN3LZRKU-CZeB8ThH.js} +6 -6
  52. package/dist/web-ui/assets/linear-D1g5s_fh.js +1 -0
  53. package/dist/web-ui/assets/{mermaid.core-rPZMstL0.js → mermaid.core-B_8QQ1RU.js} +10 -10
  54. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BKYYirSK.js → mindmap-definition-RKZ34NQL-DFF-GTkZ.js} +2 -2
  55. package/dist/web-ui/assets/pieDiagram-4H26LBE5-45MXMyT3.js +30 -0
  56. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-V5VbcvJY.js → quadrantDiagram-W4KKPZXB-kRCd2Nqe.js} +2 -2
  57. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-D2uVfqfP.js → requirementDiagram-4Y6WPE33-DSILTvsw.js} +2 -2
  58. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-C8ejeGTc.js → sankeyDiagram-5OEKKPKP-CwkyEhye.js} +2 -2
  59. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CI3unFup.js → sequenceDiagram-3UESZ5HK-0fo5Z81y.js} +2 -2
  60. package/dist/web-ui/assets/stateDiagram-AJRCARHV-B74U4HO9.js +1 -0
  61. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-bSRzYPvh.js +1 -0
  62. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-BrkWr53g.js → timeline-definition-PNZ67QCA-mRhWzQjp.js} +2 -2
  63. package/dist/web-ui/assets/transform-CpIVI4vC.js +1 -0
  64. package/dist/web-ui/assets/value-DIujSiJ7.js +1 -0
  65. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-C8mr8EAq.js → vennDiagram-CIIHVFJN-C82YisLk.js} +2 -2
  66. package/dist/web-ui/assets/{wardley-L42UT6IY-BFlL89Fu.js → wardley-L42UT6IY-Ba6AG0iH.js} +1 -1
  67. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CezrtcCI.js → wardleyDiagram-YWT4CUSO-BSmLAatg.js} +2 -2
  68. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-DrvIX-i_.js → xychartDiagram-2RQKCTM6-Z72DDYUU.js} +2 -2
  69. package/dist/web-ui/index.html +2 -2
  70. package/package.json +1 -1
  71. package/templates/roles/SHARED.md +11 -4
  72. package/templates/roles/agent-father/ROLE.md +1 -1
  73. package/templates/roles/secretary/HEARTBEAT.md +2 -2
  74. package/templates/roles/secretary/ROLE.md +26 -23
  75. package/templates/roles/skill-architect/ROLE.md +2 -2
  76. package/templates/roles/team-factory/ROLE.md +1 -1
  77. package/templates/skills/agent-building/SKILL.md +29 -10
  78. package/templates/skills/agent-building/skill.json +1 -1
  79. package/templates/skills/markus-hub-connector/server.mjs +12 -1
  80. package/templates/skills/skill-building/SKILL.md +30 -10
  81. package/templates/skills/skill-building/skill.json +1 -1
  82. package/templates/skills/team-building/SKILL.md +32 -13
  83. package/templates/skills/team-building/skill.json +1 -1
  84. package/dist/web-ui/assets/architectureDiagram-3BPJPVTR-D0tUssz3.js +0 -36
  85. package/dist/web-ui/assets/channel-CVrfB_bR.js +0 -1
  86. package/dist/web-ui/assets/chunk-55IACEB6-D1NbvEGQ.js +0 -1
  87. package/dist/web-ui/assets/chunk-ND2GUHAM-8DcNh3kD.js +0 -1
  88. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-vzqgiM0p.js +0 -1
  89. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-vzqgiM0p.js +0 -1
  90. package/dist/web-ui/assets/cose-bilkent-S5V4N54A-70zGiErc.js +0 -1
  91. package/dist/web-ui/assets/dagre-BM42HDAG-CjH95T53.js +0 -4
  92. package/dist/web-ui/assets/diagram-2AECGRRQ-D1h-kJfb.js +0 -43
  93. package/dist/web-ui/assets/diagram-5GNKFQAL-BfpyuUIG.js +0 -10
  94. package/dist/web-ui/assets/diagram-LMA3HP47-BzZcoqw9.js +0 -24
  95. package/dist/web-ui/assets/diagram-OG6HWLK6-UzfnxP-8.js +0 -24
  96. package/dist/web-ui/assets/ganttDiagram-6RSMTGT7-M0LiSJYB.js +0 -292
  97. package/dist/web-ui/assets/gitGraphDiagram-PVQCEYII-DMJ8bJ-V.js +0 -106
  98. package/dist/web-ui/assets/index-C0TJwd4k.js +0 -776
  99. package/dist/web-ui/assets/index-C1_HX8vL.css +0 -1
  100. package/dist/web-ui/assets/infoDiagram-5YYISTIA-H3O_dXaX.js +0 -2
  101. package/dist/web-ui/assets/linear-w-ZA_ecm.js +0 -1
  102. package/dist/web-ui/assets/pieDiagram-4H26LBE5-Cwjk7qIl.js +0 -30
  103. package/dist/web-ui/assets/stateDiagram-AJRCARHV-C4edfdOw.js +0 -1
  104. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CzloKUKx.js +0 -1
@@ -0,0 +1,39 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D_HH4ju2.js","assets/index-YDpknaqo.css"])))=>i.map(i=>d[i]);
2
+ import{r,e as go,u as Ve,j as e,q as fo,a as zr,k as ci,P as at,f as A,w as Fe,M as ho,A as mt,n as os,C as Sn,s as po,t as bo,b as di,v as ui,x as mi,g as tr,i as sr,E as vo,D as yo,y as Sa,z as jo,B as wo,F as xi,G as gi,H as No,J as ko,K as So,_ as fi,l as Ca,L as Co,O as To,Q as Mo,R as Ta,U as Po,V as Eo,W as Ma,h as _o,X as Ao,Y as Io,Z as Lo,$ as Do,m as Ro,a0 as Zn,a1 as er}from"./index-D_HH4ju2.js";import{r as Pa,p as $o}from"./CommentInput-CmSnFGbv.js";import{resolveFormat as Oo,ContentRenderer as Ea}from"./ContentRenderer-CFJndxtW.js";import{h as Is,t as Lr,d as Dr,e as _a,a as Aa,s as Fo,g as Ia,f as Bo,b as zo,c as Wo}from"./ChatHelpers-Cb26xxzl.js";function Ks(a,i,s){let n=s.initialDeps??[],o,l=!0;function u(){var m,f,y;let k;s.key&&((m=s.debug)!=null&&m.call(s))&&(k=Date.now());const j=a();if(!(j.length!==n.length||j.some((b,I)=>n[I]!==b)))return o;n=j;let p;if(s.key&&((f=s.debug)!=null&&f.call(s))&&(p=Date.now()),o=i(...j),s.key&&((y=s.debug)!=null&&y.call(s))){const b=Math.round((Date.now()-k)*100)/100,I=Math.round((Date.now()-p)*100)/100,N=I/16,_=(h,T)=>{for(h=String(h);h.length<T;)h=" "+h;return h};console.info(`%c⏱ ${_(I,5)} /${_(b,5)} ms`,`
3
+ font-size: .6rem;
4
+ font-weight: bold;
5
+ color: hsl(${Math.max(0,Math.min(120-120*N,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(l&&s.skipInitialOnChange)&&s.onChange(o),l=!1,o}return u.updateDeps=m=>{n=m},u}function La(a,i){if(a===void 0)throw new Error("Unexpected undefined");return a}const Ho=(a,i)=>Math.abs(a-i)<1.01,Vo=(a,i,s)=>{let n;return function(...o){a.clearTimeout(n),n=a.setTimeout(()=>i.apply(this,o),s)}},Da=a=>{const{offsetWidth:i,offsetHeight:s}=a;return{width:i,height:s}},qo=a=>a,Uo=a=>{const i=Math.max(a.startIndex-a.overscan,0),s=Math.min(a.endIndex+a.overscan,a.count-1),n=[];for(let o=i;o<=s;o++)n.push(o);return n},Ko=(a,i)=>{const s=a.scrollElement;if(!s)return;const n=a.targetWindow;if(!n)return;const o=u=>{const{width:m,height:f}=u;i({width:Math.round(m),height:Math.round(f)})};if(o(Da(s)),!n.ResizeObserver)return()=>{};const l=new n.ResizeObserver(u=>{const m=()=>{const f=u[0];if(f?.borderBoxSize){const y=f.borderBoxSize[0];if(y){o({width:y.inlineSize,height:y.blockSize});return}}o(Da(s))};a.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()});return l.observe(s,{box:"border-box"}),()=>{l.unobserve(s)}},Ra={passive:!0},$a=typeof window>"u"?!0:"onscrollend"in window,Go=(a,i)=>{const s=a.scrollElement;if(!s)return;const n=a.targetWindow;if(!n)return;let o=0;const l=a.options.useScrollendEvent&&$a?()=>{}:Vo(n,()=>{i(o,!1)},a.options.isScrollingResetDelay),u=k=>()=>{const{horizontal:j,isRtl:E}=a.options;o=j?s.scrollLeft*(E&&-1||1):s.scrollTop,l(),i(o,k)},m=u(!0),f=u(!1);s.addEventListener("scroll",m,Ra);const y=a.options.useScrollendEvent&&$a;return y&&s.addEventListener("scrollend",f,Ra),()=>{s.removeEventListener("scroll",m),y&&s.removeEventListener("scrollend",f)}},Yo=(a,i,s)=>{if(i?.borderBoxSize){const n=i.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return a[s.options.horizontal?"offsetWidth":"offsetHeight"]},Xo=(a,{adjustments:i=0,behavior:s},n)=>{var o,l;const u=a+i;(l=(o=n.scrollElement)==null?void 0:o.scrollTo)==null||l.call(o,{[n.options.horizontal?"left":"top"]:u,behavior:s})};class Qo{constructor(i){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 s,n,o;return((o=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:o.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(l=>{const u=()=>{const m=l.target,f=this.indexFromElement(m);if(!m.isConnected){this.observer.unobserve(m);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(m,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var o;(o=n())==null||o.disconnect(),s=null},observe:o=>{var l;return(l=n())==null?void 0:l.observe(o,{box:"border-box"})},unobserve:o=>{var l;return(l=n())==null?void 0:l.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,o])=>{typeof o>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:qo,rangeExtractor:Uo,onChange:()=>{},measureElement:Yo,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",...s}},this.notify=s=>{var n,o;(o=(n=this.options).onChange)==null||o.call(n,this,s)},this.maybeNotify=Ks(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{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(s=>s()),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 s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,l)=>{this.scrollAdjustments=0,this.scrollDirection=l?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=l,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=(s,n)=>{const o=new Map,l=new Map;for(let u=n-1;u>=0;u--){const m=s[u];if(o.has(m.lane))continue;const f=l.get(m.lane);if(f==null||m.end>f.end?l.set(m.lane,m):m.end<f.end&&o.set(m.lane,!0),o.size===this.options.lanes)break}return l.size===this.options.lanes?Array.from(l.values()).sort((u,m)=>u.end===m.end?u.index-m.index:u.end-m.end)[0]:void 0},this.getMeasurementOptions=Ks(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(s,n,o,l,u,m,f)=>(this.prevLanes!==void 0&&this.prevLanes!==m&&(this.lanesChangedFlag=!0),this.prevLanes=m,this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:o,getItemKey:l,enabled:u,lanes:m,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=Ks(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:o,getItemKey:l,enabled:u,lanes:m,laneAssignmentMode:f},y)=>{if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const p of this.laneAssignments.keys())p>=s&&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 k=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1);const j=this.measurementsCache.slice(0,k),E=new Array(m).fill(void 0);for(let p=0;p<k;p++){const b=j[p];b&&(E[b.lane]=p)}for(let p=k;p<s;p++){const b=l(p),I=this.laneAssignments.get(p);let N,_;const h=f==="estimate"||y.has(b);if(I!==void 0&&this.options.lanes>1){N=I;const P=E[N],L=P!==void 0?j[P]:void 0;_=L?L.end+this.options.gap:n+o}else{const P=this.options.lanes===1?j[p-1]:this.getFurthestMeasurement(j,p);_=P?P.end+this.options.gap:n+o,N=P?P.lane:p%this.options.lanes,this.options.lanes>1&&h&&this.laneAssignments.set(p,N)}const T=y.get(b),D=typeof T=="number"?T:this.options.estimateSize(p),M=_+D;j[p]={index:p,start:_,size:D,end:M,key:b,lane:N},E[N]=p}return this.measurementsCache=j,j},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ks(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,l)=>this.range=s.length>0&&n>0?Jo({measurements:s,outerSize:n,scrollOffset:o,lanes:l}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ks(()=>{let s=null,n=null;const o=this.calculateRange();return o&&(s=o.startIndex,n=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,o,l,u)=>l===null||u===null?[]:s({startIndex:l,endIndex:u,overscan:n,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,o=s.getAttribute(n);return o?parseInt(o,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(o!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,o-l),m=Math.min(this.options.count-1,o+l);return s>=u&&s<=m}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((u,m)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(m))});return}const n=this.indexFromElement(s),o=this.options.getItemKey(n),l=this.elementsCache.get(o);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(o,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var o;const l=this.measurementsCache[s];if(!l)return;const u=this.itemSizeCache.get(l.key)??l.size,m=n-u;m!==0&&(((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(l,m,this):l.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=m,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(l.index),this.itemSizeCache=new Map(this.itemSizeCache.set(l.key,n)),this.notify(!1))},this.getVirtualItems=Ks(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const o=[];for(let l=0,u=s.length;l<u;l++){const m=s[l],f=n[m];o.push(f)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return La(n[hi(0,n.length-1,o=>La(n[o]).start,s)])},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 s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(s,n,o=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();n==="auto"&&(n=s>=u+l?"end":"start"),n==="center"?s+=(o-l)/2:n==="end"&&(s-=l);const m=this.getMaxScrollOffset();return Math.max(Math.min(m,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[s];if(!u)return;if(n==="auto")if(u.end>=l+o-this.options.scrollPaddingEnd)n="end";else if(u.start<=l+this.options.scrollPaddingStart)n="start";else return[l,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const m=n==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(m,n,u.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:o="auto"}={})=>{const l=this.getOffsetForAlignment(s,n),u=this.now();this.scrollState={index:null,align:n,behavior:o,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:o="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const l=this.getOffsetForIndex(s,n);if(!l)return;const[u,m]=l,f=this.now();this.scrollState={index:s,align:m,behavior:o,startedAt:f,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const o=this.getScrollOffset()+s,l=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let o;if(n.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=n[n.length-1])==null?void 0:s.end)??0;else{const l=Array(this.options.lanes).fill(null);let u=n.length-1;for(;u>=0&&l.some(m=>m===null);){const m=n[u];l[m.lane]===null&&(l[m.lane]=m.end),u--}o=Math.max(...l.filter(m=>m!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(i)}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 n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,o=n?n[0]:this.scrollState.lastTargetOffset,l=1,u=o!==this.scrollState.lastTargetOffset;if(!u&&Ho(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.scrollState=null;return}}else this.scrollState.stableFrames=0,u&&(this.scrollState.lastTargetOffset=o,this.scrollState.behavior="auto",this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const hi=(a,i,s,n)=>{for(;a<=i;){const o=(a+i)/2|0,l=s(o);if(l<n)a=o+1;else if(l>n)i=o-1;else return o}return a>0?a-1:0};function Jo({measurements:a,outerSize:i,scrollOffset:s,lanes:n}){const o=a.length-1,l=f=>a[f].start;if(a.length<=n)return{startIndex:0,endIndex:o};let u=hi(0,o,l,s),m=u;if(n===1)for(;m<o&&a[m].end<s+i;)m++;else if(n>1){const f=Array(n).fill(0);for(;m<o&&f.some(k=>k<s+i);){const k=a[m];f[k.lane]=k.end,m++}const y=Array(n).fill(s+i);for(;u>=0&&y.some(k=>k>=s);){const k=a[u];y[k.lane]=k.start,u--}u=Math.max(0,u-u%n),m=Math.min(o,m+(n-1-m%n))}return{startIndex:u,endIndex:m}}const Oa=typeof document<"u"?r.useLayoutEffect:r.useEffect;function Zo({useFlushSync:a=!0,...i}){const s=r.useReducer(()=>({}),{})[1],n={...i,onChange:(l,u)=>{var m;a&&u?go.flushSync(s):s(),(m=i.onChange)==null||m.call(i,l,u)}},[o]=r.useState(()=>new Qo(n));return o.setOptions(n),Oa(()=>o._didMount(),[]),Oa(()=>o._willUpdate()),o}function el(a){return Zo({observeElementRect:Ko,observeElementOffset:Go,scrollToFn:Xo,...a})}function Nn({children:a,onClose:i,title:s,width:n="w-[440px]"}){return e.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:i,children:e.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${n} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:o=>o.stopPropagation(),children:[e.jsx("h3",{className:"text-base font-semibold mb-5",children:s}),a]})})}function Ys({label:a,children:i}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:a}),i]})}function tl({onClose:a,onCreate:i}){const{t:s}=Ve(["team","common"]),[n,o]=r.useState(""),[l,u]=r.useState("");return e.jsx(Nn,{onClose:a,title:s("team:modals.createTeam.title"),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ys,{label:s("team:modals.createTeam.teamName"),children:e.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:s("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:m=>{m.key==="Enter"&&n.trim()&&i(n.trim(),l.trim()||void 0)}})}),e.jsx(Ys,{label:s("team:modals.createTeam.description"),children:e.jsx("textarea",{value:l,onChange:m=>u(m.target.value),placeholder:s("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("team:modals.createTeam.hint")}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:e.jsx(fo,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:e.jsx("span",{className:"text-brand-400 font-medium"}),1:e.jsx("span",{className:"text-brand-400"})}})}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:a,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:()=>n.trim()&&i(n.trim(),l.trim()||void 0),disabled:!n.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:s("team:modals.createTeam.createTeam")})]})]})})}function sl({onClose:a,onAdd:i}){const{t:s}=Ve(["team","common"]),[n,o]=r.useState(""),[l,u]=r.useState("member"),[m,f]=r.useState(""),[y,k]=r.useState(""),[j,E]=r.useState(!1),[p,b]=r.useState(null),[I,N]=r.useState(!1),_=p?.inviteToken?`${window.location.origin}/#invite?token=${p.inviteToken}`:null,h=async()=>{if(k(""),!n.trim()){k(s("team:modals.addHuman.nameRequired"));return}if(!m.trim()){k(s("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){k(s("team:modals.addHuman.invalidEmail"));return}E(!0);try{const D=await i(n.trim(),l,m.trim());b({...D,userName:n.trim()})}catch(D){k(D instanceof Error?D.message:String(D))}finally{E(!1)}},T=()=>{_&&(navigator.clipboard.writeText(_),N(!0),setTimeout(()=>N(!1),2e3))};return p?e.jsxs(Nn,{onClose:a,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx("div",{className:"text-base font-medium mb-1",children:s("team:modals.addHuman.memberCreated",{name:p.userName})}),_?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:s("team:modals.addHuman.inviteHint")}),e.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:s("team:modals.addHuman.inviteLink")}),e.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:_})]}),e.jsx("button",{onClick:T,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${I?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(I?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):e.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:s("team:modals.addHuman.memberCreatedNoInvite")})]}),e.jsx("div",{className:"flex justify-end pt-3",children:e.jsx("button",{onClick:a,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("common:done")})})]}):e.jsx(Nn,{onClose:a,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[e.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:s("team:modals.addHuman.sharedInstanceTitle")}),s("team:modals.addHuman.sharedInstanceDesc"),e.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[s("team:modals.addHuman.orgHint")," ",e.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:s("team:modals.addHuman.orgLink")})]})]}),e.jsx(Ys,{label:s("team:modals.addHuman.name"),children:e.jsx("input",{value:n,onChange:D=>o(D.target.value),placeholder:s("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),e.jsx(Ys,{label:s("team:modals.addHuman.role"),children:e.jsxs("select",{value:l,onChange:D=>u(D.target.value),className:"input",children:[e.jsx("option",{value:"owner",children:s("common:role.owner")}),e.jsx("option",{value:"admin",children:s("common:role.admin")}),e.jsx("option",{value:"member",children:s("common:role.member")}),e.jsx("option",{value:"guest",children:s("common:role.guest")})]})}),e.jsx(Ys,{label:s("team:modals.addHuman.emailRequired"),children:e.jsx("input",{value:m,onChange:D=>f(D.target.value),type:"email",placeholder:s("team:modals.addHuman.emailPlaceholder"),className:"input"})}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:s("team:modals.addHuman.inviteFlowHint")}),y&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:y}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:a,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:h,disabled:j,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:s(j?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function nl({teamId:a,ungrouped:i,onClose:s,onAdd:n}){const{t:o}=Ve(["team","common"]);return e.jsx(Nn,{onClose:s,title:o("team:modals.addExisting.title"),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("team:modals.addExisting.hint")}),i.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:o("team:modals.addExisting.allInTeam")}):e.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:i.map(l=>e.jsxs("button",{onClick:()=>n(l.id,l.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${l.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:l.name.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:l.name}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[l.role," · ",l.type==="agent"?o("team:modals.addExisting.typeAgent"):o("team:modals.addExisting.typeHuman")]})]}),l.status&&e.jsx("span",{className:`w-2 h-2 rounded-full ${l.status==="idle"?"bg-green-400":l.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},l.id))}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:o("common:close")})})]})})}function rl({onClose:a,onConnected:i}){const{t:s}=Ve(["team","common"]),[n,o]=r.useState(""),[l,u]=r.useState(""),[m,f]=r.useState(!1),[y,k]=r.useState(null),[j,E]=r.useState(null),p=async()=>{if(!n.trim()){u(s("team:modals.openClaw.agentNameRequired"));return}const I=n.trim().toLowerCase().replace(/\s+/g,"-");f(!0),u("");try{const N=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:I,agentName:n.trim(),orgId:"default",capabilities:["general"]})});if(!N.ok){const h=await N.json().catch(()=>({}));throw new Error(h.error??`HTTP ${N.status}`)}const _=await N.json();k({externalAgentId:I,markusAgentId:_.registration?.markusAgentId,token:_.token,gatewayUrl:_.gatewayUrl})}catch(N){u(String(N))}f(!1)},b=(I,N)=>{navigator.clipboard.writeText(I),E(N),setTimeout(()=>E(null),2e3)};return e.jsx(Nn,{onClose:a,title:s("team:modals.openClaw.title"),width:"w-[560px]",children:y?(()=>{const I=y.gatewayUrl??`${window.location.origin}/api/gateway`,N=y.token?s("team:modals.openClaw.bearerTokenLine",{token:y.token}):"",_=s("team:modals.openClaw.connectionPromptBody",{gwUrl:I,externalAgentId:y.externalAgentId,tokenSection:N});return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),e.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:s("team:modals.openClaw.agentRegistered")}),e.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:e.jsx("strong",{children:n})})]}),e.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:s("team:modals.openClaw.copyInstruction")}),e.jsx("button",{onClick:()=>b(_,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${j==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(j==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),e.jsx("div",{className:"flex justify-end pt-5",children:e.jsx("button",{onClick:()=>{i()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("team:modals.openClaw.done")})})]})})():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:s("team:modals.openClaw.description")}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ys,{label:s("team:modals.openClaw.agentName"),children:e.jsx("input",{className:"input",placeholder:s("team:modals.openClaw.agentNamePlaceholder"),value:n,onChange:I=>o(I.target.value),autoFocus:!0})}),l&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:l}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:a,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:p,disabled:m,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:s(m?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let Xn=new Map;function al({agents:a,humans:i,authUser:s,onClose:n,onCreate:o}){const{t:l}=Ve(["team","common"]),[u,m]=r.useState(""),[f,y]=r.useState(new Set),[k,j]=r.useState(""),[E,p]=r.useState(!1),b=r.useMemo(()=>{const h=[];for(const T of a)h.push({id:T.id,name:T.name,type:"agent",subtitle:T.role||"Agent"});for(const T of i)T.id!==s?.id&&h.push({id:T.id,name:T.name,type:"human",subtitle:T.email||T.role||"Human"});return h},[a,i,s]),I=r.useMemo(()=>{if(!k)return b;const h=k.toLowerCase();return b.filter(T=>T.name.toLowerCase().includes(h)||T.subtitle.toLowerCase().includes(h))},[b,k]),N=h=>{y(T=>{const D=new Set(T);return D.has(h)?D.delete(h):D.add(h),D})},_=async()=>{if(!u.trim()||f.size===0)return;p(!0);const h=[...f],T={},D={};for(const M of h){const P=b.find(L=>L.id===M);P&&(T[M]=P.type,D[M]=P.name)}await o(u.trim(),h,T,D),p(!1)};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:n,children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("modals.createGroupChat.title")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:l("modals.createGroupChat.subtitle")})]}),e.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:e.jsx("input",{value:u,onChange:h=>m(h.target.value),placeholder:l("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),e.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:e.jsx("input",{value:k,onChange:h=>j(h.target.value),placeholder:l("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[I.length===0&&e.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:l("modals.createGroupChat.noMembersFound")}),I.map(h=>e.jsxs("button",{onClick:()=>N(h.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${f.has(h.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${f.has(h.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:f.has(h.id)&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx(mt,{name:h.name,size:20,bgClass:h.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate text-[11px] font-medium block",children:h.name}),e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:h.subtitle})]}),e.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${h.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:h.type==="agent"?l("modals.addExisting.typeAgent"):l("modals.addExisting.typeHuman")})]},h.id))]}),e.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modals.createGroupChat.selected",{count:f.size})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:n,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:l("common:cancel")}),e.jsx("button",{onClick:_,disabled:!u.trim()||f.size===0||E,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:l(E?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const il=r.memo(function({authUser:i,agents:s,teams:n,humans:o,tasks:l,externalAgents:u,groupChats:m,chatMode:f,selectedAgent:y,activeChannel:k,activeDmUserId:j,onSelectAgent:E,onSelectChannel:p,onSelectDm:b,onSelectTeam:I,selectedTeamId:N,onRefreshTeams:_,onRefreshAgents:h,onRefreshHumans:T,onRefreshGroupChats:D,onViewProfile:M,onManageGroupMembers:P,unreadByAgent:L,unreadByChannel:G,width:me,onResizeStart:Ee,hidden:Le,onCollapse:Q,initialLoading:De,previewMode:be}){const{t:R}=Ve(["team","common"]),ne=zr(),v=ci(at.TEAM),H=i?.role==="owner"||i?.role==="admin",w=r.useMemo(()=>new Set(u.map(g=>g.markusAgentId).filter(Boolean)),[u]),[Z,ie]=r.useState([]),[Re,$e]=r.useState(new Set),[ye,dt]=r.useState(!1),[ht,zt]=r.useState(!1),[ls,Dt]=r.useState(null),[Qt,cs]=r.useState(!1),[Ls,Wt]=r.useState(!1),[xt,it]=r.useState(null),[ae,Be]=r.useState(null),[He,Oe]=r.useState(null),[gt,Xs]=r.useState(!1),[Cn,Qs]=r.useState(""),[Ht,Js]=r.useState(null),[Zs,Vr]=r.useState(null),[ps,ds]=r.useState(null),[us,Vt]=r.useState(!1),Tn=r.useRef(null),[rr,bs]=r.useState(null),Jt=r.useRef(null),Mn=r.useRef(null),[en,tn]=r.useState(null),vs=(g,z="success")=>{tn({message:g,type:z}),setTimeout(()=>tn(null),3e3)},[Mt,Rt]=r.useState(null),[Pn,sn]=r.useState(!1),Ds=r.useRef(!1);r.useEffect(()=>{if(be)return;A.governance.getSystemStatus().then(X=>{Ds.current=!0,Rt(X.globalPaused)}).catch(()=>{Ds.current=!0,Rt(!1)});const g=Fe.on("system:pause-all",()=>{Ds.current&&Rt(!0)}),z=Fe.on("system:resume-all",()=>{Ds.current&&Rt(!1)});return()=>{g(),z()}},[]),r.useEffect(()=>{if(!be)return;const g=setTimeout(()=>{const z=Mn.current,X=Jt.current;z&&X&&X.scrollTo({top:z.offsetTop-X.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(g)},[be]);const nn=r.useCallback(()=>{Mt!==null&&ys({title:R(Mt?"modals.resumeAll.title":"modals.pauseAll.title"),message:R(Mt?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:R(Mt?"chat.resume":"chat.pause"),onConfirm:async()=>{sn(!0);try{Mt?(await A.governance.resumeAll(),Rt(!1)):(await A.governance.pauseAll(),Rt(!0))}catch{}sn(!1)}})},[Mt]),[qt,ys]=r.useState(null),Rs=(g,z,X,ue,ve)=>{ys({title:g,message:z,onConfirm:X,confirmLabel:ue,checkboxes:ve})},[Pt,ms]=r.useState(null),[js,rn]=r.useState(null),Et=r.useRef(null),ft=r.useRef(null),[$t,an]=r.useState(!1),[O,_e]=r.useState(null),[te,st]=r.useState(""),Ne=r.useCallback((g,z=176,X=220)=>{const ue=window.innerWidth,ve=window.innerHeight,Ae=8;let Ue=g.clientX,ze=g.clientY;return Ue+z>ue-Ae&&(Ue=Math.max(Ae,ue-z-Ae)),ze+X>ve-Ae&&(ze=Math.max(Ae,ve-X-Ae)),Ue=Math.max(Ae,Math.min(Ue,ue-z-Ae)),ze=Math.max(Ae,Math.min(ze,ve-X-Ae)),{x:Ue,y:ze}},[]),[pt,Je]=r.useState(Xn),ws=r.useMemo(()=>s.map(g=>g.id).sort().join(","),[s]);r.useEffect(()=>{if(!s.length||!v)return;let g=!1;(async()=>{const ze=[];await Promise.allSettled(s.map(async ke=>{if(!Xn.has(ke.id))try{const{sessions:Ye}=await A.sessions.listByAgent(ke.id,1);if(!Ye.length)return;const{messages:lt}=await A.sessions.getMessages(Ye[0].id,1);if(lt.length){const nt=lt[0],Ft=nt.metadata?.segments;let et=nt.content;if(Ft&&Ft.length>0){const St=[...Ft].reverse().find(xs=>xs.type==="text");St&&St.type==="text"&&(et=St.content)}const Xe=et.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);Xe&&ze.push([ke.id,Xe])}}catch{}})),!g&&ze.length&&Je(ke=>{const Ye=new Map(ke);for(const[lt,nt]of ze)Ye.set(lt,nt);return Xn=Ye,Ye})})();const X=new Set(s.map(ze=>ze.id)),ue=ze=>ze.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),ve=(ze,ke)=>{if(!ze||!ke||!X.has(ze))return;const Ye=ue(ke);Ye&&Je(lt=>{const nt=new Map(lt);return nt.set(ze,Ye),Xn=nt,nt})},Ae=Fe.on("chat:proactive_message",ze=>{const ke=ze.payload;ve(ke.agentId??"",ke.message??"")}),Ue=Fe.on("chat:message",ze=>{const ke=ze.payload,Ye=ke.senderId??ke.agentId??"",lt=ke.text??ke.message??"";ve(Ye,lt)});return()=>{g=!0,Ae(),Ue()}},[ws,v]);const bt=r.useCallback(()=>{be||A.teams.list().then(g=>ie(g.ungrouped)).catch(()=>{})},[be]);r.useEffect(()=>{bt()},[bt]),r.useEffect(()=>{if(!v)return;const g=Fe.on("team:update",bt),z=Fe.on("agent:removed",bt);return()=>{g(),z()}},[bt,v]),r.useEffect(()=>{if(!ae&&!He&&!Ht&&!us&&!ps)return;const g=()=>{Be(null),Oe(null),Js(null),ds(null),Vt(!1)},z=setTimeout(()=>document.addEventListener("click",g),0);return()=>{clearTimeout(z),document.removeEventListener("click",g)}},[ae,He,Ht,us,ps]);const Ns=(g,z)=>{Rs(`${R("common:delete")} "${z}"?`,R("modals.deleteTeam.message"),async X=>{const ue=X?.deleteMembers??!0,ve=X?.purgeFiles??!1;await A.teams.delete(g,ue,{purgeFiles:ve}),_(),bt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},R("contextMenu.deleteTeam"),[{id:"deleteMembers",label:R("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:R("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},$s=async(g,z)=>{try{const ue=await(z==="start"?A.teams.startAll:A.teams.stopAll)(g),ve=ue.success?.length??0,Ae=ue.failed?.length??0;Ae>0?vs(R("batchAction.failed",{action:R(`batchAction.operation.${z}`),ok:ve,fail:Ae}),"error"):ve>0&&vs(R("batchAction.succeeded",{count:ve,action:R(`batchAction.past.${z}`)}),"success"),h()}catch(X){vs(R("batchAction.failedToRun",{action:R(`batchAction.operation.${z}`),error:X instanceof Error?X.message:String(X)}),"error")}},ar=async(g,z,X)=>{await A.teams.update(g,{managerId:z,managerType:X}),_()},En=async g=>{if(!te.trim()){_e(null);return}await A.teams.update(g,{name:te.trim()}),_e(null),_()},qe=async(g,z)=>{z==="offline"?await A.agents.start(g):await A.agents.stop(g),h()},vt=(g,z)=>{Rs(R("modals.removeFromTeam.title"),R("modals.removeFromTeam.message"),async()=>{await A.teams.removeMember(g,z),_(),bt()},R("common:remove"))},yt=(g,z,X)=>{Rs(`${R("common:remove")} "${z}"?`,R(X==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async ue=>{if(X==="agent"){const ve=ue?.purgeFiles??!1;await A.agents.remove(g,{purgeFiles:ve})}else await A.users.remove(g);h(),_(),T?.(),bt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},R("common:remove"),X==="agent"?[{id:"purgeFiles",label:R("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},ot=g=>{if(g.isOrgSecretary||g.protected)return!0;if(g.teamId)return!1;const z=(g.role??"").toLowerCase().trim(),X=(g.name??"").trim();return X==="Secretary"||X==="秘书"||z==="secretary"||z.startsWith("secretary")},ir=(g,z,X)=>{const ue=s.find(ve=>ve.id===z);ue&&ot(ue)||(ft.current={x:g.clientX,y:g.clientY},Et.current=setTimeout(()=>{ms({agentId:z,fromTeamId:X}),an(!0)},200))},Ut=g=>{if(!ft.current||!Et.current)return;const z=Math.abs(g.clientX-ft.current.x),X=Math.abs(g.clientY-ft.current.y);(z>5||X>5)&&($t||(clearTimeout(Et.current),Et.current=null))},kt=async()=>{if(Et.current&&(clearTimeout(Et.current),Et.current=null),ft.current=null,$t&&Pt&&js){const g=js==="_ungrouped"?void 0:js;try{if(Pt.fromTeamId&&Pt.fromTeamId!==g&&await A.teams.removeMember(Pt.fromTeamId,Pt.agentId),g&&g!==Pt.fromTeamId){const z=s.find(X=>X.id===Pt.agentId);await A.teams.addMember(g,Pt.agentId,"agent")}_(),h(),bt()}catch(z){vs(R("batchAction.moveFailed",{error:z instanceof Error?z.message:String(z)}),"error")}}ms(null),rn(null),an(!1)},ks=r.useMemo(()=>new Map(n.map(g=>[g.id,g])),[n]),_t=r.useMemo(()=>{const g=new Map,z=[];for(const X of s)if(X.teamId&&ks.has(X.teamId)){const ue=g.get(X.teamId)??[];ue.push(X),g.set(X.teamId,ue)}else z.push(X);return{byTeam:g,ungrouped:z}},[s,ks]),Ot=(g,z)=>{const X=f==="direct"&&y===g.id,ue=w.has(g.id),ve=g.status==="offline",Ae=g.status==="idle"?"bg-green-500":g.status==="working"?"bg-blue-500 animate-pulse":g.status==="error"?"bg-red-500":"bg-gray-600",ze=(void 0)?.managerId===g.id,ke=g.role?.toLowerCase().replace(/[-_]/g," ").trim(),Ye=g.name.toLowerCase().trim(),lt=ke&&ke!==Ye,nt=pt.get(g.id)||g.currentActivity?.label?.slice(0,60)||"",Ft=g.status==="idle"?R("common:status.online"):g.status==="working"?R("common:status.working"):g.status==="error"?R("common:status.error"):R("common:status.offline");return e.jsx("div",{className:`relative mb-0.5 ${$t&&Pt?.agentId===g.id?"opacity-40":""}`,onPointerDown:et=>ir(et,g.id,z),onPointerMove:Ut,onPointerUp:kt,children:e.jsxs("button",{onClick:()=>{$t||E(g.id)},onContextMenu:et=>{if(!H)return;et.preventDefault();const Xe=Ne(et);Xs(!1),Qs(""),Oe({agentId:g.id,teamId:z,...Xe})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ne?"":"touch-none"} ${ve?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${X?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(mt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:ve?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:g.name}),lt&&e.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",g.role,")"]}),ze&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),ue&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),ve&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:R("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:nt||" "})]}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(L?.get(g.id)??0)>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:L.get(g.id)}),g.mailboxDepth!=null&&g.mailboxDepth>0&&e.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:g.mailboxDepth}),e.jsx("span",{title:Ft,onClick:et=>{et.stopPropagation(),M(g.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Ae}`}),ne&&H&&e.jsx("span",{role:"button",tabIndex:0,onClick:et=>{if(et.stopPropagation(),He?.agentId===g.id)Oe(null);else{const Xe=Ne(et);Xs(!1),Qs(""),Oe({agentId:g.id,teamId:z,...Xe})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:R("chat.moreOptions"),children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},g.id)},_n=(g,z,X,ue)=>{const ve=$t&&js===g&&Pt?.fromTeamId!==g,Ae=rr===g,Ue=N===g,ze=L?(_t.byTeam.get(g)??[]).reduce((Ke,Kt)=>Ke+(L.get(Kt.id)??0),0):0,ke=m.find(Ke=>Ke.type==="team"&&Ke.teamId===g),Ye=ke&&G?G[ke.channelKey]??0:0,lt=ze+Ye,nt=_t.byTeam.get(g)??[],Ft=nt.filter(Ke=>Ke.status==="offline").length,et=nt.length,Xe=et>0&&Ft===et,St=Ft>0&&!Xe,xs=Xe?"bg-gray-500":St?"bg-amber-500":"bg-green-500";return e.jsxs("div",{"data-team-id":g,className:`mb-0.5 rounded-lg transition-all duration-500 ${ve?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Ae?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{$t&&rn(g)},onPointerLeave:()=>{$t&&js===g&&rn(null)},children:[e.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[e.jsxs("button",{onClick:()=>{I&&g!=="_ungrouped"&&I(g)},onContextMenu:Ke=>{if(!H||!z)return;Ke.preventDefault();const Kt=Ne(Ke);Be({teamId:g,...Kt})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${Xe?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ue?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${Xe?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),et>0&&e.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${xs}`})]}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[O===g?e.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:te,onChange:Ke=>st(Ke.target.value),onBlur:()=>En(g),onKeyDown:Ke=>{Ke.key==="Enter"&&En(g),Ke.key==="Escape"&&_e(null)},onClick:Ke=>Ke.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:ue}),e.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[R("chat.members_other",{count:X}),Xe&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:R("common:status.offline")}),St&&e.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Ft,"/",et]})]})]}),lt>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:lt}),e.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),H&&z&&e.jsx("button",{onClick:Ke=>{if(Ke.stopPropagation(),ae?.teamId===g)Be(null);else{const Kt=Ne(Ke);Be({teamId:g,...Kt})}},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:R("chat.moreOptions"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),ve&&$t&&e.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:R("chat.dropHere")})]},g)},je=r.useMemo(()=>{const g=new Map,z=[],X=[],ue=[];for(const ve of m)if(ve.channelKey.startsWith("dm:a2a:"))ue.push(ve);else if(ve.type==="custom")X.push(ve);else if(ve.teamId){const Ae=g.get(ve.teamId)??[];Ae.push(ve),g.set(ve.teamId,Ae)}else{const Ae=n.find(Ue=>ve.name.toLowerCase().includes(Ue.name.toLowerCase())||Ue.name.toLowerCase().includes(ve.name.toLowerCase()));if(Ae){const Ue=g.get(Ae.id)??[];Ue.push(ve),g.set(Ae.id,Ue)}else z.push(ve)}return{byTeam:g,unmatched:z,custom:X,dmChannels:ue}},[m,n]),[Se,Zt]=r.useState(!1),Ss=f==="channel"&&je.dmChannels.some(g=>g.channelKey===k);return r.useEffect(()=>{Ss&&Zt(!0)},[Ss]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`bg-surface-primary flex flex-col ${me!=null?"shrink-0":"flex-1 min-w-0"}`,style:Le?{display:"none"}:me!=null?{width:me}:void 0,children:[e.jsxs("div",{className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[ne&&e.jsx(ho,{}),!ne&&Q&&e.jsx("button",{onClick:Q,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsx("h2",{className:"text-lg font-semibold",children:R("chat.title")}),H&&e.jsxs("div",{className:"ml-auto relative",ref:Tn,children:[e.jsxs("button",{onClick:()=>Vt(!us),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[e.jsx("span",{className:"text-brand-500",children:"+"})," ",R("chat.manage"),e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${us?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),us&&e.jsxs("div",{ref:g=>{if(!g)return;const z=g.getBoundingClientRect(),X=window.innerWidth,ue=8;z.right>X-ue&&(g.style.left="auto",g.style.right="0"),z.left<ue&&(g.style.left="0",g.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-secondary border border-border-default rounded-lg shadow-xl z-30 overflow-hidden",children:[e.jsxs("button",{onClick:()=>{Vt(!1),it("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("circle",{cx:"12",cy:"5",r:"2"}),e.jsx("path",{d:"M12 7v4"}),e.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),R("chat.addAgent")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:R("chat.addAgentDesc")})]}),e.jsxs("button",{onClick:()=>{Vt(!1),it("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),e.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),R("chat.newTeam")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:R("chat.newTeamDesc")})]}),e.jsxs("button",{onClick:()=>{Vt(!1),zt(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M20 8v6"}),e.jsx("path",{d:"M23 11h-6"})]}),R("chat.addHuman")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:R("chat.addHumanDesc")})]}),e.jsxs("button",{onClick:()=>{Vt(!1),Wt(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),e.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),R("chat.newGroupChat")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:R("chat.newGroupChatDesc")})]}),Mt!==null&&e.jsxs("button",{onClick:()=>{Vt(!1),nn()},disabled:Pn,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 ${Mt?"text-green-600":"text-red-500"}`,children:[e.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Mt?e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",R("chat.resume")]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",R("contextMenu.stopAll")]})}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:R(Mt?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),e.jsxs("div",{ref:Jt,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:R("chat.people")}),i&&e.jsxs("button",{onClick:()=>b(i.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="dm"&&(j===i.id||!j)?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(mt,{name:i.name,avatarUrl:i.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:i.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:R("chat.myNotes")})]}),e.jsx("span",{className:"text-fg-secondary shrink-0",children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),o.filter(g=>g.id!==i?.id).map(g=>{const z=i?.id?`dm:${[i.id,g.id].sort().join(":")}`:"",X=z&&G?G[z]??0:0;return e.jsxs("button",{onClick:()=>b(g.id),onContextMenu:ue=>{if(!H||g.id===i?.id)return;ue.preventDefault();const ve=Ne(ue);Js({userId:g.id,...ve})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="dm"&&j===g.id?"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[e.jsx(mt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:g.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:g.email||g.role})]}),X>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:X}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},g.id)})]}),je.custom.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:R("chat.groups")}),je.custom.map(g=>{const z=f==="channel"&&k===g.channelKey;return e.jsxs("button",{onClick:()=>p(g.channelKey),onContextMenu:X=>{X.preventDefault();const ue=Ne(X);ds({gcId:g.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 text-fg-primary ${z?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:g.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:R("chat.members_other",{count:g.memberCount??0})})]})]},g.id)})]}),De?e.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((g,z)=>e.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[e.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),e.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},z))}):s.length===0&&n.length===0?e.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:R("chat.noAgentsYet")}):null,je.unmatched.map(g=>{const z=G?.[g.channelKey]??0;return e.jsxs("button",{onClick:()=>p(g.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="channel"&&k===g.channelKey?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:g.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:R("chat.groupChat")})]}),z>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:z}):g.memberCount!==void 0&&g.memberCount>0?e.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:g.memberCount}):null]},g.id)}),_t.ungrouped.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:R("chat.agents")}),_t.ungrouped.map(g=>Ot(g))]}),n.length>0&&e.jsxs("div",{className:"mb-2",ref:Mn,children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:R("chat.teams")}),n.map(g=>{const z=_t.byTeam.get(g.id)??[],X=g.members?.length||z.length;return _n(g.id,g,X,g.name)})]}),n.length===0&&_t.ungrouped.length===0&&s.length>0&&s.map(g=>Ot(g)),je.dmChannels.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsxs("button",{onClick:()=>Zt(g=>!g),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Se?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),R("chat.agentDMs"),e.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:je.dmChannels.length})]}),Se&&je.dmChannels.map(g=>{const z=f==="channel"&&k===g.channelKey,X=G?.[g.channelKey]??0,ue=g.name.replace(/^DM:\s*/,"");return e.jsxs("button",{onClick:()=>p(g.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${z?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:ue}),X>0&&e.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:X})]},g.id)})]})]})]}),Ee&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:Ee,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),ae&&(()=>{const g=_t.byTeam.get(ae.teamId)??[],z=g.some(ue=>ue.status==="offline"),X=g.some(ue=>ue.status!=="offline");return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:ae.x,top:ae.y},onClick:ue=>ue.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{const ue=ks.get(ae.teamId);ue&&(_e(ae.teamId),st(ue.name)),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),R("contextMenu.renameTeam")]}),z&&e.jsxs("button",{onClick:()=>{$s(ae.teamId,"start"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),R("contextMenu.startAll")]}),X&&e.jsxs("button",{onClick:()=>{$s(ae.teamId,"stop"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),R("contextMenu.stopAll")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{Be(null),os.navigate(at.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),R("chat.addAgent")]}),Z.length>0&&e.jsxs("button",{onClick:()=>{Be(null),Dt(ae.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),e.jsx("polyline",{points:"17 11 19 13 23 9"})]}),R("contextMenu.addExisting")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{const ue=ks.get(ae.teamId);ue&&Ns(ae.teamId,ue.name),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),R("contextMenu.deleteTeam")]})]})})(),He&&(()=>{const g=s.find(Ae=>Ae.id===He.agentId);if(!g||!H)return null;const X=(He.teamId?ks.get(He.teamId):void 0)?.managerId===g.id,ue=g.id===i?.id,ve=ot(g);return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:He.x,top:He.y,maxHeight:Math.max(160,window.innerHeight-He.y-8)},onClick:Ae=>Ae.stopPropagation(),children:[ve&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:R("contextMenu.orgSecretaryProtected")}),e.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),e.jsxs("button",{onClick:()=>{Oe(null),M(g.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),R("contextMenu.viewProfile")]}),g.status==="offline"?e.jsxs("button",{onClick:()=>{qe(g.id,"offline"),Oe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),R("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{qe(g.id,g.status??"idle"),Oe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),R("contextMenu.stop")]}),!ve&&He.teamId&&!X&&e.jsxs("button",{onClick:()=>{ar(He.teamId,g.id,"agent"),Oe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),R("contextMenu.setAsManager")]}),!ve&&He.teamId&&e.jsxs("button",{onClick:()=>{vt(He.teamId,g.id),Oe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),R("contextMenu.removeFromTeam")]}),!ve&&(()=>{const Ae=n.filter(ke=>ke.id!==He.teamId);if(Ae.length===0)return null;const Ue=Cn.trim().toLowerCase(),ze=Ue?Ae.filter(ke=>ke.name.toLowerCase().includes(Ue)):Ae;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>Xs(ke=>!ke),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:R("contextMenu.moveTo")}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${gt?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),gt&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:ke=>ke.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:Cn,onChange:ke=>Qs(ke.target.value),onKeyDown:ke=>ke.stopPropagation(),placeholder:R("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:ze.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:R("contextMenu.moveToEmpty")}):ze.map(ke=>e.jsx("button",{type:"button",onClick:async()=>{He.teamId&&await A.teams.removeMember(He.teamId,g.id),await A.teams.addMember(ke.id,g.id,"agent"),_(),h(),bt(),Oe(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:ke.name,children:ke.name},ke.id))})]})]})})(),!ve&&!ue&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{yt(g.id,g.name,"agent"),Oe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),R("contextMenu.removeFromOrg")]})]})]})})(),Ht&&(()=>{const g=o.find(z=>z.id===Ht.userId);return!g||!H?null:e.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Ht.x,top:Ht.y},onClick:z=>z.stopPropagation(),children:e.jsxs("button",{onClick:()=>{yt(g.id,g.name,"human"),Js(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),R("contextMenu.removeFromOrg")]})})})(),ye&&e.jsx(tl,{onClose:()=>dt(!1),onCreate:async(g,z)=>{try{const{team:X}=await A.teams.create(g,z);dt(!1),_(),bs(X.id),setTimeout(()=>{document.querySelector(`[data-team-id="${X.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>bs(null),3e3)}catch(X){vs(R("chat.failedToCreateTeam",{message:X instanceof Error?X.message:String(X)}),"error")}}}),ht&&e.jsx(sl,{onClose:()=>{zt(!1),T?.()},onAdd:async(g,z,X)=>{const{inviteToken:ue}=await A.users.create(g,z,void 0,X);return T?.(),{inviteToken:ue}}}),ls!==null&&e.jsx(nl,{teamId:ls,ungrouped:Z,onClose:()=>Dt(null),onAdd:async(g,z)=>{await A.teams.addMember(ls,g,z),Dt(null),_(),bt()}}),Qt&&e.jsx(rl,{onClose:()=>cs(!1),onConnected:()=>{cs(!1),h(),_()}}),ps&&(()=>{const g=m.find(z=>z.id===ps.gcId);return g?e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:ps.x,top:ps.y},onClick:z=>z.stopPropagation(),children:[g.type==="custom"&&e.jsxs("button",{onClick:()=>{ds(null),P?P(g.channelKey):p(g.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),R("contextMenu.manageMembers")]}),e.jsxs("button",{onClick:async()=>{ds(null),Rs(R("modals.deleteGroupChat.title"),R("modals.deleteGroupChat.message",{name:g.name}),async()=>{await A.groupChats.delete(g.id),D()},R("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),R("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ls&&e.jsx(al,{agents:s,humans:o,authUser:i,onClose:()=>Wt(!1),onCreate:async(g,z,X,ue)=>{await A.groupChats.create({name:g,memberIds:z,memberTypes:X,memberNames:ue,creatorId:i?.id,creatorName:i?.name}),Wt(!1),D()}}),xt&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>it(null),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:R(xt==="agent"?"chat.addAgent":"chat.newTeam")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:R("chat.methodChoiceSubtitle")})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>{const g=xt;it(null);const z=s.find(X=>X.role==="secretary")??s.find(X=>X.name?.toLowerCase().includes("secretary"));z?(E(z.id),os.navigate(at.TEAM,{agentId:z.id,prefillMessage:R(g==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):g==="agent"?os.navigate(at.STORE):dt(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),e.jsx("path",{d:"M20 3v4"}),e.jsx("path",{d:"M22 5h-4"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:R("chat.methodSecretary")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:R("chat.methodSecretaryDesc")})]}),e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:R("chat.recommended")})]}),e.jsxs("button",{onClick:()=>{const g=xt;it(null),g==="agent"?os.navigate(at.STORE):dt(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:R("chat.methodManual")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:R(xt==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),e.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:e.jsx("button",{onClick:()=>it(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:R("common:cancel")})})]})}),qt&&e.jsx(Sn,{title:qt.title,message:qt.message,confirmLabel:qt.confirmLabel,checkboxes:qt.checkboxes,onConfirm:g=>{qt.onConfirm(g),ys(null)},onCancel:()=>ys(null)}),en&&e.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${en.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:en.message})]})});function Fa({team:a,agents:i,humans:s,authUser:n,groupChat:o,chatMode:l,selectedAgent:u,activeChannel:m,teams:f,onSelectAgent:y,onSelectChannel:k,onSelectDm:j,onBack:E,onViewProfile:p,onRefreshAgents:b,onRefreshTeams:I,unreadByAgent:N,width:_,onResizeStart:h}){const{t:T}=Ve(["team","common"]),D=n?.role==="owner"||n?.role==="admin",M=r.useMemo(()=>i.filter(w=>w.teamId===a.id),[i,a.id]),P=r.useMemo(()=>{const w=new Set((a.members??[]).filter(Z=>Z.type==="human").map(Z=>Z.id));return s.filter(Z=>w.has(Z.id))},[a.members,s]),L=o&&l==="channel"&&m===o.channelKey,[G,me]=r.useState(null),[Ee,Le]=r.useState(!1),[Q,De]=r.useState(""),be=r.useCallback((w,Z=176,ie=220)=>{const Re=window.innerWidth,$e=window.innerHeight,ye=8;let dt=w.clientX,ht=w.clientY;return dt+Z>Re-ye&&(dt=Math.max(ye,Re-Z-ye)),ht+ie>$e-ye&&(ht=Math.max(ye,$e-ie-ye)),dt=Math.max(ye,Math.min(dt,Re-Z-ye)),ht=Math.max(ye,Math.min(ht,$e-ie-ye)),{x:dt,y:ht}},[]);r.useEffect(()=>{if(!G)return;const w=()=>me(null),Z=setTimeout(()=>document.addEventListener("click",w),0);return()=>{clearTimeout(Z),document.removeEventListener("click",w)}},[G]);const R=r.useCallback(async(w,Z)=>{Z==="offline"?await A.agents.start(w):await A.agents.stop(w),b()},[b]),ne=r.useCallback(async w=>{await A.teams.update(a.id,{managerId:w,managerType:"agent"}),I()},[a.id,I]),v=r.useCallback(async w=>{await A.teams.removeMember(a.id,w),I(),b()},[a.id,I,b]),H=r.useCallback(async(w,Z)=>{await A.teams.removeMember(a.id,w),await A.teams.addMember(Z,w,"agent"),I(),b()},[a.id,I,b]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-surface-primary flex flex-col shrink-0",style:_!=null?{width:_}:{width:260},children:[e.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:E,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:T("common:back",{defaultValue:"Back"}),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"truncate font-semibold text-sm",children:a.name}),a.description&&e.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:a.description})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[o&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:T("chat.groupChat",{defaultValue:"Group Chat"})}),e.jsxs("button",{onClick:()=>k(o.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${L?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:a.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:T("chat.members_other",{count:o.memberCount||M.length+P.length})})]})]})]}),M.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[T("chat.agents",{defaultValue:"Agents"}),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:M.length})]}),M.map(w=>{const Z=l==="direct"&&u===w.id,ie=a.managerId===w.id,Re=w.status==="offline",$e=w.status==="idle"?"bg-green-500":w.status==="working"?"bg-blue-500 animate-pulse":w.status==="error"?"bg-red-500":"bg-gray-600";return e.jsxs("button",{onClick:()=>y(w.id),onContextMenu:ye=>{if(!D)return;ye.preventDefault();const dt=be(ye);Le(!1),De(""),me({agentId:w.id,...dt})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${Re?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Z?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(mt,{name:w.name,avatarUrl:w.avatarUrl,size:28,bgClass:Re?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:w.name}),ie&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Re&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:T("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:w.role||" "})]}),(N?.get(w.id)??0)>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:N.get(w.id)}),e.jsx("span",{title:w.status,onClick:ye=>{ye.stopPropagation(),p(w.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${$e}`})]},w.id)})]}),P.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[T("chat.people"),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:P.length})]}),P.map(w=>{const Z=w.id===n?.id;return e.jsxs("button",{onClick:()=>j(w.id),className:"w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary hover:bg-white/[0.08]",children:[e.jsx(mt,{name:w.name,avatarUrl:w.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[w.name,Z?` (${T("chat.you",{defaultValue:"You"})})`:""]}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:w.email||w.role})]}),e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},w.id)})]}),M.length===0&&P.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:T("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),h&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:h,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),G&&(()=>{const w=M.find(ie=>ie.id===G.agentId);if(!w||!D)return null;const Z=a.managerId===w.id;return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:G.x,top:G.y,maxHeight:Math.max(160,window.innerHeight-G.y-8)},onClick:ie=>ie.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{me(null),p(w.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),T("contextMenu.viewProfile")]}),w.status==="offline"?e.jsxs("button",{onClick:()=>{R(w.id,"offline"),me(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),T("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{R(w.id,w.status??"idle"),me(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),T("contextMenu.stop")]}),!Z&&e.jsxs("button",{onClick:()=>{ne(w.id),me(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),T("contextMenu.setAsManager")]}),e.jsxs("button",{onClick:()=>{v(w.id),me(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),T("contextMenu.removeFromTeam")]}),(()=>{const ie=f.filter(ye=>ye.id!==a.id);if(ie.length===0)return null;const Re=Q.trim().toLowerCase(),$e=Re?ie.filter(ye=>ye.name.toLowerCase().includes(Re)):ie;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>Le(ye=>!ye),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:T("contextMenu.moveTo")}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${Ee?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),Ee&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:ye=>ye.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:Q,onChange:ye=>De(ye.target.value),onKeyDown:ye=>ye.stopPropagation(),placeholder:T("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:$e.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:T("contextMenu.moveToEmpty")}):$e.map(ye=>e.jsx("button",{type:"button",onClick:()=>{H(w.id,ye.id),me(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:ye.name,children:ye.name},ye.id))})]})]})})(),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:async()=>{await A.agents.remove(w.id),b(),me(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),T("contextMenu.removeFromOrg")]})]})})()]})}function ol({url:a,browserId:i,className:s}){const n=r.useId().replace(/:/g,""),o=i||`eb_${n}`,l=!i,u=r.useRef(null),m=r.useRef(null),[f,y]=r.useState(a==="about:blank"?"":a),[k,j]=r.useState(!1),[E,p]=r.useState(!1),b=typeof window<"u"?window.markusDesktop?.browser:void 0;return r.useEffect(()=>{if(!b)return;let I=!1;return(async()=>{const N=await b.getState(o);I||(N.ok?a&&N.url!==a&&await b.navigate(o,a):await b.create(o,a),!I&&document.activeElement!==m.current&&y(!N.ok||a==="about:blank"?a==="about:blank"?"":a:N.url&&N.url!=="about:blank"?N.url:""))})(),()=>{I=!0,l&&b.destroy(o)}},[b,o,a,l]),r.useEffect(()=>{if(a!=="about:blank")return;const I=window.setTimeout(()=>{m.current?.focus(),m.current?.select()},0);return()=>clearTimeout(I)},[a,o]),r.useEffect(()=>{if(!b||!u.current)return;const I=u.current;let N=!0;const _=()=>{let P=I;for(;P;){const L=getComputedStyle(P);if(L.visibility==="hidden"||L.display==="none")return!1;P=P.parentElement}return!0},h=()=>{if(!N)return;if(!bo()||!_()||po()){b.setBounds(o,{x:0,y:0,width:0,height:0},!1);return}const P=I.getBoundingClientRect();b.setBounds(o,{x:Math.round(P.left),y:Math.round(P.top),width:Math.round(P.width),height:Math.round(P.height)},P.width>2&&P.height>2)};h();const T=new ResizeObserver(h);T.observe(I),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0),window.addEventListener("markus:embedded-browser-resync",h),window.addEventListener("markus:native-browser-overlay",h),window.addEventListener("markus:native-browser-page",h);const D=setInterval(()=>{N&&b.getState(o).then(P=>{!N||!P.ok||(P.url&&document.activeElement!==m.current&&y(P.url==="about:blank"?"":P.url),j(!!P.canGoBack),p(!!P.canGoForward))})},800),M=()=>{b.setBounds(o,{x:0,y:0,width:0,height:0},!1)};return window.addEventListener("pagehide",M),()=>{N=!1,T.disconnect(),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0),window.removeEventListener("markus:embedded-browser-resync",h),window.removeEventListener("markus:native-browser-overlay",h),window.removeEventListener("markus:native-browser-page",h),window.removeEventListener("pagehide",M),clearInterval(D),b.setBounds(o,{x:0,y:0,width:0,height:0},!1)}},[b,o]),b?e.jsxs("div",{className:`flex flex-col h-full min-h-0 min-w-0 w-full ${s??""}`,children:[e.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2 py-1.5 border border-border-default rounded-lg bg-surface-elevated mb-2",children:[e.jsx("button",{disabled:!k,onClick:()=>{b.action(o,"back")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Back",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("button",{disabled:!E,onClick:()=>{b.action(o,"forward")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Forward",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})}),e.jsx("button",{onClick:()=>{b.action(o,"reload")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay",title:"Reload",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),e.jsx("form",{className:"flex-1 min-w-0",onSubmit:I=>{I.preventDefault();let N=f.trim();N&&(N!=="about:blank"&&!/^https?:\/\//i.test(N)&&(N=`https://${N}`),b.navigate(o,N),y(N))},children:e.jsx("input",{ref:m,value:f,onChange:I=>y(I.target.value),placeholder:"Enter a URL",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md text-fg-primary outline-none focus:border-brand-500"})})]}),e.jsx("div",{ref:u,className:"flex-1 min-h-0 min-w-0 w-full rounded-lg border border-border-default bg-surface-elevated/30"})]}):e.jsxs("div",{className:`space-y-3 ${s??""}`,children:[e.jsx("p",{className:"text-sm text-fg-secondary break-all",children:a}),e.jsx("button",{onClick:()=>window.open(a,"_blank","noopener,noreferrer"),className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:"Open in browser"})]})}function Ba(a){return/^https?:\/\//i.test(a)}function ll(a){return a.kind==="deliverable"?a.deliverable.reference??"":a.kind==="url"?a.url:a.path}function cl(a){return a.kind==="deliverable"?a.deliverable.title||a.deliverable.reference||"":a.kind==="url"?a.title||a.url:a.title||a.path.split(/[/\\]/).pop()||a.path}function dl(a,i){if(a.kind==="file")return`file:${a.path}:${i??""}`;if(a.kind==="url")return`url:${a.browserId||a.url}:${i??""}`;const s=a.deliverable;return`deliverable:${s.id||s.reference||s.title||"unknown"}:${i??""}`}function Rr(a){return a==null||!Number.isFinite(a)?"":a<1024?`${a} B`:a<1024*1024?`${(a/1024).toFixed(1)} KB`:`${(a/(1024*1024)).toFixed(1)} MB`}function ul({payload:a,onClose:i,width:s,onResizeStart:n,onAddToChat:o,tabs:l,activeTabId:u,onSelectTab:m,onCloseTab:f,onNewTab:y,fullscreen:k,onToggleFullscreen:j}){const{t:E}=Ve(["deliverables","agent","common"]),[p,b]=r.useState({mode:"loading"}),[I,N]=r.useState(!1),[_,h]=r.useState(null),T=r.useRef(null),D=r.useRef(null),M=r.useRef(null),P=ll(a),L=cl(a),G=(l?.length??0)>=1,me=dl(a,u);r.useEffect(()=>{if(!u)return;const v=M.current,H=D.current;if(!v||!H)return;const w=requestAnimationFrame(()=>{v.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(w)},[u,l?.length]),r.useEffect(()=>{const v=H=>{H.key==="Escape"&&(k&&j?j():i())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[i,k,j]),r.useEffect(()=>{let v=!1;return h(null),b({mode:"loading"}),a.kind==="deliverable"&&a.deliverable.artifactType&&a.deliverable.artifactData?(b({mode:"artifact",summary:a.deliverable.summary||a.deliverable.title||""}),()=>{v=!0}):a.kind==="url"?(b({mode:"url",url:a.url,browserId:a.browserId}),()=>{v=!0}):P?Ba(P)?(b({mode:"url",url:P}),()=>{v=!0}):a.kind==="deliverable"&&a.deliverable.type==="directory"?(b({mode:"unpreviewable",reference:P,isDirectory:!0}),()=>{v=!0}):(A.files.preview(P).then(w=>{if(v)return;if(w.type==="image"){b({mode:"image",src:`data:${w.mimeType||"image/png"};base64,${w.content}`,name:w.name||L});return}if(w.type==="audio"){const ie=w.streamUrl||(w.path?A.files.streamUrl(w.path):A.files.streamUrl(P));b({mode:"audio",src:ie,name:w.name||L,mimeType:w.mimeType||"audio/mpeg",size:w.size});return}if(w.type==="video"){const ie=w.streamUrl||(w.path?A.files.streamUrl(w.path):A.files.streamUrl(P));b({mode:"video",src:ie,name:w.name||L,mimeType:w.mimeType||"video/mp4",size:w.size});return}if(w.type==="binary"){b({mode:"binary",name:w.name||L,reference:w.path||P,size:w.size,extension:w.extension});return}if(typeof w.content!="string"){b({mode:"unpreviewable",reference:P,isDirectory:!1});return}const Z=Oo({format:a.kind==="deliverable"?a.deliverable.format:void 0,reference:P,content:w.content});b({mode:"content",content:w.content,format:Z})}).catch(()=>{v||b({mode:"unpreviewable",reference:P,isDirectory:!1})}),()=>{v=!0}):(b({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{v=!0})},[me,a,P,L]);const Ee=L||P,Le=r.useCallback((v,H)=>{const w=v.length>40?`${v.slice(0,24)}…${v.slice(-12)}`:v;return H?{label:`🌐 ${w}`,content:["[html-selection]",`Text: "${v}"`,`CSS Selector: ${H.cssSelector}`,`XPath: ${H.xpath}`,P?`File: ${P}`:""].filter(Boolean).join(`
6
+ `)}:{label:`“${w}”`,content:`${E("deliverables:chat.selectedFrom",{defaultValue:"Selected from"})} ${Ee}:
7
+
8
+ """
9
+ ${v}
10
+ """`}},[P,Ee,E]),Q=r.useCallback((v,H)=>{!v.trim()||!o||(o(Le(v.trim(),H)),h(null),window.getSelection()?.removeAllRanges())},[o,Le]),De=r.useCallback(v=>{if(!v.text.trim()||!o)return;const H=T.current?.querySelector("iframe")?.getBoundingClientRect(),w=(H?.left??0)+v.rect.x+v.rect.width/2,Z=(H?.top??0)+v.rect.y;h({x:w,y:Z,text:v.text,htmlMeta:{xpath:v.xpath,cssSelector:v.cssSelector}})},[o]);r.useEffect(()=>{const v=T.current;if(!v||!o)return;const H=()=>{requestAnimationFrame(()=>{const Z=window.getSelection(),ie=Z?.toString().trim();if(!ie||!Z?.rangeCount){h(null);return}const Re=Z.getRangeAt(0);if(!v.contains(Re.commonAncestorContainer)){h(null);return}const $e=Re.getBoundingClientRect();h({x:$e.left+$e.width/2,y:$e.top,text:ie})})},w=Z=>{const ie=document.getElementById("right-panel-selection-toolbar");ie&&ie.contains(Z.target)||h(null)};return v.addEventListener("mouseup",H),document.addEventListener("mousedown",w),()=>{v.removeEventListener("mouseup",H),document.removeEventListener("mousedown",w)}},[o,p.mode]);const be=()=>{A.files.reveal(P).catch(()=>{})},R=()=>{navigator.clipboard?.writeText(P).then(()=>{N(!0),setTimeout(()=>N(!1),1500)}).catch(()=>{})},ne=!!P&&!Ba(P)&&(a.kind==="file"||a.kind==="deliverable");return e.jsxs(e.Fragment,{children:[!k&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:n,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),e.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${k?"flex-1 min-w-0":"shrink-0"}`,style:k?void 0:{width:s},"data-right-panel":!0,children:[e.jsxs("header",{className:"h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default",children:[G||y?e.jsxs("div",{ref:D,className:"flex-1 min-w-0 flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-thin",onWheel:v=>{const H=v.currentTarget;H.scrollWidth<=H.clientWidth||Math.abs(v.deltaY)<=Math.abs(v.deltaX)||(H.scrollLeft+=v.deltaY,v.preventDefault())},children:[l?.map(v=>{const H=v.id===u;return e.jsxs("button",{type:"button",ref:H?M:void 0,className:`group shrink-0 flex items-center gap-1 max-w-[160px] pl-2.5 pr-1 py-1 rounded-md text-[11px] cursor-pointer border transition-colors ${H?"bg-surface-elevated border-border-default text-fg-primary":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>m?.(v.id),title:v.title,children:[e.jsx("span",{className:"truncate min-w-0",children:v.title}),f&&e.jsx("span",{role:"button",tabIndex:0,onClick:w=>{w.stopPropagation(),f(v.id)},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),w.stopPropagation(),f(v.id))},className:`shrink-0 p-0.5 rounded hover:bg-surface-overlay transition-colors ${H?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:E("common:closeTab",{defaultValue:"Close tab"}),"aria-label":E("common:closeTab",{defaultValue:"Close tab"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},v.id)}),y&&e.jsx("button",{type:"button",onClick:y,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:E("common:newTab",{defaultValue:"New Tab"}),"aria-label":E("common:newTab",{defaultValue:"New Tab"}),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):e.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:P||L,children:L}),e.jsxs("div",{className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[a.kind==="deliverable"&&e.jsx("button",{onClick:()=>os.navigate(at.DELIVERABLES,{openDeliverable:a.deliverable.id}),title:E("agent:deliverables.openInPage",{defaultValue:"Open in page"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),ne&&e.jsx("button",{onClick:be,title:E("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":E("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),j&&e.jsx("button",{onClick:j,title:k?E("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):E("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:k?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"4 14 10 14 10 20"}),e.jsx("polyline",{points:"20 10 14 10 14 4"}),e.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("polyline",{points:"9 21 3 21 3 15"}),e.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),e.jsx("button",{onClick:i,title:E("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":E("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),e.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${p.mode==="url"?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[p.mode==="loading"&&e.jsxs("div",{className:"animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),e.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),p.mode==="image"&&e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("img",{src:p.src,alt:p.name,className:"max-w-full rounded-lg object-contain"}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:p.name})]}),p.mode==="audio"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 18V5l12-2v13"}),e.jsx("circle",{cx:"6",cy:"18",r:"3"}),e.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:p.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p.mimeType,p.size!=null?` · ${Rr(p.size)}`:""]})]})]}),e.jsx("audio",{controls:!0,preload:"metadata",src:p.src,className:"w-full"})]}),p.mode==="video"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[e.jsx("video",{controls:!0,preload:"metadata",src:p.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:[p.name,p.size!=null?` · ${Rr(p.size)}`:""]})]}),p.mode==="binary"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(p.extension||"file").replace(/^\./,"")||"file"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:p.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[E("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),p.size!=null?` · ${Rr(p.size)}`:""]})]})]}),p.reference&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:()=>{A.files.reveal(p.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:E("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),p.mode==="content"&&e.jsx("div",{ref:T,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:e.jsx(Ea,{content:p.content,format:p.format,className:"text-fg-secondary text-sm",onHtmlSelection:De})}),p.mode==="artifact"&&e.jsx("div",{ref:T,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:e.jsx(Ea,{content:p.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),p.mode==="url"&&e.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:e.jsx(ol,{url:p.url,browserId:p.browserId,className:"flex-1 min-h-0"})}),p.mode==="unpreviewable"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-fg-secondary",children:p.isDirectory?E("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):E("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),p.reference&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:be,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:E("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:p.reference}),e.jsx("button",{onClick:be,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:E("common:open",{defaultValue:"Open"})}),e.jsx("button",{onClick:R,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${I?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:I?E("common:copied",{defaultValue:"Copied"}):E("common:copy",{defaultValue:"Copy"})})]})]})]},me)]}),_&&o&&e.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden",style:{left:_.x,top:_.y-8},children:e.jsxs("button",{onMouseDown:v=>{v.preventDefault(),v.stopPropagation(),Q(_.text,_.htmlMeta)},className:"px-3 py-1.5 text-xs text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),E("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const ml=r.lazy(()=>fi(()=>import("./index-D_HH4ju2.js").then(a=>a.al),__vite__mapDeps([0,1])).then(a=>({default:a.MarkdownMessage}))),Wr=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Fr(a,i){return i(`agent:profilePage.taskStatus.${a}`,{defaultValue:a.replace(/_/g," ")})}function pi(a,i){const n={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[a];return n?i(n):a}const bi={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function Gs(a){return a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${(a/1e3).toFixed(1)}K`:a.toLocaleString()}function za({agentId:a,onBack:i,inline:s,defaultTab:n,onSwipeBack:o,highlightMailboxId:l,authUser:u,headless:m,activeTab:f}){const{t:y}=Ve(["agent","common"]),k=zr(),[j,E]=r.useState(null),[p,b]=r.useState(null),[I,N]=r.useState(n??"overview"),_=m&&f?f:I,[h,T]=r.useState(null),D=r.useMemo(()=>Wr.map(Q=>({...Q,label:y(`agent:tabs.${Q.key}`)})),[y]),M=r.useMemo(()=>D.map(Q=>({id:Q.key})),[D]),P=r.useMemo(()=>({onSwipeOutLeft:o}),[o]),L=di(M,I,N,P),G=r.useRef(null);r.useEffect(()=>{const Q=G.current;if(!Q)return;Q.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[I]);const me=r.useCallback(()=>{A.agents.get(a).then(E).catch(()=>{})},[a]);if(r.useEffect(()=>(N(n??"overview"),T(null),me(),A.externalAgents.list().then(De=>{const be=De.agents.find(R=>R.markusAgentId===a);T(be??null)}).catch(()=>{}),Fe.on("agent:update",De=>{De.payload.agentId===a&&me()})),[a,me]),!j)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:y("agent:profilePage.loadingAgent")});const Ee=bi[j.state.status]??"bg-gray-500",Le=u?.role==="owner"||u?.role==="admin";return m?e.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:e.jsxs("div",{className:"p-5",children:[(_==="overview"||_==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(Wa,{agent:j,onUpdate:me,externalInfo:h,t:y,canManageAgents:Le}),e.jsx("div",{className:"mt-6",children:e.jsx(si,{agentId:a,highlightId:l,agentStatus:j.state.status,canManageAgents:Le,onAgentStateChange:me})})]}),_==="files"&&e.jsx(qa,{agentId:a}),_==="tools"&&e.jsx(Ua,{tools:j.tools??[],agent:j}),_==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ga,{agentId:a,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(Ka,{agentId:a})})]}),_==="deliverables"&&e.jsx(ni,{agentId:a})]})}):e.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(mt,{name:j.name,avatarUrl:j.avatarUrl,size:40,className:"rounded-xl"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:j.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${Ee}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:pi(j.state.status,y)}),h&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:y("agent:profilePage.badges.external")}),j.agentRole==="manager"&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:y("agent:profilePage.badges.manager")})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[j.role,j.roleDescription?` — ${j.roleDescription}`:""]})]}),e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!s&&e.jsxs("button",{onClick:()=>os.navigate(at.TEAM,{agentId:a}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[e.jsx("span",{children:"◈"})," ",y("agent:profilePage.chat")]}),Le&&e.jsxs("button",{onClick:async()=>{if(j)try{const{filesMap:Q}=await A.agents.getFilesMap(a),De={type:"agent",name:ui(j.name,j.name),displayName:j.name,version:"1.0.0",description:j.roleDescription??j.role,author:"",category:"general",tags:[],agent:{roleName:j.role,agentRole:j.agentRole},dependencies:{skills:j.skills??[]}};await mi.publishViaProxy({itemType:"agent",name:j.name,description:De.description,category:"general",config:De,files:Q}),b({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishSuccess",{name:j.name}),variant:"primary"})}catch(Q){b({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishFailed",{error:String(Q)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:y("agent:profilePage.publishTitle"),children:[e.jsx("span",{children:"↑"})," ",y("agent:profilePage.hub")]}),s&&e.jsx("button",{onClick:i,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),e.jsx("div",{ref:G,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:D.filter(Q=>!h||["overview","mind"].includes(Q.key)).map(Q=>e.jsxs("button",{onClick:()=>N(Q.key),"data-active":I===Q.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${I===Q.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{className:"mr-1",children:Q.icon}),Q.label]},Q.key))})]}),e.jsxs("div",{className:"p-5",onTouchStart:k?L.onTouchStart:void 0,onTouchEnd:k?L.onTouchEnd:void 0,children:[(I==="overview"||I==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(Wa,{agent:j,onUpdate:me,externalInfo:h,t:y,canManageAgents:Le}),e.jsx("div",{className:"mt-6",children:e.jsx(si,{agentId:a,highlightId:l,agentStatus:j.state.status,canManageAgents:Le,onAgentStateChange:me})})]}),I==="files"&&e.jsx(qa,{agentId:a}),I==="tools"&&e.jsx(Ua,{tools:j.tools??[],agent:j}),I==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ga,{agentId:a,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(Ka,{agentId:a})})]}),I==="deliverables"&&e.jsx(ni,{agentId:a})]}),p&&e.jsx(Sn,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function Wa({agent:a,onUpdate:i,externalInfo:s,t:n,canManageAgents:o}){const[l,u]=r.useState(null),[m,f]=r.useState([]),[y,k]=r.useState(null),[j,E]=r.useState(null),[p,b]=r.useState(""),[I,N]=r.useState([]);r.useEffect(()=>{A.usage.agents().then(L=>{const G=L.agents.find(me=>me.agentId===a.id);G&&u(G)}).catch(()=>{}),A.agents.getRecentActivities(a.id).then(L=>f(L.activities)).catch(()=>{}),A.system.storage().then(L=>{b(L.dataDir+"/agents/"+a.id);const G=L.agents.find(me=>me.id===a.id);G&&E(G)}).catch(()=>{}),a.state.activeTaskIds?.length&&A.tasks.list({assignedAgentId:a.id}).then(L=>{N(L.tasks.filter(G=>a.state.activeTaskIds?.includes(G.id)))}).catch(()=>{})},[a.id,a.state.activeTaskIds]);const _=()=>{a.state.status==="offline"?A.agents.start(a.id).then(i):A.agents.stop(a.id).then(i)},h=r.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:n("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:n("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:n("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:n("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:n("agent:profilePage.gateway.requirements")}],[n]),T=r.useMemo(()=>[{field:"assignedTasks",desc:n("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:n("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:n("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:n("agent:profilePage.syncContext.projectContext")}],[n]);if(s)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ze,{title:n("agent:profilePage.overview.identity"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(Nt,{label:n("agent:profilePage.overview.labels.name"),children:a.name}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:a.agentRole==="manager"?"text-amber-600":"text-blue-600",children:a.agentRole==="manager"?n("agent:profilePage.roles.managerDisplay"):n("agent:profilePage.roles.workerDisplay")})}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.roleTemplate"),children:a.role}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:a.id}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.organization"),children:a.config?.orgId??"default"}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.created"),children:a.config?.createdAt?new Date(a.config.createdAt).toLocaleDateString():n("agent:profilePage.emDash")})]})}),e.jsx(Ze,{title:n("agent:profilePage.overview.connectionStatus"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(rt,{label:n("agent:profilePage.overview.labels.connection"),value:s.connected?n("common:status.online"):n("common:status.offline"),color:s.connected?"green":"gray"}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.platform"),value:n("agent:profilePage.overview.openClaw")}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.activeTasks"),value:String(a.state.activeTaskIds?.length??0)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.lastSync"),value:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleTimeString():n("agent:profilePage.never")})]})}),e.jsx(Ze,{title:n("agent:profilePage.overview.externalAgentDetails"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(Nt,{label:n("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:s.externalAgentId}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.registered"),children:new Date(s.registeredAt).toLocaleString()}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.capabilities"),children:s.capabilities.length>0?s.capabilities.join(", "):n("agent:profilePage.overview.noneDeclared")}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.lastHeartbeat"),children:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleString():n("agent:profilePage.never")})]})}),e.jsx(Ze,{title:n("agent:profilePage.overview.syncContextTitle"),children:e.jsx("div",{className:"space-y-1.5",children:T.map(L=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:L.field}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:L.desc})]},L.field))})}),e.jsx(Ze,{title:n("agent:profilePage.overview.gatewayEndpoints"),children:e.jsx("div",{className:"space-y-1.5",children:h.map(L=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${L.method==="POST"?"text-amber-600":"text-green-600"}`,children:L.method}),e.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:L.path}),e.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:L.desc})]},L.path))})})]});const D=m.filter(L=>L.type==="heartbeat").length,M=m.filter(L=>L.type==="chat").length,P=a.state.activeTaskIds?.length??0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(Nt,{label:n("agent:profilePage.overview.labels.roleTemplate"),children:a.role}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:a.agentRole==="manager"?"text-amber-600":"text-blue-600",children:a.agentRole==="manager"?n("agent:profilePage.roles.managerDisplay"):n("agent:profilePage.roles.workerDisplay")})}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.agentId"),mono:!0,children:a.id}),e.jsx(Nt,{label:n("agent:profilePage.overview.labels.created"),children:a.config?.createdAt?new Date(a.config.createdAt).toLocaleDateString():n("agent:profilePage.emDash")})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${bi[a.state.status]||"bg-gray-500"}`}),e.jsx("span",{className:`text-sm font-semibold ${a.state.status==="idle"?"text-green-500":a.state.status==="working"?"text-blue-400":a.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:pi(a.state.status,n)})]}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.tokensToday"),value:Gs(a.state.tokensUsedToday)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.activeTasks"),value:String(P),color:P>0?"blue":void 0}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.lastHeartbeat"),value:a.state.lastHeartbeat?new Date(a.state.lastHeartbeat).toLocaleTimeString():n("agent:profilePage.never")}),o&&e.jsx("button",{onClick:_,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:a.state.status==="offline"?n("agent:profilePage.overview.startAgent"):n("agent:profilePage.overview.stopAgent")})]}),a.state.status==="error"&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-red-500",children:n("agent:profilePage.overview.errorDetails")}),a.state.lastErrorAt&&e.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(a.state.lastErrorAt).toLocaleString()})]}),e.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:tr(a.state.lastError,n)||a.state.lastError||n("agent:profilePage.overview.errorFallback")})]}),a.state.status==="working"&&P>0&&e.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:e.jsx("div",{className:"space-y-1",children:I.map(L=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsx("span",{className:"text-fg-secondary truncate flex-1",children:L.title}),e.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Fr(L.status,n)})]},L.id))})}),l&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(rt,{label:n("agent:profilePage.overview.labels.totalTokens"),value:Gs(l.totalTokens)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.requests"),value:String(l.requestCount)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.toolCalls"),value:String(l.toolCalls)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.promptTokens"),value:Gs(l.promptTokens)}),e.jsx(rt,{label:n("agent:profilePage.overview.labels.completionTokens"),value:Gs(l.completionTokens)}),e.jsx(rt,{label:"CU Used",value:Gs(l.cuUsed??0)})]})]}),j&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(rt,{label:n("agent:profilePage.overview.storage"),value:Ja(j.size)}),j.subItems.filter(L=>L.size>0).map(L=>e.jsx(rt,{label:L.name,value:Ja(L.size)},L.name)),e.jsxs("button",{onClick:()=>{A.system.openPath(p)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[n("agent:profilePage.overview.openFolder")," →"]})]})]})]}),D>0&&e.jsx(Ze,{title:n("agent:profilePage.overview.recentHeartbeats"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.overview.heartbeatRuns",{count:D})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(L=>L.type==="heartbeat").map(L=>{const G=y===L.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(G?null:L.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:L.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(L.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:G?"▲":"▼"})]}),G&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(kn,{agentId:a.id,activityId:L.id})})]},L.id)})})}),M>0&&e.jsx(Ze,{title:n("agent:profilePage.overview.recentA2A"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.overview.conversations",{count:M})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(L=>L.type==="chat").map(L=>{const G=y===L.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(G?null:L.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:L.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(L.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:G?"▲":"▼"})]}),G&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(kn,{agentId:a.id,activityId:L.id})})]},L.id)})})})]})}function xl(a,i){const s=a.split(`
11
+ `),n=i.split(`
12
+ `),o=s.length,l=n.length,u=Array.from({length:o+1},()=>new Array(l+1).fill(0));for(let E=o-1;E>=0;E--)for(let p=l-1;p>=0;p--)u[E][p]=s[E]===n[p]?u[E+1][p+1]+1:Math.max(u[E+1][p],u[E][p+1]);const m=[];let f=0,y=0,k=1,j=1;for(;f<o||y<l;)f<o&&y<l&&s[f]===n[y]?(m.push({type:"equal",content:s[f],oldLineNum:k++,lineNum:j++}),f++,y++):y<l&&(f>=o||u[f][y+1]>=u[f+1][y])?(m.push({type:"add",content:n[y],lineNum:j++}),y++):(m.push({type:"remove",content:s[f],oldLineNum:k++}),f++);return m}function Ha(a){return a.match(/\S+|\s+/g)??[""]}function Va({oldText:a,newText:i,mode:s}){const n=Ha(a),o=Ha(i),l=n.length,u=o.length,m=Array.from({length:l+1},()=>new Array(u+1).fill(0));for(let j=l-1;j>=0;j--)for(let E=u-1;E>=0;E--)m[j][E]=n[j]===o[E]?m[j+1][E+1]+1:Math.max(m[j+1][E],m[j][E+1]);const f=[];let y=0,k=0;for(;y<l||k<u;)y<l&&k<u&&n[y]===o[k]?(f.push({text:s==="remove"?n[y]:o[k],changed:!1}),y++,k++):k<u&&(y>=l||m[y][k+1]>=m[y+1][k])?(s==="add"&&f.push({text:o[k],changed:!0}),k++):(s==="remove"&&f.push({text:n[y],changed:!0}),y++);return e.jsx("span",{children:f.map((j,E)=>j.changed?e.jsx("span",{className:s==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:j.text},E):e.jsx("span",{children:j.text},E))})}function gl({agent:a,template:i,templateId:s}){const{t:n}=Ve(["agent","common"]),o=r.useMemo(()=>xl(a,i),[a,i]),[l,u]=r.useState(!0),m=3,f=r.useMemo(()=>{const p=o.map((_,h)=>_.type!=="equal"?h:-1).filter(_=>_>=0);if(p.length===0)return[];const b=[];let I=Math.max(0,p[0]-m),N=Math.min(o.length-1,p[0]+m);for(let _=1;_<p.length;_++){const h=Math.max(0,p[_]-m),T=Math.min(o.length-1,p[_]+m);h<=N+1||(b.push({start:I,end:N}),I=h),N=T}return b.push({start:I,end:N}),b},[o]),y=(p,b,I)=>{const N=p.type==="add"?"+":p.type==="remove"?"-":" ",_=p.type==="add"?"bg-green-500/8":p.type==="remove"?"bg-red-500/8":"",h=p.type==="add"?"text-green-600/90":p.type==="remove"?"text-red-500/80":"text-fg-tertiary",T=p.type==="add"?"text-green-500":p.type==="remove"?"text-red-500":"text-fg-muted",D=p.type==="remove"?p.oldLineNum:p.lineNum;let M=null;return p.type==="remove"&&b+1<I.length&&I[b+1].type==="add"?M=e.jsx(Va,{oldText:p.content,newText:I[b+1].content,mode:"remove"}):p.type==="add"&&b>0&&I[b-1].type==="remove"&&(M=e.jsx(Va,{oldText:I[b-1].content,newText:p.content,mode:"add"})),e.jsxs("div",{className:`flex ${_} hover:brightness-95 transition-colors`,children:[e.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:D??""}),e.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${T} select-none leading-[20px]`,children:N}),e.jsxs("span",{className:`flex-1 text-[11px] font-mono ${h} whitespace-pre-wrap break-words leading-[20px]`,children:[M??p.content,p.content===""&&" "]})]},b)},k=o.filter(p=>p.type==="add").length,j=o.filter(p=>p.type==="remove").length,E=l?f.flatMap(p=>{const b=[];for(let I=p.start;I<=p.end;I++)b.push({...o[I],_idx:I});return b}):o.map((p,b)=>({...p,_idx:b}));return e.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.diff.title",{templateId:s})}),e.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",k]}),e.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",j]})]}),e.jsx("button",{onClick:()=>u(p=>!p),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:n(l?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),e.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[l&&f.length>0&&f[0].start>0&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:n("agent:profilePage.diff.linesHidden",{count:f[0].start})}),E.map((p,b)=>{const I=b>0?E[b-1]:null,N=l&&I&&p._idx-I._idx>1;return e.jsxs("div",{children:[N&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),y(p,p._idx,o)]},b)}),l&&f.length>0&&f[f.length-1].end<o.length-1&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:n("agent:profilePage.diff.linesHidden",{count:o.length-1-f[f.length-1].end})}),f.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:n("agent:profilePage.diff.identical")})]})]})}function fl(a,i){const s=a.split(`
13
+ `),n=i.split(`
14
+ `),o=[],l=Math.max(s.length,n.length);for(let u=0;u<l;u++){const m=s[u],f=n[u];if(m===f){o.push(` ${m??""}`);continue}m!==void 0&&(f===void 0||m!==f)&&o.push(`- ${m}`),f!==void 0&&(m===void 0||m!==f)&&o.push(`+ ${f}`)}if(o.length>80){const u=o.filter(m=>m.startsWith("+ ")||m.startsWith("- "));if(u.length>0)return u.join(`
15
+ `)}return o.join(`
16
+ `)}function qa({agentId:a}){const{t:i}=Ve(["agent","common"]),[s,n]=r.useState([]),[o,l]=r.useState(!0),[u,m]=r.useState(null),[f,y]=r.useState(""),[k,j]=r.useState(""),[E,p]=r.useState(!1);r.useEffect(()=>{A.system.storage().then(ne=>{j(ne.dataDir+"/agents/"+a+"/role")}).catch(()=>{})},[a]);const[b,I]=r.useState(!1),[N,_]=r.useState(!1),[h,T]=r.useState(null),[D,M]=r.useState(null),P=r.useCallback(()=>{l(!0),Promise.all([A.agents.getFiles(a),A.agents.roleStatus(a).catch(()=>null)]).then(([ne,v])=>{n(ne.files),T(v),ne.files.length>0&&!u&&(m(ne.files[0].name),y(ne.files[0].content))}).catch(()=>{}).finally(()=>l(!1))},[a]);r.useEffect(()=>{P()},[P]);const L=ne=>{const v=s.find(H=>H.name===ne);v&&(m(ne),y(v.content),_(!1),M(null))},G=async()=>{if(u){I(!0);try{await A.agents.updateFile(a,u,f),n(ne=>ne.map(v=>v.name===u?{...v,content:f}:v)),_(!1),u==="ROLE.md"&&await A.agents.updateSystemPrompt(a,f)}catch{}I(!1)}},me=h?.files.filter(ne=>ne.status==="modified"||ne.status==="added_in_template")??[],Ee=async ne=>{const v=ne?me.filter(Z=>Z.file===ne):me;if(v.length===0)return;const H=[];for(const Z of v)try{const ie=await A.agents.roleDiff(a,Z.file);ie.agentContent!=null&&ie.templateContent!=null&&H.push(`## ${Z.file}
17
+
18
+ **Template file path:** built-in template \`${h?.templateId??"unknown"}\`
19
+
20
+ **Key changes in the new template version:**
21
+ \`\`\`diff
22
+ `+fl(ie.agentContent,ie.templateContent)+"\n```\n")}catch{}if(H.length===0)return;const w=`Your role configuration files have been updated in the latest template (\`${h?.templateId??""}\`). Please review the following changes and decide whether to update your files accordingly.
23
+
24
+ `+H.join(`
25
+ ---
26
+
27
+ `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";os.navigate(at.TEAM,{agentId:a,prefillMessage:w})},Le=async ne=>{if(D?.file===ne){M(null);return}try{const v=await A.agents.roleDiff(a,ne);v.agentContent!=null&&v.templateContent!=null&&M({file:ne,agent:v.agentContent,template:v.templateContent})}catch{}};if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:i("agent:profilePage.filesTab.loading")});const Q={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},De=ne=>{const v=Q[ne];return v?i(`agent:profilePage.filesTab.fileLabels.${v}`):ne},be=h?.hasTemplate&&!h.isUpToDate,R=u?me.some(ne=>ne.file===u):!1;return e.jsxs("div",{className:"space-y-4",children:[be&&e.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[e.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-amber-600 font-medium",children:i("agent:profilePage.filesTab.templateUpdateAvailable")}),e.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[i("agent:profilePage.filesTab.filesDiffer",{count:me.length,templateId:h.templateId})," ",me.map(ne=>ne.file).join(", ")]})]}),e.jsx("button",{onClick:()=>Ee(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:i("agent:profilePage.filesTab.sendToAgent")})]}),e.jsxs(Ze,{title:i("agent:profilePage.filesTab.agentConfigFiles"),action:h?.hasTemplate?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${h.isUpToDate?"bg-green-400":"bg-amber-400"}`}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.filesTab.templateLabel")," ",e.jsx("span",{className:"text-fg-secondary",children:h.templateId}),h.isUpToDate?i("agent:profilePage.filesTab.upToDate"):i("agent:profilePage.filesTab.updatesAvailable")]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[e.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:s.map(ne=>{const v=me.some(H=>H.file===ne.name);return e.jsxs("button",{onClick:()=>L(ne.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${u===ne.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[ne.name,v&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},ne.name)})}),u&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:De(u)}),e.jsxs("div",{className:"flex gap-2 items-center",children:[R&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Le(u),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:D?.file===u?i("agent:profilePage.filesTab.hideDiff"):i("agent:profilePage.filesTab.viewDiff")}),e.jsx("button",{onClick:()=>Ee(u),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:i("agent:profilePage.filesTab.sendToAgentTitle"),children:i("agent:profilePage.filesTab.sendToAgent")})]}),b&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("common:saving")})]})]}),k&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[e.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${k}/${u}`,children:[k,"/",u]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${k}/${u}`),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:i("agent:profilePage.filesTab.copyPath"),children:i(E?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),e.jsx("button",{onClick:()=>{A.system.openPath(k)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:i("agent:profilePage.filesTab.openInFinder"),children:i("agent:profilePage.filesTab.openInFinder")})]}),D?.file===u&&e.jsx(gl,{agent:D.agent,template:D.template,templateId:h?.templateId??""}),e.jsx(hl,{content:s.find(ne=>ne.name===u)?.content??"",editContent:f,setEditContent:ne=>{y(ne),_(!0)},dirty:N,onSave:G}),u==="ROLE.md"&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:i("agent:profilePage.filesTab.roleMdHint")})]}),s.length===0&&e.jsx(nr,{text:i("agent:profilePage.filesTab.noConfigFiles")})]})]})}function hl({content:a,editContent:i,setEditContent:s,dirty:n,onSave:o}){const[l,u]=r.useState(!1),m=r.useRef(null);return r.useEffect(()=>{l&&m.current?.focus()},[l]),r.useEffect(()=>{u(!1)},[a]),l||n?e.jsx("textarea",{ref:m,value:i,onChange:f=>s(f.target.value),onBlur:()=>{i!==a&&o(),u(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),s(a),u(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):e.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>u(!0),role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&u(!0)},children:[e.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),i.trim()?e.jsx(r.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(ml,{content:i,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const pl=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_"]}];function bl(a,i){const s=new Map,n=new Set;for(const{id:u,prefixes:m}of pl){const f=i(`agent:toolCategories.${u}`),y=a.filter(k=>!n.has(k.name)&&m.some(j=>k.name.startsWith(j)));y.length>0&&(s.set(f,y),y.forEach(k=>n.add(k.name)))}const o=a.filter(u=>!n.has(u.name));for(const u of o){const m=u.name.indexOf("__");if(m>0){const f=u.name.slice(0,m),y=i("agent:toolCategories.mcp",{server:f});s.has(y)||s.set(y,[]),s.get(y).push(u),n.add(u.name)}}const l=a.filter(u=>!n.has(u.name));return l.length>0&&s.set(i("agent:toolCategories.other"),l),[...s.entries()].map(([u,m])=>({category:u,tools:m}))}function vl(a){return a.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function yl({tools:a}){const{t:i}=Ve(["agent","common"]),s=bl(a,i);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:i("agent:profilePage.toolsTab.registeredCount",{count:a.length})}),s.map(n=>e.jsx(Ze,{title:`${n.category} (${n.tools.length})`,children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:n.tools.map(o=>{const l=ko(o.name),u=i(`common:execution.tools.${l.key}`,{defaultValue:l.label}),m=o.name.includes("__"),f=m?o.name.split("__").pop():o.name,y=vl(o.description||"");return e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[e.jsx(So,{name:l.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:u}),m&&e.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),f!==u&&e.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:f}),y&&e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:y,children:y})]})]},o.name)})})},n.category)),a.length===0&&e.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:i("agent:profilePage.toolsTab.noToolsRegistered")})]})}function jl({agent:a}){const{t:i}=Ve(["agent","common"]),s=a.proficiency??{},[n,o]=r.useState(null),[l,u]=r.useState(null),[m,f]=r.useState(!1),y=a.availableSkills??[],k=new Map;for(const N of y){const _=N.category||"custom";k.has(_)||k.set(_,[]),k.get(_).push(N)}const j=async N=>{if(n===N){o(null),u(null);return}o(N),f(!0);try{const _=await fetch(`/api/skills/${encodeURIComponent(N)}`);if(_.ok){const h=await _.json();u(h.skill)}else u(null)}catch{u(null)}f(!1)},E={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"},p=N=>{const _=s[N.name],h=_&&_.uses>0?Math.round(_.successes/_.uses*100):null,T=_&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[i("agent:profilePage.skillsTab.usesStats",{uses:_.uses,successes:_.successes}),_.lastUsed&&i("agent:profilePage.skillsTab.lastUsed",{date:new Date(_.lastUsed).toLocaleDateString()})]}),D=n===N.name;return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${D?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>j(N.name),children:[e.jsx("span",{className:`text-sm transition-transform ${D?"rotate-90":""}`,children:"▶"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:N.name}),N.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:i("agent:profilePage.skillsTab.alwaysOn")}),N.builtIn&&!N.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:i("agent:profilePage.skillsTab.builtIn")}),!N.builtIn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:i("agent:profilePage.skillsTab.installed")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:N.description}),T]}),h!==null&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${h>=80?"bg-green-400":h>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${h}%`}})}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[h,"%"]})]})]}),D&&e.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:m?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:i("agent:profilePage.skillsTab.loadingDetails")}):l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${E[l.category]??E.custom}`,children:l.category}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",l.version]}),l.author&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.skillsTab.byAuthor",{author:l.author})}),l.requiredPermissions?.map(M=>e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:M},M))]}),l.description&&e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:l.description}),l.tags&&l.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap",children:l.tags.map(M=>e.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",M]},M))}),(l.toolDetails??l.tools??[]).length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:i("agent:profilePage.skillsTab.toolsHeading",{count:(l.toolDetails??l.tools??[]).length})}),e.jsx("div",{className:"space-y-1.5",children:(l.toolDetails??l.tools??[]).map(M=>e.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:M.name}),M.description&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:M.description})]},M.name))})]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:i("agent:profilePage.skillsTab.detailsUnavailable")})})]},N.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],I=[...k.entries()].sort((N,_)=>{const h=b.indexOf(N[0]),T=b.indexOf(_[0]);return(h===-1?999:h)-(T===-1?999:T)});return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{className:"text-xs text-fg-tertiary",children:i("agent:profilePage.skillsTab.installedCount",{count:y.length})})}),I.map(([N,_])=>e.jsx(Ze,{title:e.jsxs("span",{className:"capitalize",children:[N," ",e.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",_.length,")"]})]}),children:e.jsx("div",{className:"space-y-2",children:_.map(h=>p(h))})},N)),y.length===0&&e.jsx(nr,{text:i("agent:profilePage.skillsTab.noSkills")})]})}function Ua({tools:a,agent:i}){const{t:s}=Ve(["agent","common"]),[n,o]=r.useState("tools");return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(l=>e.jsx("button",{onClick:()=>o(l),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${n===l?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:l==="tools"?`${s("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${a.length})`:`${s("agent:tabs.skills")} (${i.availableSkills?.length??0})`},l))}),n==="tools"?e.jsx(yl,{tools:a}):e.jsx(jl,{agent:i})]})}function Ka({agentId:a}){const{t:i}=Ve(["agent","common"]),[s,n]=r.useState(null),[o,l]=r.useState(!0),[u,m]=r.useState("longterm"),[f,y]=r.useState(""),[k,j]=r.useState(""),[E,p]=r.useState(!1),[b,I]=r.useState(null),[N,_]=r.useState(null),[h,T]=r.useState([]),[D,M]=r.useState(!1),P=r.useCallback(()=>{l(!0),A.agents.getMemory(a).then(Q=>{n(Q),y(Q.recentDailyLogs??""),j(Q.longTermMemory??"")}).catch(()=>{}).finally(()=>l(!1))},[a]);r.useEffect(()=>{P()},[P]);const L=async()=>{p(!0),await A.agents.updateDailyMemory(a,f).catch(()=>{}),p(!1),P()},G=async()=>{p(!0),await A.agents.updateLongTermMemory(a,i("agent:profilePage.memoryTab.userEditedSource"),k).catch(()=>{}),p(!1),P()},me=f!==(s?.recentDailyLogs??""),Ee=k!==(s?.longTermMemory??"");if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:i("agent:profilePage.memoryTab.loading")});if(!s)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:i("agent:profilePage.memoryTab.loadFailed")});const Le=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${s.entries.length})`},{key:"sessions",label:i("agent:profilePage.memoryTab.sessions",{count:s.sessions.length})},{key:"daily",label:i("agent:profilePage.memoryTab.dailyLogs")}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex gap-2",children:Le.map(Q=>e.jsx("button",{onClick:()=>m(Q.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${u===Q.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:Q.label},Q.key))}),u==="entries"&&e.jsx(Ze,{title:i("agent:profilePage.memoryTab.recentEntries"),children:s.entries.length===0?e.jsx(nr,{text:i("agent:profilePage.memoryTab.noEntries")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.entries.map((Q,De)=>{const be=b===De;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>I(be?null:De),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${Q.type==="fact"?"bg-blue-500/15 text-blue-600":Q.type==="task"?"bg-green-500/15 text-green-600":Q.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:Q.type}),e.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${be?"":"line-clamp-2"}`,children:Q.content}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[Q.importance!=null&&e.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${Q.importance>=7?"bg-red-500/15 text-red-500":Q.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",Q.importance]}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(Q.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:be?"▲":"▼"})]})]}),be&&e.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[e.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:Q.content}),e.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[e.jsxs("span",{children:[i("agent:profilePage.overview.labels.type"),": ",Q.type]}),Q.importance!=null&&e.jsxs("span",{children:[i("agent:profilePage.overview.labels.importance"),": ",Q.importance]}),e.jsx("span",{children:new Date(Q.timestamp).toLocaleString()})]})]})]},De)})})}),u==="sessions"&&e.jsx(Ze,{title:i("agent:profilePage.memoryTab.chatSessions"),children:s.sessions.length===0?e.jsx(nr,{text:i("agent:profilePage.memoryTab.noSessions")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.sessions.map(Q=>{const De=N===Q.id,be=async()=>{if(De){_(null),T([]);return}_(Q.id),M(!0);try{const R=await A.agents.getMemorySession(a,Q.id);T(R.messages)}catch{T([])}M(!1)};return e.jsxs("div",{children:[e.jsxs("button",{onClick:be,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[e.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:Q.id}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[Q.messageCount," ",i("agent:profilePage.memoryTab.msgs")]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(Q.updatedAt).toLocaleDateString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:De?"▲":"▼"})]}),De&&e.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:D?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:i("agent:profilePage.memoryTab.loadingMessages")}):h.length===0?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:i("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const R=new Map;for(const ne of h)ne.role==="tool"&&ne.toolCallId&&R.set(ne.toolCallId,ne.content);return e.jsx("div",{className:"divide-y divide-gray-700/30",children:h.filter(ne=>ne.role!=="tool").map((ne,v)=>e.jsxs("div",{className:"px-3 py-2",children:[(ne.role==="user"||ne.role==="system")&&e.jsxs("div",{children:[e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${ne.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:i(`agent:profilePage.memoryTab.roles.${ne.role}`,{defaultValue:ne.role})}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx(sr,{content:ne.content,className:"text-xs text-fg-secondary"})})]}),ne.role==="assistant"&&e.jsxs("div",{className:"space-y-1",children:[ne.content&&e.jsxs("div",{children:[e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:i("agent:profilePage.memoryTab.roles.assistant")}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx(sr,{content:ne.content,className:"text-xs text-fg-secondary"})})]}),ne.toolCalls&&ne.toolCalls.length>0&&e.jsx("div",{className:"space-y-0.5",children:ne.toolCalls.map(H=>{let w;try{w=JSON.parse(H.arguments)}catch{}const Z={tool:H.name,status:"done",args:w,result:R.get(H.id)};return e.jsx(vo,{entry:{type:"tool",info:Z}},H.id)})})]})]},v))})})()})]},Q.id)})})}),u==="daily"&&e.jsx(Ze,{title:i("agent:profilePage.memoryTab.dailyLogs"),action:me?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>y(s?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:i("common:cancel")}),e.jsx("button",{onClick:L,disabled:E,className:"text-xs text-brand-500",children:i(E?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:f,onChange:Q=>y(Q.target.value),placeholder:i("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"})}),u==="longterm"&&e.jsx(Ze,{title:i("agent:profilePage.memoryTab.longTermTitle"),action:Ee?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>j(s?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:i("common:cancel")}),e.jsx("button",{onClick:G,disabled:E,className:"text-xs text-brand-500",children:i(E?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:k,onChange:Q=>j(Q.target.value),placeholder:i("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 Ga({agentId:a,initialData:i}){const{t:s}=Ve(["agent","common"]),[n,o]=r.useState(i??null),[l,u]=r.useState(!i),[m,f]=r.useState([]),[y,k]=r.useState(null),[j,E]=r.useState(!1),[p,b]=r.useState(null),I=r.useCallback(()=>Promise.all([A.agents.getHeartbeat(a).then(o).catch(()=>{}),A.agents.getRecentActivities(a).then(D=>{f(D.activities.filter(M=>M.type==="heartbeat"))}).catch(()=>{})]),[a]);r.useEffect(()=>{u(!0),I().finally(()=>u(!1))},[I]),r.useEffect(()=>Fe.on("agent:update",M=>{M.payload?.agentId===a&&I()}),[a,I]);const N=async()=>{E(!0),b(null);try{const D=await A.agents.triggerHeartbeat(a);b(D.message),setTimeout(()=>b(null),4e3),setTimeout(I,2e3)}catch(D){b(String(D).replace("Error: ",""))}E(!1)},_=async D=>{try{await A.agents.cancelWakeup(a,D),I()}catch{}};if(l)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.loading")});if(!n)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.noData")});const h=D=>D?D<1e3?`${D}ms`:D<6e4?`${(D/1e3).toFixed(1)}s`:`${(D/6e4).toFixed(1)}m`:null,T=D=>{if(!D)return null;const M=Date.now()-new Date(D).getTime();if(M<0){const P=Math.abs(M);return P<6e4?s("agent:profilePage.relative.inSeconds",{count:Math.ceil(P/1e3)}):P<36e5?s("agent:profilePage.relative.inMinutes",{count:Math.ceil(P/6e4)}):s("agent:profilePage.relative.inHours",{hours:(P/36e5).toFixed(1)})}return M<6e4?s("agent:profilePage.relative.secondsAgo",{count:Math.floor(M/1e3)}):M<36e5?s("agent:profilePage.relative.minutesAgo",{count:Math.floor(M/6e4)}):s("agent:profilePage.relative.hoursAgo",{hours:(M/36e5).toFixed(1)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ze,{title:s("agent:profilePage.heartbeatTab.scheduler"),action:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:I,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:s("common:refresh")}),e.jsx("button",{onClick:N,disabled:j||!n.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:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsx(rt,{label:s("agent:profilePage.overview.labels.status"),value:n.running?s("agent:profilePage.heartbeatTab.running"):s("agent:profilePage.heartbeatTab.stopped"),color:n.running?"green":"gray"}),e.jsx(Nl,{agentId:a,intervalMs:n.intervalMs,onChanged:I}),e.jsx(rt,{label:s("agent:profilePage.heartbeatTab.lastRun"),value:n.lastHeartbeat?T(n.lastHeartbeat)??s("agent:profilePage.emDash"):s("agent:profilePage.never")}),e.jsx(rt,{label:s("agent:profilePage.heartbeatTab.nextWake"),value:n.nextWakeAt?T(n.nextWakeAt)??s("agent:profilePage.emDash"):n.running?s("agent:profilePage.heartbeatTab.pending"):s("agent:profilePage.emDash")})]}),e.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:s("agent:profilePage.heartbeatTab.rhythmHint")}),p&&e.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),n.wakeups&&n.wakeups.length>0&&e.jsx(Ze,{title:s("agent:profilePage.heartbeatTab.wakeupsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.wakeupsCount",{count:n.wakeups.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:n.wakeups.map(D=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate",children:D.note||s("agent:profilePage.heartbeatTab.wakeupNoNote")}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[T(D.wakeAt)??new Date(D.wakeAt).toLocaleString(),D.recurringMs?` · ${s("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${D.deliveryMode==="in_session"?s("agent:profilePage.heartbeatTab.deliveryInSession"):s("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),e.jsx("button",{onClick:()=>_(D.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:s("agent:profilePage.heartbeatTab.cancelWakeup")})]},D.id))})}),n.pendingCallbacks&&n.pendingCallbacks.length>0&&e.jsx(Ze,{title:s("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.pendingOpsCount",{count:n.pendingCallbacks.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:n.pendingCallbacks.map(D=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:D.type==="background_exec"?"⚙":"↔"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:D.label}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[s(`agent:profilePage.heartbeatTab.callbackType.${D.type}`),` · ${s("agent:profilePage.heartbeatTab.timesOut")} ${T(D.timeoutAt)??new Date(D.timeoutAt).toLocaleString()}`]})]})]},D.id))})}),n.lastSummary&&e.jsx(Ze,{title:s("agent:profilePage.heartbeatTab.lastSummary"),action:n.lastSummaryAt?e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(n.lastSummaryAt).toLocaleString()}):void 0,children:e.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:e.jsx(sr,{content:n.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),m.length>0?e.jsx(Ze,{title:s("agent:profilePage.heartbeatTab.recentRuns"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.runsThisSession",{count:m.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...m].reverse().map(D=>{const M=y===D.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(M?null:D.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:D.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:s("agent:profilePage.heartbeatTab.actionsCount",{count:D.logCount})}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(D.startedAt).toLocaleString()}),e.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${M?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:e.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),M&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(kn,{agentId:a,activityId:D.id})})]},D.id)})})}):n.lastHeartbeat?null:e.jsx(Ze,{title:s("agent:profilePage.heartbeatTab.recentRuns"),children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.noRunsYet")}),e.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:n.running?s("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:h(n.intervalMs-n.uptimeMs%n.intervalMs)??s("agent:profilePage.heartbeatTab.soon")}):s("agent:profilePage.heartbeatTab.schedulerStopped")}),n.running&&e.jsx("button",{onClick:N,disabled:j,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function wl({taskId:a,isLive:i}){const{t:s}=Ve("agent"),[n,o]=r.useState([]),[l,u]=r.useState(""),[m,f]=r.useState(!0),[y,k]=r.useState("compact");if(r.useEffect(()=>{f(!0),u(""),A.tasks.getLogs(a).then(p=>{o(p.logs),f(!1)}).catch(()=>f(!1))},[a]),r.useEffect(()=>{if(!i)return;const p=Fe.on("task:log",I=>{const N=I.payload;if(N.taskId!==a)return;const _={id:N.id,taskId:N.taskId,agentId:N.agentId,seq:N.seq,type:N.logType,content:N.content,metadata:N.metadata,createdAt:N.createdAt};o(h=>_.id&&h.some(T=>T.id===_.id)?h:[...h,_]),_.type==="text"&&u("")}),b=Fe.on("task:log:delta",I=>{const N=I.payload;N.taskId===a&&u(_=>_+N.text)});return()=>{p(),b()}},[a,i]),m)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.loading")});if(n.length===0&&!l)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.noLogs")});const j=n.map(p=>No(p)),E=new Set(j.filter(p=>p.executionRound!=null).map(p=>p.executionRound)).size>1;return e.jsx("div",{className:"px-3 py-2",children:y==="compact"?e.jsx(xi,{entries:j,streamingText:l,isActive:i,onExpand:()=>k("full"),showRounds:E}):e.jsx(gi,{entries:j,streamingText:l,isActive:i,onCollapse:()=>k("compact"),showRounds:E})})}function kn({agentId:a,activityId:i,isLive:s=!1}){const{t:n}=Ve("agent"),[o,l]=r.useState([]),[u,m]=r.useState(!0),[f,y]=r.useState("compact");if(r.useEffect(()=>{m(!0),A.agents.getActivityLogs(a,i).then(j=>{l(j.logs),m(!1)}).catch(()=>m(!1))},[a,i]),r.useEffect(()=>s?Fe.on("agent:activity_log",E=>{const p=E.payload;if(p.agentId!==a||p.activityId!==i)return;const b={seq:p.seq,type:p.type,content:p.content,metadata:p.metadata,createdAt:p.createdAt};l(I=>I.some(N=>N.seq===b.seq)?I:[...I,b])}):void 0,[a,i,s]),u)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:n("profilePage.activityLog.loading")});if(o.length===0)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:n("profilePage.activityLog.noLogs")});const k=o.map(j=>wo(j,i,a)).filter(j=>j!==null);return e.jsx("div",{className:"px-3 py-2",children:f==="compact"?e.jsx(xi,{entries:k,isActive:s,onExpand:()=>y("full")}):e.jsx(gi,{entries:k,isActive:s,onCollapse:()=>y("compact")})})}function Ze({title:a,action:i,children:s}){return e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:a}),i]}),s]})}function Nt({label:a,mono:i,children:s}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a}),e.jsx("span",{className:`text-xs text-fg-secondary ${i?"font-mono text-[10px]":""}`,children:s})]})}function rt({label:a,value:i,color:s}){const n=s==="green"?"text-green-500":s==="blue"?"text-blue-400":s==="indigo"?"text-brand-500":s==="red"?"text-red-400":"text-fg-secondary";return e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`text-sm font-semibold ${n}`,children:i}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a})]})}const Ya=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Xa=5,Qa=1440;function Nl({agentId:a,intervalMs:i,onChanged:s}){const{t:n}=Ve(["agent","common"]),[o,l]=r.useState(!1),[u,m]=r.useState(null),[f,y]=r.useState(!1),[k,j]=r.useState(String(Math.round(i/6e4))),E=h=>h%(3600*1e3)===0?n("agent:profilePage.heartbeatTab.intervalHours",{count:h/(3600*1e3)}):n("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(h/6e4)}),p=async h=>{l(!0),m(null);try{await A.agents.updateConfig(a,{heartbeatIntervalMs:h}),s()}catch(T){m(String(T).replace("Error: ",""))}l(!1)},b=h=>{if(h.target.value==="custom"){y(!0);return}y(!1),p(Number(h.target.value))},I=()=>{const h=Math.round(Number(k));if(!Number.isFinite(h)||h<Xa||h>Qa){m(n("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(h*60*1e3)},N=Ya.includes(i),_=f||!N?"custom":String(i);return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.heartbeatTab.safetyNetInterval")}),e.jsxs("select",{value:_,onChange:b,disabled:o,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!N&&e.jsx("option",{value:String(i),children:E(i)}),Ya.map(h=>e.jsx("option",{value:String(h),children:E(h)},h)),e.jsx("option",{value:"custom",children:n("agent:profilePage.heartbeatTab.intervalCustom")})]}),(f||!N)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("input",{type:"number",min:Xa,max:Qa,value:k,onChange:h=>j(h.target.value),disabled:o,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.heartbeatTab.intervalCustomUnit")}),e.jsx("button",{onClick:I,disabled:o,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:n(o?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),u&&e.jsx("span",{className:"text-[10px] text-red-400",children:u})]})}function nr({text:a}){return e.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:a})}function Ja(a){if(a===0)return"0 B";const i=["B","KB","MB","GB"],s=Math.min(Math.floor(Math.log(a)/Math.log(1024)),i.length-1),n=a/Math.pow(1024,s);return`${n<10?n.toFixed(1):Math.round(n)} ${i[s]}`}const Za={0:"0",1:"1",2:"2",3:"3",4:"4"},ei={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},kl={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"},Sl={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},Qn={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:"🧠"},Cl=["all","interaction","task","notification","system"],Tl={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"]},Ml={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"},Pl={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 $r(a){const i=a.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(i?.[1]){const s=i[1].trim().replace(/\n/g," ");return s.length>80?s.slice(0,80)+"…":s}}function ti(a,i){const s=a.payload,n=s?.summary??"",o=s?.content??"",l=a.metadata?.senderName;switch(a.sourceType){case"task_status_update":{const u=n.match(/^Task "(.+?)" status:/),m=n.match(/status:\s*(\S+)\s*→\s*(\S+)/),f=u?.[1]??n;if(m){const k=m[1],j=m[2],E=Fr(k,i),p=Fr(j,i),b=Pl[j]??"text-fg-secondary";return{title:f,subtitle:i("agent:profilePage.mind.mailbox.statusArrow",{from:E,to:p}),badge:{label:p,color:b}}}const y=n.match(/^Task:\s*(.+)/);return y?{title:y[1]}:{title:f}}case"task_comment":{const u=n.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=$r(o);if(u){const f=m?i("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):i("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:n}}case"requirement_update":{const u=n.match(/^Requirement "(.+?)"\s+(.*)/);return u?{title:u[1],subtitle:u[2]}:{title:n}}case"requirement_comment":{const u=n.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=$r(o);if(u){const f=m?i("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):i("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:n}}case"human_chat":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?i("agent:profilePage.mind.mailbox.chatFrom",{sender:l}):i("agent:profilePage.mind.mailbox.humanChat"),subtitle:u+(o.length>120?"…":"")}}case"a2a_message":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?i("agent:profilePage.mind.mailbox.messageFrom",{sender:l}):i("agent:profilePage.mind.mailbox.agentMessage"),subtitle:u+(o.length>120?"…":"")}}case"mention":{const u=n.match(/from (.+)$/),m=$r(o);return{title:u?i("agent:profilePage.mind.mailbox.mentionedBy",{name:u[1]}):i("agent:profilePage.mind.mailbox.mention"),subtitle:m||void 0}}case"review_request":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?i("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:l}):i("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:u+(o.length>120?"…":"")}}case"session_reply":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?i("agent:profilePage.mind.mailbox.replyInSession",{sender:l}):i("agent:profilePage.mind.mailbox.sessionReply"),subtitle:u+(o.length>120?"…":"")}}case"heartbeat":return{title:i("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:i("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:i("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const u=n.match(/^\[Announcement]\s*(.+)/);return u?{title:u[1],subtitle:i("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:n||i("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:n||a.sourceType}}}function si({agentId:a,highlightId:i,agentStatus:s,canManageAgents:n,onAgentStateChange:o}){const{t:l}=Ve(["agent","common","team"]),[u,m]=r.useState(null),[f,y]=r.useState(null),[k,j]=r.useState(!0),[E,p]=r.useState("all"),[b,I]=r.useState("all"),[N,_]=r.useState(i??null),[h,T]=r.useState(i??null),[D,M]=r.useState(!1),[P,L]=r.useState(!0),[G,me]=r.useState(null),Ee=50,Le=3,Q=r.useCallback(async(v=!0)=>{v&&j(!0);try{const H=E==="all"?void 0:E,w=b==="all"?void 0:b,[Z,ie]=await Promise.all([A.agents.getMindState(a),A.agents.getMailbox(a,{limit:Ee,category:H,status:w})]);m(Z),y(ie),L((ie.history?.length??0)>=Ee)}catch{}j(!1)},[a,E,b]),De=r.useCallback(async()=>{if(!f)return;const v=E==="all"?void 0:E,H=b==="all"?void 0:b;try{const w=await A.agents.getMailbox(a,{limit:Ee,offset:f.history.length,category:v,status:H});y(Z=>Z?{...Z,history:[...Z.history,...w.history]}:w),L((w.history?.length??0)>=Ee)}catch{}},[a,f,E,b]);r.useEffect(()=>{_(i??null),T(i??null),Q()},[Q,i]);const be=r.useRef(!1);if(r.useEffect(()=>{if(!h||k)return;if(f?.history?.some(H=>H.id===h)){be.current=!1;const H=document.getElementById(`mbx-${h}`);if(H){setTimeout(()=>H.scrollIntoView({behavior:"smooth",block:"center"}),100);const w=setTimeout(()=>T(null),3e3);return()=>clearTimeout(w)}}else P&&!be.current&&(be.current=!0,(async()=>{let H=f?.history??[],w=P;for(;w;)try{const Z=await A.agents.getMailbox(a,{limit:Ee,offset:H.length}),ie=[...H,...Z.history];H=ie,w=(Z.history?.length??0)>=Ee;const Re=Z.history.some($e=>$e.id===h);if(y($e=>$e?{...$e,history:ie}:Z),L(w),Re||!w)break}catch{break}be.current=!1})())},[h,k,f,P,a]),r.useEffect(()=>{let v=null;const H=Z=>{Z.payload?.agentId===a&&(v&&clearTimeout(v),v=setTimeout(()=>{v=null,Q(!1)},500))},w=[Fe.on("agent:mailbox",H),Fe.on("agent:decision",H),Fe.on("agent:attention",H),Fe.on("agent:focus",H),Fe.on("agent:update",H),Fe.on("agent:triage",H)];return()=>{v&&clearTimeout(v),w.forEach(Z=>Z())}},[a,Q]),k&&!u)return e.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:l("agent:profilePage.mind.loading")});const R=(()=>{const v=u?.attentionState??"idle";return v==="deciding"?"deciding":v!=="idle"&&!u?.currentFocus?"idle":v})(),ne=R==="idle"&&f?.history?.some(v=>v.status==="processing");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${Sl[R]??"bg-gray-500/20 text-gray-500"}`,children:l(`agent:profilePage.mind.attention.${R}`)}),u?.currentFocus?(()=>{const v=ti({id:u.currentFocus.mailboxItemId,sourceType:u.currentFocus.type,payload:{summary:u.currentFocus.label,taskId:u.currentFocus.taskId},metadata:{},queuedAt:u.currentFocus.startedAt},l);return e.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[e.jsxs("span",{children:[Qn[u.currentFocus.type]??"●"," ",e.jsx("span",{className:"text-fg-primary font-medium",children:v.title}),v.subtitle&&e.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:v.subtitle}),e.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:l("agent:profilePage.mind.since",{time:new Date(u.currentFocus.startedAt).toLocaleTimeString()})})]}),n&&e.jsxs("button",{onClick:()=>me(u.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:["✕ ",l("agent:profilePage.mind.cancelCurrentBtn")]})]})})():R==="deciding"?e.jsx("span",{className:"text-sm text-amber-500",children:l("agent:profilePage.mind.decidingWaiting",{count:u?.mailboxDepth??0})}):e.jsx("span",{className:"text-sm text-fg-tertiary",children:l("agent:profilePage.mind.idleWaiting")}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[n&&s==="offline"&&e.jsxs("button",{onClick:()=>{A.agents.start(a).then(()=>{o?.(),Q()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-green-500/15 text-green-500 hover:bg-green-500/25 transition-colors",children:["▶ ",l("agent:profilePage.mind.continueBtn")]}),n&&(s==="working"||s==="idle")&&e.jsxs("button",{onClick:()=>{A.agents.stop(a).then(()=>{o?.(),Q()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors",children:["■ ",l("team:contextMenu.stop")]}),e.jsx("button",{onClick:()=>{Q()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:l("agent:profilePage.mind.refresh")})]})]}),ne&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[e.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),e.jsx("span",{className:"text-[11px] text-amber-600",children:l("agent:profilePage.mind.staleProcessingWarning")})]}),(u?.queuedItems?.length??0)>0&&(()=>{const v=u.queuedItems,H=v.length>Le,w=H&&!D?v.slice(0,Le):v,Z=v.reduce((ie,Re)=>(ie[Re.sourceType]=(ie[Re.sourceType]??0)+1,ie),{});return e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:l("agent:profilePage.mind.queue",{count:v.length})}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(Z).map(([ie,Re])=>e.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Qn[ie]??"●"," ",Re]},ie))})]}),e.jsxs("div",{className:"space-y-1",children:[w.map((ie,Re)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[e.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:Re+1}),e.jsx("span",{className:"text-sm",children:Qn[ie.sourceType]??"●"}),e.jsx("span",{className:`text-[10px] ${ei[ie.priority]??"text-fg-tertiary"}`,children:l(`agent:profilePage.mind.priority.${Za[ie.priority]??ie.priority}`,{defaultValue:`P${ie.priority}`})}),e.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:ie.summary}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(ie.queuedAt).toLocaleTimeString()})]},ie.id)),H&&e.jsx("button",{onClick:()=>M(!D),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:D?l("agent:profilePage.mind.collapseQueue"):l("agent:profilePage.mind.expandQueue",{count:v.length-Le})})]})]})})()]}),(u?.notebook?.length??0)>0&&e.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:e.jsxs("details",{open:!0,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"📓"}),e.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),e.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[u.notebook.length," ",u.notebook.length===1?"entry":"entries"]})]}),e.jsx("div",{className:"mt-2 space-y-2",children:u.notebook.map(v=>{const H=Date.now()-v.updatedAt,w=H<6e4?`${Math.round(H/1e3)}s ago`:H<36e5?`${Math.round(H/6e4)}min ago`:`${(H/36e5).toFixed(1)}h ago`,Z=v.managed==="system"?"text-blue-400":v.managed==="cpp"?"text-purple-400":"text-emerald-400";return e.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary",children:v.key}),e.jsxs("span",{className:`text-[10px] ${Z}`,children:["[",v.managed,"]"]}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:w})]}),e.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:v.text.length>500?v.text.slice(0,500)+"…":v.text})]},v.key)})})]})}),u?.deliberationActivity&&e.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:l("agent:profilePage.mind.deliberationInProgress")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:l("agent:profilePage.mind.since",{time:new Date(u.deliberationActivity.startedAt).toLocaleTimeString()})})]}),e.jsx(kn,{agentId:a,activityId:u.deliberationActivity.activityId,isLive:!0})]}),u?.lastTriage&&(()=>{const H=Date.now()-new Date(u.lastTriage.timestamp).getTime()>6e4;return e.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${H?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:e.jsxs("details",{open:!H,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:l("agent:profilePage.mind.triageDecision")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(u.lastTriage.timestamp).toLocaleTimeString()})]}),e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:u.lastTriage.reasoning}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:l("agent:profilePage.mind.processingItem",{id:u.lastTriage.processedItemId.slice(0,12)})}),u.lastTriage.deferredItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:l("agent:profilePage.mind.deferred",{count:u.lastTriage.deferredItemIds.length})}),u.lastTriage.droppedItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:l("agent:profilePage.mind.dropped",{count:u.lastTriage.droppedItemIds.length})}),(u.lastTriage.inlineCompletedIds?.length??0)>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:l("agent:profilePage.mind.inlineCompleted",{count:u.lastTriage.inlineCompletedIds.length})})]})]})})})(),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:l("agent:profilePage.mind.mailboxHistory")}),e.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:Cl.map(v=>{const H=f?.sourceTypeCounts,w=v==="all"?H?Object.values(H).reduce((Z,ie)=>Z+ie,0):void 0:H?(Tl[v]??[]).reduce((Z,ie)=>Z+(H[ie]??0),0):void 0;return e.jsxs("button",{onClick:()=>p(v),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${E===v?"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:[l(`agent:profilePage.mind.categoryFilters.${v}`),w!=null&&w>0&&e.jsx("span",{className:"ml-1 opacity-60",children:w})]},v)})})]}),e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(v=>{const H=f?.statusCounts,w=v.key==="all"?H?Object.values(H).reduce((Z,ie)=>Z+ie,0):void 0:H?.[v.key];return e.jsxs("button",{onClick:()=>I(v.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${b===v.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:[v.dot&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${v.dot}`}),l(`agent:profilePage.mind.statusFilters.${v.key}`),w!=null&&w>0&&e.jsx("span",{className:"ml-1 opacity-60",children:w})]},v.key)})}),(!f?.history||f.history.length===0)&&!k&&e.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:l("agent:profilePage.mind.noHistory")}),e.jsx("div",{className:"space-y-1",children:f?.history?.map(v=>{const H=N===v.id,w=Qn[v.sourceType]??"●",Z=ti(v,l),ie=v.metadata?.senderName,Re=v.metadata?.senderRole,$e=h===v.id;return e.jsxs("div",{id:`mbx-${v.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${$e?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[e.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>_(H?null:v.id),children:[e.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:H?"▾":"▸"}),e.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${Ml[v.status]??"bg-gray-400"}`}),e.jsx("span",{className:"text-sm",children:w}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-medium text-fg-primary ${H?"":"truncate"}`,children:Z.title}),Z.badge&&e.jsx("span",{className:`text-[10px] font-medium shrink-0 ${Z.badge.color}`,children:Z.badge.label}),e.jsx("span",{className:`text-[10px] shrink-0 ${ei[v.priority]??"text-fg-tertiary"}`,children:l(`agent:profilePage.mind.priority.${Za[v.priority]??v.priority}`,{defaultValue:""})})]}),Z.subtitle&&e.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${H?"":"truncate"}`,children:Z.subtitle}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[e.jsx("span",{children:new Date(v.queuedAt).toLocaleString()}),v.completedAt&&e.jsxs("span",{children:["→ ",new Date(v.completedAt).toLocaleTimeString()]}),v.activity&&e.jsxs(e.Fragment,{children:[v.activity.totalTokens>0&&e.jsx("span",{children:l("agent:profilePage.mind.tokensCount",{count:Gs(v.activity.totalTokens)})}),v.activity.totalTools>0&&e.jsx("span",{children:l("agent:profilePage.mind.toolsCount",{count:v.activity.totalTools})})]})]})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:v.sourceType}),n&&v.status==="processing"&&e.jsxs("button",{onClick:ye=>{ye.stopPropagation(),me(v.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:["✕ ",l("agent:profilePage.mind.cancelCurrentBtn")]})]}),H&&e.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[ie&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[l("agent:profilePage.mind.from")," ",e.jsx("span",{className:"text-fg-secondary",children:ie}),Re&&e.jsxs("span",{className:"text-fg-tertiary",children:[" (",Re,")"]})]}),v.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(v.sourceType)&&e.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:v.payload.content}),v.decisions&&v.decisions.length>0&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:l("agent:profilePage.mind.decisions")}),e.jsx("div",{className:"space-y-1",children:v.decisions.map(ye=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${kl[ye.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:ye.decisionType}),e.jsx("span",{className:"text-fg-secondary flex-1",children:ye.reasoning}),e.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(ye.createdAt).toLocaleTimeString()})]},ye.id))})]}),v.activity?e.jsxs("div",{children:[e.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[l("agent:profilePage.mind.activityHeading",{label:v.activity.label}),e.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${v.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:v.activity.success?l("agent:profilePage.mind.success"):l("agent:profilePage.mind.failed")})]}),v.activity.type==="task"&&v.payload?.taskId?e.jsx(wl,{taskId:v.payload.taskId,isLive:!v.activity.endedAt}):e.jsx(kn,{agentId:a,activityId:v.activity.id,isLive:!v.activity.endedAt})]}):v.status==="processing"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:l("agent:profilePage.mind.processing")}):v.status==="completed"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:l("agent:profilePage.mind.noActivityLog")}):null]})]},v.id)})}),P&&(f?.history?.length??0)>0&&e.jsx("div",{className:"text-center mt-3",children:e.jsx("button",{onClick:De,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:l("agent:profilePage.mind.loadEarlier")})})]}),G&&e.jsx(Sn,{title:l("agent:profilePage.mind.cancelConfirmTitle"),message:l("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:l("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{A.agents.cancelProcessing(a).then(()=>Q()),me(null)},onCancel:()=>me(null)})]})}function ni({agentId:a}){const{t:i}=Ve(["agent","common"]),[s,n]=r.useState([]),[o,l]=r.useState(!0),[u,m]=r.useState(null),f=r.useCallback(async()=>{l(!0);try{const{results:y}=await A.deliverables.search({agentId:a,limit:200});n(y)}catch{n([])}l(!1)},[a]);return r.useEffect(()=>{f()},[f]),r.useEffect(()=>{const y=Fe.on("deliverable:created",()=>f()),k=Fe.on("deliverable:updated",()=>f()),j=Fe.on("deliverable:removed",()=>f());return()=>{y(),k(),j()}},[f]),o?e.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(y=>e.jsxs("div",{className:"animate-pulse space-y-2",children:[e.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),e.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},y))}):s.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("span",{className:"text-3xl mb-3",children:"📦"}),e.jsx("p",{className:"text-sm text-fg-secondary",children:i("agent:deliverables.empty")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:i("agent:deliverables.emptyHint")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:i("agent:deliverables.count",{count:s.length})}),s.map(y=>{const k=yo[y.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},j=Sa[y.status]??Sa.active;return e.jsxs("button",{onClick:()=>m(y),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[e.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${k.color}`,children:k.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:y.title}),e.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${j.color}`,children:y.status})]}),y.summary&&e.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:y.summary}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[e.jsx("span",{children:new Date(y.createdAt).toLocaleDateString()}),y.tags.length>0&&e.jsx("span",{children:y.tags.slice(0,3).join(", ")})]})]}),e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},y.id)})]}),u&&e.jsx(jo,{item:u,onClose:()=>m(null),onOpenInPage:y=>{m(null),os.navigate(at.DELIVERABLES,{openDeliverable:y})}})]})}const El=r.lazy(()=>fi(()=>import("./index-D_HH4ju2.js").then(a=>a.al),__vite__mapDeps([0,1])).then(a=>({default:a.MarkdownMessage}))),Hr=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],ri={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function ai({teamId:a,onBack:i,inline:s,headless:n,activeTab:o,onSelectAgent:l}){const{t:u}=Ve("team"),[m,f]=r.useState(null),[y,k]=r.useState(null),[j,E]=r.useState("overview"),p=n&&o?o:j,[b,I]=r.useState(""),[N,_]=r.useState(""),[h,T]=r.useState(!1),[D,M]=r.useState(!1),[P,L]=r.useState(""),[G,me]=r.useState(""),Ee=r.useRef(null),Le=r.useRef(null),Q=r.useRef(null),De=r.useRef(null),[be,R]=r.useState(!1),[ne,v]=r.useState(!1),[H,w]=r.useState(""),[Z,ie]=r.useState(""),[Re,$e]=r.useState(!1),[ye,dt]=r.useState([]),ht=r.useRef(null),zt=r.useCallback(async()=>{try{const Be=(await A.teams.list()).teams.find(Oe=>Oe.id===a);Be&&f(Be);const He=await A.teams.status(a);dt(He.agents)}catch{}},[a]),ls=r.useCallback(async()=>{try{const ae=await A.teams.getFile(a,"ANNOUNCEMENT.md");I(ae.content)}catch{I("")}try{const ae=await A.teams.getFile(a,"NORMS.md");_(ae.content)}catch{_("")}},[a]);r.useEffect(()=>{E("overview"),zt(),ls()},[a,zt,ls]),r.useEffect(()=>{h&&Le.current&&Le.current.focus()},[h]),r.useEffect(()=>{D&&De.current&&De.current.focus()},[D]);const Dt=async(ae,Be)=>{R(!0);try{await A.teams.updateFile(a,ae,Be),ae==="ANNOUNCEMENT.md"?(I(Be),T(!1)):(_(Be),M(!1))}catch{}R(!1)},Qt=async()=>{H.trim()&&(await A.teams.update(a,{name:H.trim()}),v(!1),zt())},cs=async()=>{await A.teams.update(a,{description:Z}),$e(!1),zt()};if(!m)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const Ls=m.members.find(ae=>ae.agentRole==="manager"),Wt=ye.filter(ae=>ae.status!=="offline").length,xt=p==="announcements"&&h||p==="norms"&&D;if(n)return e.jsx("div",{className:`flex-1 bg-surface-primary ${xt?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:e.jsxs("div",{className:`${xt?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[p==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:Ls?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ae=>{const Be=ye.find(gt=>gt.id===ae.id),He=ri[Be?.status??"offline"]??"bg-gray-500",Oe=ae.type==="agent";return e.jsxs("div",{onClick:()=>Oe&&l?.(ae.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Oe&&l?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(mt,{name:ae.name,avatarUrl:ae.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ae.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:Be?.status??"offline"}),ae.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae.role," · ",ae.type]})]}),Oe&&l&&e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ae.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),p==="announcements"&&e.jsx(Jn,{content:b,draft:P,setDraft:L,editing:h,setEditing:T,textareaRef:Le,contentRef:Ee,saving:be,onSave:()=>Dt("ANNOUNCEMENT.md",P),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),p==="norms"&&e.jsx(Jn,{content:N,draft:G,setDraft:me,editing:D,setEditing:M,textareaRef:De,contentRef:Q,saving:be,onSave:()=>Dt("NORMS.md",G),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),p==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),ne?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:ht,value:H,onChange:ae=>w(ae.target.value),onKeyDown:ae=>ae.key==="Enter"&&Qt(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),e.jsx("button",{onClick:Qt,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>v(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{w(m.name),v(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),Re?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:Z,onChange:ae=>ie(ae.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:cs,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>$e(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{ie(m.description??""),$e(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(ii,{teamId:a,teamName:m.name,onDeleted:i})]})]})});const it=j==="announcements"&&h||j==="norms"&&D;return e.jsxs("div",{className:`flex-1 bg-surface-primary ${it?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:m.name}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[m.members.length," members"]}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Wt," online"]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:m.description||"No description"})]}),e.jsxs("button",{onClick:async()=>{if(m)try{const{files:ae}=await A.teams.getFilesMap(m.id),Be=m.members.filter(Oe=>Oe.type==="agent"),He={type:"team",name:ui(m.name,m.name),displayName:m.name,version:"1.0.0",description:m.description??"",author:"",category:"general",tags:[],team:{members:Be.map(Oe=>({name:Oe.name,roleName:Oe.role,role:Oe.agentRole??"worker",count:1,skills:[]}))}};await mi.publishViaProxy({itemType:"team",name:m.name,description:m.description??"",category:"general",config:He,files:ae}),k({title:"Hub",message:`Published "${m.name}" to Markus Hub`,variant:"primary"})}catch(ae){k({title:"Hub",message:`Failed to publish: ${ae}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[e.jsx("span",{children:"↑"})," Hub"]}),s&&e.jsx("button",{onClick:i,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),e.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Hr.map(ae=>e.jsxs("button",{onClick:()=>E(ae.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${j===ae.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[ae.icon," ",u(ae.labelKey)]},ae.key))})]}),e.jsxs("div",{className:`${it?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[j==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:Ls?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ae=>{const Be=ye.find(gt=>gt.id===ae.id),He=ri[Be?.status??"offline"]??"bg-gray-500",Oe=ae.type==="agent";return e.jsxs("div",{onClick:()=>Oe&&l?.(ae.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Oe&&l?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(mt,{name:ae.name,avatarUrl:ae.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ae.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:Be?.status??"offline"}),ae.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae.role," · ",ae.type]})]}),Oe&&l&&e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ae.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),j==="announcements"&&e.jsx(Jn,{content:b,draft:P,setDraft:L,editing:h,setEditing:T,textareaRef:Le,contentRef:Ee,saving:be,onSave:()=>Dt("ANNOUNCEMENT.md",P),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),j==="norms"&&e.jsx(Jn,{content:N,draft:G,setDraft:me,editing:D,setEditing:M,textareaRef:De,contentRef:Q,saving:be,onSave:()=>Dt("NORMS.md",G),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),j==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),ne?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:ht,value:H,onChange:ae=>w(ae.target.value),onKeyDown:ae=>ae.key==="Enter"&&Qt(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),e.jsx("button",{onClick:Qt,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>v(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{w(m.name),v(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),Re?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:Z,onChange:ae=>ie(ae.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:cs,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>$e(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{ie(m.description??""),$e(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(ii,{teamId:a,teamName:m.name,onDeleted:i})]})]}),y&&e.jsx(Sn,{alertOnly:!0,variant:y.variant??"primary",title:y.title,message:y.message,onConfirm:()=>k(null),onCancel:()=>k(null)})]})}function Jn({content:a,draft:i,setDraft:s,editing:n,setEditing:o,textareaRef:l,contentRef:u,saving:m,onSave:f,placeholder:y,emptyText:k}){return n?e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("textarea",{ref:l,value:i,onChange:j=>s(j.target.value),onBlur:()=>{i!==a?f():o(!1)},onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),s(a),o(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:y}),m&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):e.jsx("div",{ref:u,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{s(a),o(!0)},role:"button",tabIndex:0,onKeyDown:j=>{j.key==="Enter"&&(s(a),o(!0))},children:a.trim()?e.jsx(r.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(El,{content:a,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic",children:k})})}function ii({teamId:a,teamName:i,onDeleted:s}){const[n,o]=r.useState(!1),[l,u]=r.useState(!1),[m,f]=r.useState(!1),[y,k]=r.useState(!1);return e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',i,'"? This removes the team record from the database.']}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:j=>f(j.target.checked),className:"rounded"}),"Also delete all members in this team"]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:j=>u(j.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y,onClick:async()=>{k(!0);try{await A.teams.delete(a,m,{purgeFiles:l}),window.dispatchEvent(new CustomEvent("markus:data-changed")),s()}catch{k(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:y?"Deleting...":"Confirm Delete"}),e.jsx("button",{onClick:()=>o(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function Or(a,i,s,n){return a==="channel"?`ch:${s}`:a==="dm"?`dm:${n??""}`:i||"_direct"}class is{currentConvKey="";loadingSession=null;msgBuffers=new Map;sessionMsgCache=new Map;activeSession=new Map;actBuffers=new Map;sessionTabs=new Map;phase=new Map;sendCount=new Map;streamingSessions=new Map;sessionCacheOrder=[];static MAX_MESSAGES=500;static MAX_CONVERSATIONS=20;static MAX_SESSION_CACHE=30;static NEW_CHAT_ID="__new_chat__";getPhase(i){return this.phase.get(i)??"idle"}beginLoad(i){this.getPhase(i)!=="streaming"&&this.phase.set(i,"loading")}completeLoad(i){this.getPhase(i)==="loading"&&this.phase.set(i,"ready")}beginStream(i){this.phase.set(i,"streaming")}endStream(i){this.getPhase(i)==="streaming"&&this.phase.set(i,"ready")}resetConv(i){this.phase.set(i,"idle"),this.activeSession.delete(i)}updateMessages(i,s,n){const o=this.activeSession.get(i),l=!n||o===n||o===void 0,u=l?this.msgBuffers.get(i)??[]:this.sessionMsgCache.get(n)??[];let m=s(u);m.length>is.MAX_MESSAGES&&(m=m.slice(-500));let f=!1;return l&&(this.msgBuffers.set(i,m),this.evictIfNeeded(i),f=this.currentConvKey===i),n&&n!==is.NEW_CHAT_ID&&(this.sessionMsgCache.set(n,m),this.touchSessionCache(n)),{displayChanged:f,newMessages:f?m:void 0}}applyLoadResult(i,s,n){const o=this.isCacheFresher(s,n);o||(this.sessionMsgCache.set(s,n),this.touchSessionCache(s));const l=this.getPhase(i);if(this.currentConvKey===i&&this.loadingSession===s&&l!=="streaming"){const m=o?this.sessionMsgCache.get(s):n;return this.msgBuffers.set(i,m),this.completeLoad(i),{displayChanged:!0,newMessages:m}}return{displayChanged:!1}}appendActivity(i,s,n){const o=n??i,l=[...this.actBuffers.get(o)??[],s];if(this.actBuffers.set(o,l),this.currentConvKey!==i)return{displayChanged:!1};const u=this.activeSession.get(i);return!n||!u||u===n?{displayChanged:!0,newActivities:l}:{displayChanged:!1}}getActiveSession(i){return this.activeSession.get(i)}setActiveSession(i,s){this.activeSession.set(i,s)}saveToCache(i,s){if(!s||s===is.NEW_CHAT_ID)return;const n=this.msgBuffers.get(i);n&&n.length>0&&(this.sessionMsgCache.set(s,n),this.touchSessionCache(s))}restoreFromCache(i,s){const n=this.sessionMsgCache.get(s);if(n&&n.length>0)return this.msgBuffers.set(i,n),n;this.msgBuffers.delete(i)}isCacheFresher(i,s){const n=this.sessionMsgCache.get(i);if(!n||n.length===0)return!1;if(n.length>s.length)return!0;const o=n.reduce((f,y)=>f+y.text.length,0),l=s.reduce((f,y)=>f+y.text.length,0);if(o>l)return!0;const u=n.reduce((f,y)=>f+(y.segments?.length??0),0),m=s.reduce((f,y)=>f+(y.segments?.length??0),0);return u>m}incrementSend(i){this.sendCount.set(i,(this.sendCount.get(i)??0)+1)}decrementSend(i){const s=Math.max(0,(this.sendCount.get(i)??1)-1);return this.sendCount.set(i,s),s}resetSend(i){this.sendCount.set(i,0)}isSending(i){return(this.sendCount.get(i)??0)>0}addStreamSession(i,s){const n=this.streamingSessions.get(i)??new Set;n.add(s),this.streamingSessions.set(i,n)}removeStreamSession(i,s){if(s){const n=this.streamingSessions.get(i);n&&(n.delete(s),n.size===0&&this.streamingSessions.delete(i))}else this.streamingSessions.delete(i)}getStreamSessions(i){return this.streamingSessions.get(i)}getMessages(i){return this.msgBuffers.get(i)}getActivities(i){return this.actBuffers.get(i)??[]}deleteBuffer(i){this.msgBuffers.delete(i)}evictIfNeeded(i){if(this.msgBuffers.size<=is.MAX_CONVERSATIONS)return;const s=[...this.msgBuffers.keys()],n=s.filter(o=>o!==i&&o!==this.currentConvKey).slice(0,s.length-is.MAX_CONVERSATIONS);for(const o of n)this.msgBuffers.delete(o),this.actBuffers.delete(o),this.sessionTabs.delete(o),this.activeSession.delete(o)}touchSessionCache(i){const s=this.sessionCacheOrder.indexOf(i);for(s!==-1&&this.sessionCacheOrder.splice(s,1),this.sessionCacheOrder.push(i);this.sessionCacheOrder.length>is.MAX_SESSION_CACHE;){const n=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(n)){this.sessionCacheOrder.push(n);break}this.sessionMsgCache.delete(n)}}}const We=is.NEW_CHAT_ID;function _l(a){const i=r.useRef(new is),[s,n]=r.useState(a??[]),[o,l]=r.useState(!1),[u,m]=r.useState([]),f=r.useRef(null);r.useEffect(()=>()=>{f.current!==null&&cancelAnimationFrame(f.current)},[]);const y=r.useCallback((h,T,D)=>{const M=i.current.updateMessages(h,T,D);M.displayChanged&&M.newMessages&&n(M.newMessages)},[]),k=r.useCallback((h,T,D)=>{i.current.updateMessages(h,T,D).displayChanged&&f.current===null&&(f.current=requestAnimationFrame(()=>{f.current=null;const P=i.current.getMessages(h);P&&i.current.currentConvKey===h&&n([...P])}))},[]),j=r.useCallback((h,T,D)=>{const M=i.current.appendActivity(h,T,D);M.displayChanged&&M.newActivities&&m(M.newActivities)},[]),E=r.useCallback(h=>i.current.getPhase(h),[]),p=r.useCallback(h=>i.current.beginLoad(h),[]),b=r.useCallback(h=>i.current.beginStream(h),[]),I=r.useCallback(h=>i.current.endStream(h),[]),N=r.useCallback(h=>{i.current.resetConv(h),i.current.deleteBuffer(h)},[]),_=r.useCallback(async(h,T,D)=>{i.current.loadingSession=h,i.current.beginLoad(T);try{const M=await D(),P=i.current.applyLoadResult(T,h,M.messages);return P.displayChanged&&P.newMessages&&n(P.newMessages),{count:M.messages.length,hasMore:M.hasMore,oldestCursor:M.oldestCursor}}catch{return i.current.currentConvKey===T&&i.current.getPhase(T)!=="streaming"&&(n([]),i.current.completeLoad(T)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:i.current,messages:s,setMessages:n,sending:o,setSending:l,activities:u,setActivities:m,get msgBuffers(){return i.current.msgBuffers},get sessionMsgCache(){return i.current.sessionMsgCache},get activeSessionBuffer(){return i.current.activeSession},get actBuffers(){return i.current.actBuffers},get sessionTabsBuffer(){return i.current.sessionTabs},get currentConvKeyRef(){return{get current(){return i.current.currentConvKey},set current(h){i.current.currentConvKey=h}}},get loadingSessionRef(){return{get current(){return i.current.loadingSession},set current(h){i.current.loadingSession=h}}},updateConvMsgs:y,updateConvMsgsRaf:k,appendConvActivity:j,getPhase:E,beginLoad:p,beginStream:b,endStream:I,resetConv:N,loadAndDisplay:_,incrementSending:h=>i.current.incrementSend(h),decrementSending:h=>i.current.decrementSend(h),resetSending:h=>i.current.resetSend(h),isSendingFor:h=>i.current.isSending(h),setStreamSession:(h,T)=>i.current.addStreamSession(h,T),clearStreamSession:(h,T)=>i.current.removeStreamSession(h,T),getStreamSession:h=>i.current.getStreamSessions(h),saveSessionToCache:(h,T)=>i.current.saveToCache(h,T),restoreSessionFromCache:(h,T)=>{const D=i.current.restoreFromCache(h,T);return n(D??[]),D},isSessionCacheFresherThanDb:(h,T)=>i.current.isCacheFresher(h,T)}}function Al({value:a,onSelect:i,disabled:s}){const{t:n}=Ve("team"),[o,l]=r.useState(!1),[u,m]=r.useState(!1),[f,y]=r.useState(""),[k,j]=r.useState(!1),[E,p]=r.useState([]),[b,I]=r.useState(null),N=r.useRef(null),_=r.useCallback(async()=>{j(!0);try{const M=await fetch("/api/settings/llm",{credentials:"include"});if(!M.ok)throw new Error(`HTTP ${M.status}`);const P=await M.json(),L=[];for(const[me,Ee]of Object.entries(P.providers??{})){if(!Ee.configured||Ee.enabled===!1)continue;const Le=(Ee.models??[]).map(Q=>({id:Q.id,name:Q.name}));Le.length!==0&&L.push({provider:me,displayName:Ee.displayName??me,models:Le})}L.sort((me,Ee)=>me.displayName.localeCompare(Ee.displayName)),p(L);let G=null;if(P.routingDefaultModel?.provider&&P.routingDefaultModel?.model)G={provider:P.routingDefaultModel.provider,model:P.routingDefaultModel.model};else if(P.defaultProvider){const me=P.providers?.[P.defaultProvider];me?.model&&(G={provider:P.defaultProvider,model:me.model})}I(G)}catch{p([])}finally{j(!1)}},[]);r.useEffect(()=>{_()},[_]),r.useEffect(()=>{o&&(m(!1),y(""),_())},[o,_]),r.useEffect(()=>{if(!o)return;const M=P=>{N.current?.contains(P.target)||l(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[o]);const h=r.useMemo(()=>{const M=f.trim().toLowerCase();return E.map(P=>({...P,models:M?P.models.filter(L=>L.id.toLowerCase().includes(M)||(L.name?.toLowerCase().includes(M)??!1)||P.displayName.toLowerCase().includes(M)||P.provider.toLowerCase().includes(M)):P.models})).filter(P=>P.models.length>0)},[E,f]),T=a??b,D=T?.model??"";return e.jsxs("div",{ref:N,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",disabled:s,onClick:()=>l(M=>!M),className:"max-w-[220px] px-2 py-1.5 text-[11px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-lg hover:bg-surface-elevated transition-colors flex items-center gap-1",title:T?`${T.provider}: ${T.model}`:n("chatModel.title",{defaultValue:"Model"}),children:[e.jsx("span",{className:"truncate",children:D||n("chatModel.title",{defaultValue:"Model"})}),e.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),o&&e.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[e.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[e.jsx("input",{autoFocus:!0,value:f,onChange:M=>y(M.target.value),placeholder:n("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-base border border-border-default/50 outline-none focus:border-brand-500/50"}),e.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[e.jsx("span",{children:n("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),e.jsx("button",{type:"button",role:"switch","aria-checked":u,onClick:()=>m(M=>!M),className:`relative w-9 h-5 rounded-full transition-colors ${u?"bg-brand-600":"bg-fg-tertiary/30"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${u?"translate-x-4":""}`})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[k&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:n("common:loading",{defaultValue:"Loading…"})}),!k&&h.length===0&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:n("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!k&&h.map(M=>e.jsxs("div",{className:"mb-1",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:M.displayName}),M.models.slice(0,80).map(P=>{const L=T?.provider===M.provider&&T?.model===P.id;return e.jsxs("button",{type:"button",onClick:()=>{i({provider:M.provider,model:P.id},u),u&&I({provider:M.provider,model:P.id}),l(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${L?"text-fg-primary":"text-fg-secondary"}`,children:[e.jsx("span",{className:"truncate flex-1",children:P.id}),L&&e.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${M.provider}:${P.id}`)})]},M.provider))]})]})]})}async function Il(a,i,s){a&&!a.startsWith("new_")&&await A.sessions.setModelOverride(a,i),s&&await A.settings.updateRouting({defaultProvider:i.provider,routingDefaultModel:{provider:i.provider,model:i.model}})}const oi="markus_team_sidebars_c",Ll=["chat","overview","files","tools","memory","deliverables"],Dl=["chat","overview","announcements","norms","settings"];function Rl(a,i){if(a==="chat")return i("page.chatTitle");if(Wr.find(o=>o.key===a))return i(`agent:tabs.${a}`);const n=Hr.find(o=>o.key===a);return n?i(n.labelKey):a}function $l(a){if(a==="chat")return"💬";const i=Wr.find(n=>n.key===a);if(i)return i.icon;const s=Hr.find(n=>n.key===a);return s?s.icon:""}function as(a){return a!=="chat"}const Br=new Set;function Ol(){return window.location.hash}function Fl(a){return Br.add(a),()=>{Br.delete(a)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Br.forEach(a=>a()));function Gl({initialAgentId:a,authUser:i,previewMode:s,previewData:n}={}){const{t:o,i18n:l}=Ve(["team","common"]),u=r.useMemo(()=>({today:o("page.dateToday"),yesterday:o("page.dateYesterday")}),[o]),m=ci(at.TEAM),[f,y]=r.useState(n?.agents??[]),[k,j]=r.useState(n?.humans??[]),[E,p]=r.useState(!n),b=zr(),I=r.useSyncExternalStore(Fl,Ol),N=b&&(I.startsWith(`#${at.TEAM}/`)||I.startsWith("#chat/")),_=b&&I.match(/^#team\/t\/(.+)$/),h=b?_?"team":N?"chat":"roster":"roster",T=_?_[1]:null,D=r.useRef(at.TEAM),M=r.useCallback(()=>{D.current=window.location.hash.slice(1)||at.TEAM,window.location.hash=`${at.TEAM}/d`},[]),P=r.useCallback(t=>{window.location.hash=`${at.TEAM}/t/${t}`},[]);r.useEffect(()=>{if(!b)return;const t=()=>{as(me.current)&&G("chat")};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[b]);const[L,G]=r.useState("chat"),me=r.useRef("chat");me.current=L;const Ee=Ca({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[Le,Q]=r.useState(()=>{try{return localStorage.getItem(oi)==="1"}catch{return!1}}),De=r.useCallback(t=>{Q(t);try{localStorage.setItem(oi,t?"1":"0")}catch{}},[]),be=Co(),R=be?.leftCollapsed??!1,ne=be?.rightPanel??null,v=be?.rightPanelTabs??[],H=be?.activeRightPanelTabId??null,w=be?.rightPanelFullscreen??!1,Z=ne?"2xl:pr-8":"2xl:pr-[280px]",ie=be?.setHostAvailable,Re=be?.collapseRightPanelOnly??be?.toggleRightPanel,$e=be?.openRightPanel,ye=400,dt=320,ht=6,[zt,ls]=r.useState(typeof window<"u"?window.innerWidth:1440),[Dt,Qt]=r.useState("auto"),cs=r.useRef(R);r.useEffect(()=>{cs.current!==R&&(cs.current=R,Q(R))},[R]),r.useEffect(()=>{if(ie)return ie(m&&!b),()=>ie(!1)},[m,b,ie]),r.useEffect(()=>s||b||!m?void 0:Fe.on("ui:right_panel",d=>{const c=d.payload;if(c.action==="collapse"){Re?.();return}if(c.action!=="open"||!c.panel||!$e)return;const x=c.panel;if(x.kind==="url"&&x.url){const $=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;$e({kind:"url",url:x.url,title:x.title||x.url,browserId:$});return}if(x.kind==="file"&&x.path){$e({kind:"file",path:x.path,title:x.title});return}x.kind==="deliverable"&&x.deliverableId&&A.deliverables.get(x.deliverableId).then($=>{$.deliverable&&$e({kind:"deliverable",deliverable:$.deliverable})}).catch(()=>{})}),[s,b,m,Re,$e]);const Ls=r.useCallback(t=>{const d=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;or(c=>[...c,{id:d,...t}]),requestAnimationFrame(()=>ts.current?.focus())},[]),[Wt,xt]=r.useState(()=>{if(s)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),it=Ca({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),ae=r.useRef(null),[Be,He]=r.useState(!1),[Oe,gt]=r.useState(!1),Xs=r.useCallback(()=>{Be?gt(t=>!t):xt(t=>{const d=!t;try{localStorage.setItem("markus_team_panel_visible",String(d))}catch{}return d})},[Be]);r.useEffect(()=>{if(b)return;const t=ae.current;if(!t)return;const d=new ResizeObserver(([c])=>{if(!c)return;const x=c.contentRect.width;if(ls(x),!s){const $=x-Ee.width-it.width;He($<400)}});return d.observe(t),()=>d.disconnect()},[b,s,Ee.width,it.width]);const Cn=Wt&&!Be&&!Oe,Qs=Le?0:Ee.width+ht+(Cn?it.width+ht:0),Ht=Math.max(0,zt-Qs-ht-8),Js=Math.min(ye,Math.floor(Ht*.4)),Zs=Math.max(0,Ht-Js),Vr=Math.min(Math.round(Ht/2),Zs),ds=Math.max(0,Math.min(Dt==="auto"?Vr:Dt,Zs)),us=r.useRef(!1);r.useEffect(()=>{const t=(be?.rightPanel??null)!==null;t&&!us.current&&(Q(!0),Qt("auto")),us.current=t},[be?.rightPanel]);const Vt=r.useRef(ds);Vt.current=ds;const Tn=r.useRef(Zs);Tn.current=Zs;const rr=r.useCallback(t=>{t.preventDefault();const d=t.clientX,c=Vt.current,x=B=>{const S=c+(d-B.clientX),F=Tn.current,re=Math.min(dt,F);Qt(Math.max(re,Math.min(F,S)))},$=()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",$),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",x),document.addEventListener("mouseup",$),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);r.useEffect(()=>{if(!Oe)return;const t=d=>{d.target.closest("[data-l2-floating]")||gt(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Oe]);const[bs,Jt]=r.useState(null),[Mn,en]=r.useState(),[tn,vs]=r.useState(),[Mt,Rt]=r.useState(!1),[Pn,sn]=r.useState(""),[Ds,nn]=r.useState(!1),[qt,ys]=r.useState(""),Rs=r.useRef(null),Pt=r.useRef(null),ms=r.useCallback((t,d)=>{en(t),vs(d),b?(G("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):G(t??"overview")},[b]),js=[{id:"chat"},{id:"profile"}],rn=r.useCallback(t=>{t==="profile"?ms():as(me.current)?history.back():G("chat")},[ms]),Et=di(js,L,rn),ft=r.useCallback((t,d)=>{_e("direct"),st(t),b&&M(),ms(d?.tab,d?.highlightMailboxId),Jt(null)},[b,M,ms]),$t=r.useCallback((t,d)=>{const c=f.find(x=>x.name.toLowerCase()===t.toLowerCase());if(c){const x=d.target.getBoundingClientRect();Jt({agentId:c.id,top:x.bottom,left:x.left})}},[f]),an=r.useMemo(()=>f.map(t=>t.name),[f]),[O,_e]=r.useState(()=>n?.chatMode??(a?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[te,st]=r.useState(()=>a??localStorage.getItem("markus_chat_agent")??""),[Ne,pt]=r.useState(()=>n?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Je,ws]=r.useState(""),bt=500,Ns=r.useRef(new Set),$s=t=>{if(Ns.current.add(t),Ns.current.size>bt){const d=Math.floor(bt*.2),c=Ns.current.values();for(let x=0;x<d;x++){const $=c.next().value;$&&Ns.current.delete($)}}},ar=r.useMemo(()=>{if(n?.channelMessages){const t=n.activeChannel??"custom:general";return n.channelMessages.filter(d=>d.channel===t).map(d=>Is(d))}},[]),{manager:En,messages:qe,setMessages:vt,sending:yt,setSending:ot,activities:ir,setActivities:Ut,msgBuffers:kt,sessionMsgCache:ks,activeSessionBuffer:_t,actBuffers:Ot,sessionTabsBuffer:_n,currentConvKeyRef:je,updateConvMsgs:Se,updateConvMsgsRaf:Zt,appendConvActivity:Ss,beginLoad:g,beginStream:z,endStream:X,resetConv:ue,loadAndDisplay:ve,incrementSending:Ae,decrementSending:Ue,resetSending:ze,isSendingFor:ke,setStreamSession:Ye,clearStreamSession:lt,getStreamSession:nt,saveSessionToCache:Ft,restoreSessionFromCache:et}=_l(ar),[Xe,St]=r.useState(""),[xs,Ke]=r.useState(null),[Kt,or]=r.useState([]),[qr,on]=r.useState([]),At=r.useRef(null),[lr,An]=r.useState(!!n?.streamLastMessage),Cs=r.useRef(null),vi=400;r.useEffect(()=>(yt?(Cs.current&&(clearTimeout(Cs.current),Cs.current=null),An(!0)):lr&&(Cs.current=setTimeout(()=>{An(!1),Cs.current=null},vi)),()=>{Cs.current&&clearTimeout(Cs.current)}),[yt]);const Ur=yt||lr||(()=>{for(let t=qe.length-1;t>=Math.max(0,qe.length-8);t--){const d=qe[t];if(d.isStreaming&&!d.isStopped)return!0}return!1})(),cr=r.useRef({fullText:"",timers:[]});r.useEffect(()=>{if(!s||!n?.streamLastMessage||qe.length===0)return;const t=qe[qe.length-1];if(!t||t.sender!=="agent")return;const d=t.text;cr.current.fullText=d;const c=cr.current.timers;function x(){let B=0;vt(F=>F.map((re,q)=>q===F.length-1?{...re,text:""}:re)),An(!0);const S=setInterval(()=>{if(B+=1+Math.floor(Math.random()*2),B>=d.length){clearInterval(S),vt(q=>q.map((Y,ee)=>ee===q.length-1?{...Y,text:d}:Y));const F=setTimeout(()=>An(!1),800);c.push(F);const re=setTimeout(x,6e3);c.push(re)}else vt(F=>F.map((re,q)=>q===F.length-1?{...re,text:d.slice(0,B)}:re))},30);c.push(S)}const $=setTimeout(x,1500);return c.push($),()=>{c.forEach(B=>clearTimeout(B)),cr.current.timers=[]}},[]);const gs=r.useRef(0),[Kr,es]=r.useState(!1),[dr,Gr]=r.useState(!1),[Yr,ln]=r.useState(!1),[Bt,ur]=r.useState([]),mr=r.useRef(null),ts=r.useRef(null),[In,Ln]=r.useState(null),Dn=r.useRef(null),xr=r.useCallback(()=>{const t=ts.current;if(!t)return;t.style.height="auto";const d=Math.max(52,Math.min(t.scrollHeight,120));t.style.height=`${d}px`,t.style.overflowY=d>=120?"auto":"hidden"},[]);r.useEffect(()=>{xr()},[Xe,xr]);const gr=t=>{try{const d=localStorage.getItem(`markus_closed_tabs_${t}`);return d?new Set(JSON.parse(d)):new Set}catch{return new Set}},yi=(t,d)=>{const c=gr(t);c.add(d);try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},ji=(t,d)=>{const c=gr(t);if(c.delete(d))try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},wi=t=>{try{return localStorage.getItem(`markus_active_session_${t}`)}catch{return null}},fr=(t,d)=>{if(t)try{d&&d!==We?localStorage.setItem(`markus_active_session_${t}`,d):localStorage.removeItem(`markus_active_session_${t}`)}catch{}},[Xr,Os]=r.useState([]),[Pe,ss]=r.useState(null),[Ts,Ms]=r.useState(!1),[Qr,hr]=r.useState([]),[cn,pr]=r.useState(null),[Ni,Jr]=r.useState(null),[Rn,ki]=r.useState([]),Ct=t=>{ki(d=>{const c=typeof t=="function"?t(d):t,x=new Set;return c.filter($=>x.has($.id)?!1:(x.add($.id),!0))})},$n=r.useRef(null),br=r.useRef(null),Gt=r.useRef(null),[ut,dn]=r.useState(n?.groupChats??[]),vr=r.useRef(ut);vr.current=ut;const Zr=r.useRef(null),[un,ct]=r.useState(!1),[Ps,mn]=r.useState(!1),[ea,Fs]=r.useState(""),[yr,fs]=r.useState([]),[ta,sa]=r.useState(!1),jr=r.useRef(void 0),[Yt,na]=r.useState(n?.teams??[]),[Si,Ci]=r.useState([]),[On,ra]=r.useState([]),[Ti,Mi]=r.useState(null),[Bl,zl]=r.useState(!1),[Wl,Hl]=r.useState(""),[aa,xn]=r.useState(!1),[ia,Pi]=r.useState(""),[gn,Bs]=r.useState(0),[Ei,_i]=r.useState([]),oa=r.useRef(!1),Ai=r.useCallback(()=>{oa.current||(oa.current=!0,(async()=>{const t=[];try{const[d,c,x,$,B]=await Promise.all([A.projects.list().catch(()=>({projects:[]})),A.requirements.list().catch(()=>({requirements:[]})),A.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),A.deliverables.search({limit:100}).catch(()=>({results:[]})),A.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const S of d.projects)t.push({id:S.id,name:S.name,entityType:"project",role:S.status});for(const S of c.requirements)t.push({id:S.id,name:S.title,entityType:"requirement",role:S.priority});for(const S of x.tasks)t.push({id:S.id,name:S.title,entityType:"task",role:S.status});for(const S of $.results)t.push({id:S.id,name:S.title,entityType:"deliverable",role:S.type});for(const S of B.teams)try{const F=await A.workflows.list(S.id);for(const re of F.workflows)t.push({id:re.name,name:re.displayName||re.name,entityType:"workflow",role:`v${re.version}`})}catch{}}catch{}_i(t)})())},[]),Qe=O==="channel"?ut.find(t=>t.channelKey===Ne)?.teamId:void 0,Ii=r.useRef(null),fn=r.useRef(null),jt=r.useRef(null),la=r.useRef(void 0),Fn=r.useRef(!1),Xt=r.useRef(!0),ca=r.useRef(void 0);r.useEffect(()=>{if(!Ts)return;const t=d=>{br.current&&!br.current.contains(d.target)&&$n.current&&!$n.current.contains(d.target)&&Ms(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Ts]);const Bn=(t,d)=>{if(!d||t===d)return`notes:${t}`;const[c,x]=[t,d].sort();return`dm:${c}:${x}`};r.useEffect(()=>{localStorage.setItem("markus_chat_mode",O)},[O]),r.useEffect(()=>{localStorage.setItem("markus_chat_agent",te)},[te]),r.useEffect(()=>{localStorage.setItem("markus_chat_channel",Ne)},[Ne]);const{counts:wr,sessionAgentMap:hn,markRead:pn,setActiveKey:Li,clearActiveKey:Di}=To({enabled:!s}),zn=r.useMemo(()=>{const t={};for(const[d,c]of Object.entries(wr))d.startsWith("channel:")&&(t[d.slice(8)]=c);return t},[wr]),Nr=Mo(hn,wr);r.useEffect(()=>{let t=0;for(const d of Nr.values())t+=d;for(const d of Object.values(zn))t+=d;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:t}}))},[Nr,zn]);const Wn=Nr,Ri=r.useCallback(async t=>{for(const[d,c]of Object.entries(hn))c===t&&pn(`session:${d}`)},[hn,pn]);r.useEffect(()=>{if(s||!((!b||h==="chat")&&L==="chat"))return;if(O==="direct"&&te&&Ri(te),O==="channel"&&Ne)pn(`channel:${Ne}`);else if(O==="direct"&&Pe)pn(`session:${Pe}`);else if(O==="dm"&&Je){const c=`dm:${[i?.id,Je].sort().join(":")}`;pn(`channel:${c}`)}const d=[];if(O==="direct"&&Pe){d.push(`session:${Pe}`);for(const[c,x]of Object.entries(hn))x===te&&d.push(`session:${c}`)}else O==="channel"&&Ne?d.push(`channel:${Ne}`):O==="dm"&&Je&&i?.id&&d.push(`channel:dm:${[i.id,Je].sort().join(":")}`);for(const c of d)Li(c);return()=>{for(const c of d)Di(c)}},[s,O,Ne,Pe,Je,te,h,L,hn]);const It=r.useCallback(()=>A.agents.list().then(t=>y(t.agents)).catch(()=>{}),[]),Tt=r.useCallback(()=>A.teams.list().then(t=>na(t.teams)).catch(()=>{}),[]),zs=r.useCallback(()=>A.groupChats.list().then(t=>dn(t.chats)).catch(()=>{}),[]),$i=r.useMemo(()=>Lr(It,3e3),[It]),Hn=r.useMemo(()=>Lr(Tt,5e3),[Tt]),kr=r.useMemo(()=>Lr(zs,3e3),[zs]),bn=r.useCallback(()=>{A.users.list(i?.orgId).then(t=>j(t.users)).catch(()=>{})},[i?.orgId]);r.useEffect(()=>{s||(Promise.all([It(),Tt()]).finally(()=>p(!1)),bn(),A.tasks.list().then(t=>ra(t.tasks)).catch(()=>{}),A.externalAgents.list().then(t=>Ci(t.agents)).catch(()=>{}),zs())},[s,bn]),r.useEffect(()=>{if(!(!s||!n)&&(y(n.agents??[]),j(n.humans??[]),na(n.teams??[]),dn(n.groupChats??[]),n.channelMessages)){const t=n.activeChannel??"custom:general";vt(n.channelMessages.filter(d=>d.channel===t).map(d=>Is(d)))}},[s,n]),r.useEffect(()=>{if(s||!m)return;It(),Tt();const t=setInterval(It,3e4),d=setInterval(Tt,6e4),c=Fe.on("agent:update",()=>{$i(),Hn()}),x=Fe.on("team:update",()=>{Hn(),kr()}),$=Fe.on("agent:removed",Hn),B=Fe.on("chat:group_created",()=>{zs(),Tt(),It()}),S=Fe.on("chat:group_updated",kr),F=Fe.on("chat:group_deleted",()=>{kr(),Hn()}),re=Fe.on("task:update",Y=>{const ee=Y?.payload;ee?.taskId&&ra(ce=>ce.map(le=>le.id===ee.taskId?{...le,status:ee.status??le.status}:le))}),q=()=>{It(),Tt(),bn()};return window.addEventListener("markus:data-changed",q),()=>{clearInterval(t),clearInterval(d),c(),x(),$(),B(),S(),F(),re(),window.removeEventListener("markus:data-changed",q)}},[s,m,bn]),r.useEffect(()=>{if(s)return;const t=F=>{const re=F.detail;if(Ro(re.page)===at.TEAM){if(re.params?.agentId){if(re.params.profileTab)ft(re.params.agentId,{tab:re.params.profileTab});else if(_e("direct"),st(re.params.agentId),G("chat"),b&&M(),re.params.sessionId){const q=re.params.sessionId;setTimeout(async()=>{try{const{sessions:Y}=await A.sessions.listByAgent(re.params.agentId,20),ee=Y.find(ce=>ce.id===q);ee&&Gn(ee)}catch{}},300)}}if(re.params?.selectAgent&&(_e("direct"),st(re.params.selectAgent),G("chat"),b&&M()),re.params?.prefillMessage){const q=re.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),G("chat"),re.params?.autoSend==="true"?setTimeout(()=>la.current?.(q),300):(St(q),setTimeout(()=>{const Y=ts.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))},100))}if(re.params?.dm&&(_e("dm"),ws(re.params.dm),G("chat"),b&&M()),re.params?.channel&&(_e("channel"),pt(re.params.channel),G("chat"),b&&M()),re.params?.selectTeam){const q=re.params.selectTeam;if(b)P(q);else{const Y=vr.current.find(ee=>ee.type==="team"&&ee.teamId===q);_e("channel"),pt(Y?.channelKey??`group:${q}`),G("chat"),ct(!1),xt(!0)}}re.params?.openHire}},d=localStorage.getItem("markus_nav_agentId");if(d){localStorage.removeItem("markus_nav_agentId");const F=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),_e("direct"),st(d),F?ft(d,{tab:F}):(G("chat"),b&&M())}const c=localStorage.getItem("markus_nav_dm");c&&(localStorage.removeItem("markus_nav_dm"),_e("dm"),ws(c),G("chat"),b&&M());const x=localStorage.getItem("markus_nav_channel");x&&(localStorage.removeItem("markus_nav_channel"),_e("channel"),pt(x),G("chat"),b&&M());const $=localStorage.getItem("markus_nav_prefillMessage");$&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),G("chat"),St($),setTimeout(()=>{const F=ts.current;F&&(F.focus(),F.setSelectionRange(F.value.length,F.value.length))},150));const B=localStorage.getItem("markus_nav_selectAgent");B&&(localStorage.removeItem("markus_nav_selectAgent"),_e("direct"),st(B),G("chat"),b&&M());const S=localStorage.getItem("markus_nav_selectTeam");if(S)if(localStorage.removeItem("markus_nav_selectTeam"),b)P(S);else{const F=vr.current.find(re=>re.type==="team"&&re.teamId===S);_e("channel"),pt(F?.channelKey??`group:${S}`),G("chat"),ct(!1),xt(!0)}return window.addEventListener("markus:navigate",t),()=>window.removeEventListener("markus:navigate",t)},[s]),r.useEffect(()=>{const t=Zr.current;if(!t)return;const d=ut.find(c=>c.type==="team"&&c.teamId===t);Zr.current=null,_e("channel"),pt(d?.channelKey??`group:${t}`),G("chat"),ct(!1),xt(!0)},[ut,Yt]),r.useEffect(()=>{if(s&&n?.chatMode==="channel"||f.length===0||te&&f.some(d=>d.id===te))return;const t=f.find(d=>!d.teamId&&d.role?.toLowerCase()==="secretary")??f.find(d=>d.role?.toLowerCase()==="secretary")??f.find(d=>d.name?.toLowerCase().includes("secretary"));t?(_e("direct"),st(t.id),G("chat")):f.length>0&&(_e("direct"),st(f[0].id),G("chat"))},[f,te]);const Vn=r.useRef(!1),[Oi,Es]=r.useState(!1),_s=r.useRef(0),[da,Ws]=r.useState(0),Hs=r.useCallback(t=>{const d=fn.current;if(!d)return;if(d.scrollHeight-d.scrollTop-d.clientHeight<160){Xt.current=!0,Es(!1),_s.current=0,Ws(0);return}t?.fromProgrammatic||Vn.current||(Xt.current=!1,Es(!0))},[]);r.useEffect(()=>{const t=fn.current;if(!t)return;const d=()=>{Hs({fromProgrammatic:Vn.current})};t.addEventListener("scroll",d,{passive:!0});const c=typeof ResizeObserver<"u"?new ResizeObserver(()=>Hs()):null;return c?.observe(t),Hs(),()=>{t.removeEventListener("scroll",d),c?.disconnect()}},[h,Hs]);const wt=r.useMemo(()=>O==="channel"?qe:qe.filter(t=>!t.isActivityLog),[qe,O]),ns=el({count:wt.length,getScrollElement:()=>fn.current,estimateSize:t=>{const d=wt[t];return d?d.segments&&d.segments.length>0?300:d.text.length>500?200:120:120},overscan:8});ns.shouldAdjustScrollPositionOnItemSizeChange=(t,d,c)=>Ta()?!1:t.start<(c.scrollOffset??0);const Vs=r.useCallback((t="instant")=>{Vn.current=!0;const d=()=>{Vn.current=!1,Xt.current=!0,Es(!1),_s.current=0,Ws(0),requestAnimationFrame(()=>Hs({fromProgrammatic:!0}))};if(wt.length>0)ns.scrollToIndex(wt.length-1,{align:"end",behavior:t}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{ns.scrollToIndex(wt.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(d)})});else{const c=fn.current;c&&c.scrollTo({top:c.scrollHeight,behavior:t}),requestAnimationFrame(d)}},[wt.length,ns,Hs]),ua=r.useRef(m);r.useEffect(()=>{ua.current=m},[m]),r.useLayoutEffect(()=>{if(Fn.current){Fn.current=!1;const t=Un.current;t>0&&(Un.current=0,ns.scrollToIndex(t,{align:"start",behavior:"instant"}));return}ua.current&&Xt.current&&(Ta()||Vs())},[qe,Vs,ns]);const ma=r.useRef(L);r.useEffect(()=>{const t=ma.current!=="chat";if(ma.current=L,L==="chat"&&t&&(Xt.current||yt)){const d=[],c=requestAnimationFrame(()=>Vs("instant"));for(const x of[60,160,320])d.push(setTimeout(()=>Vs("instant"),x));return()=>{cancelAnimationFrame(c);for(const x of d)clearTimeout(x)}}},[L,yt,Vs]);const xa=r.useCallback(async(t,d)=>{const c=d??`ch:${t}`;je.current===c&&ln(!0);try{const x=await A.channels.getMessages(t,50),$=x.messages.map(B=>Is(B,i?.id));kt.set(c,$),je.current===c&&(vt($),es(x.hasMore),Gt.current=x.messages[0]?new Date(x.messages[0].createdAt).toISOString():null)}catch{je.current===c&&(vt([]),es(!1))}finally{je.current===c&&ln(!1)}},[]),ga=r.useCallback(async(t,d)=>{je.current===d&&ln(!0);try{const{count:c,hasMore:x,oldestCursor:$}=await ve(t,d,async()=>{const B=await A.sessions.getMessages(t,50);return{messages:B.messages.map(Dr).filter(F=>F.sender!=="agent"||F.text||F.segments&&F.segments.length>0||F.isStreaming),hasMore:B.hasMore,oldestCursor:B.messages[0]?new Date(B.messages[0].createdAt).toISOString():null}});return es(x),Gt.current=$,c}finally{je.current===d&&ln(!1)}},[ve]),fa=r.useRef(new Map),qs=r.useCallback(async(t,d,c)=>{if(!(!t||!d||d===We))try{if(jt.current&&!jt.current.signal.aborted&&nt(c)?.has(d)){z(c),je.current===c&&ot(!0);return}const x=`${t}:${d}`,$=fa.current.get(x)??0;if(Date.now()-$<1500)return;const B=await A.sessions.streamStatus(t,d),F=[...kt.get(c)??[]].reverse().find(xe=>xe.sender==="agent"),re=B.status==="streaming",q=!!B.active&&(B.status==="done"||B.status==="error")&&!!F?.isStreaming;if(!re&&!q)return;fa.current.set(x,Date.now()),Dn.current?.abort();const Y=new AbortController;Dn.current=Y,z(c),ot(!0),Ye(c,d);let ee=F?.id;if(!F||F.isError)ee=`reattach_${Date.now()}`,Se(c,xe=>[...xe,{id:ee,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],d);else{const xe=(F.segments??[]).filter(we=>we.type==="tool").map(we=>we.status==="stopped"||we.status==="running"?{...we,status:"running"}:we);Se(c,we=>we.map(J=>J.id===F.id?{...J,text:"",isStreaming:!0,isStopped:!1,segments:xe,committedSegments:void 0}:J),d)}let ce=!1;const le=xe=>{je.current===c&&(gs.current=Date.now(),Zt(c,we=>{const J=[...we],he=ee?J.findIndex(oe=>oe.id===ee):-1,ge=he>=0?he:J.map((oe,pe)=>({m:oe,j:pe})).reverse().find(oe=>oe.m.sender==="agent")?.j??-1;if(ge<0)return we;const C=J[ge].segments??[],U=C[C.length-1],V=U?.type==="text"?U.thinking??"":"";let se="",K="",W=xe;for(;W.length>0;)if(ce){const oe=W.indexOf("</think>");oe>=0?(se+=W.slice(0,oe),W=W.slice(oe+8),ce=!1):(se+=W,W="")}else{const oe=W.indexOf("<think>");oe>=0?(K+=W.slice(0,oe),W=W.slice(oe+7),ce=!0):(K+=W,W="")}const fe=V+se||void 0,Me=U?.type==="text"?[...C.slice(0,-1),{type:"text",content:U.content+K,thinking:fe,createdAt:U.createdAt}]:[...C,{type:"text",content:K,thinking:fe,createdAt:new Date().toISOString()}];return J[ge]={...J[ge],text:(J[ge].text??"")+K,segments:Me,isStreaming:!0},J},d))},de=xe=>{if(je.current===c&&(gs.current=Date.now(),xe.phase!=="heartbeat")){if((xe.phase==="start"||xe.phase==="end")&&Ss(c,{...xe,phase:xe.phase,ts:Date.now()},d),xe.phase==="start"){const we=`${xe.tool}_${Date.now()}`,J=new Date().toISOString(),he=ge=>{const C=[...ge];for(let U=C.length-1;U>=0;U--){const V=C[U];if(V.type==="tool"&&V.tool===xe.tool&&(V.status==="running"||V.status==="stopped"))return C[U]={...V,status:"running",args:xe.arguments??V.args},C}return C.push({type:"tool",key:we,tool:xe.tool,status:"running",args:xe.arguments,createdAt:J}),C};Se(c,ge=>{const C=[...ge],U=ee?C.findIndex(W=>W.id===ee):-1;if(U<0)return ge;const V=he(C[U].segments??[]),se=C[U].committedSegments,K=se&&he(se);return C[U]={...C[U],segments:V,committedSegments:K,isStreaming:!0},C},d)}else if(xe.phase==="end"){const we=new Date().toISOString(),J=he=>{const ge=[...he];for(let C=ge.length-1;C>=0;C--){const U=ge[C];if(U.type==="tool"&&U.tool===xe.tool&&(U.status==="running"||U.status==="stopped")){ge[C]={...U,status:xe.success===!1?"error":"done",args:xe.arguments??U.args,result:xe.result,error:xe.error,durationMs:xe.durationMs,liveOutput:void 0,createdAt:we};break}}return ge};Se(c,he=>{const ge=[...he],C=ee?ge.findIndex(K=>K.id===ee):-1;if(C<0)return he;const U=J(ge[C].segments??[]),V=ge[C].committedSegments,se=V&&J(V);return ge[C]={...ge[C],segments:U,committedSegments:se,isStreaming:!0},ge},d)}else if(xe.phase==="subagent_progress"&&xe.subagentEvent){const we=J=>{const he=[...J];for(let ge=he.length-1;ge>=0;ge--){const C=he[ge];if(C.type==="tool"&&(C.tool==="spawn_subagent"||C.tool==="spawn_subagents")&&(C.status==="running"||C.status==="stopped")){he[ge]={...C,status:"running",subagentLogs:_a(C.subagentLogs,xe.subagentEvent)};break}}return he};Zt(c,J=>{const he=[...J],ge=ee?he.findIndex(se=>se.id===ee):-1;if(ge<0)return J;const C=we(he[ge].segments??[]),U=he[ge].committedSegments,V=U&&we(U);return he[ge]={...he[ge],segments:C,committedSegments:V,isStreaming:!0},he},d)}}},Ce=xe=>{je.current===c&&(gs.current=Date.now(),Se(c,we=>{const J=[...we],he=ee?J.findIndex(C=>C.id===ee):-1;if(he<0)return we;const ge=[...J[he].committedSegments??[]];if(xe.type==="thinking_commit")ge.push({type:"text",content:"",thinking:xe.content,createdAt:xe.createdAt});else if(xe.type==="text_commit")ge.push({type:"text",content:xe.content,createdAt:xe.createdAt});else return we;return J[he]={...J[he],committedSegments:ge,isStreaming:!0},J},d))},Te=xe=>{if(je.current!==c)return;gs.current=Date.now();const we=(xe.segments??[]).map((J,he)=>J.type==="tool"?{type:"tool",key:`${J.tool}_${he}`,tool:J.tool??"tool",status:J.status==="error"?"error":J.status==="running"||J.status==="stopped"?"running":"done",args:J.arguments,result:J.result,error:J.error,durationMs:J.durationMs,createdAt:J.createdAt,...J.subagentLogs?.length?{subagentLogs:J.subagentLogs}:{}}:{type:"text",content:J.content??"",thinking:J.thinking,createdAt:J.createdAt});Se(c,J=>{const he=[...J],ge=ee?he.findIndex(C=>C.id===ee):-1;return ge<0?J:(he[ge]={...he[ge],text:xe.content||he[ge].text,segments:we,committedSegments:we,isStreaming:!0,isStopped:!1},he)},d);for(const J of we)J.type==="tool"&&Ss(c,{tool:J.tool,phase:J.status==="running"||J.status==="stopped"?"start":"end",success:J.status!=="error",arguments:J.args,result:J.result,error:J.error,durationMs:J.durationMs,ts:Date.now()},d)},Ie=await A.sessions.reattachStream(t,d,{onChunk:le,onActivity:de,onCommit:Ce,onSnapshot:Te},Y.signal,0);if(!Ie.attached){X(c),je.current===c&&ot(!1);return}je.current===c&&(Se(c,xe=>{const we=[...xe],J=ee?we.findIndex(U=>U.id===ee):-1,he=J>=0?J:we.map((U,V)=>({m:U,j:V})).reverse().find(U=>U.m.sender==="agent")?.j??-1;if(he<0)return xe;const ge=we[he],C=Ie.segments?.length?Aa(Ie.segments,ge.segments):void 0;return we[he]={...ge,text:Ie.content||ge.text,isStreaming:!1,isStopped:!1,...C?{segments:C,committedSegments:C}:{}},we},d),ot(!1)),X(c),Dn.current===Y&&(Dn.current=null)}catch(x){if(x instanceof Error&&x.name==="AbortError")return;X(c),je.current===c&&ot(!1)}},[Ss,z,X,nt,kt,Ye,Se,Zt]);r.useEffect(()=>{if(!m||s||O!=="direct"||!te)return;const t=Pe;!t||t===We||qs(te,t,je.current)},[m,s,O,te,Pe,qs]);const qn=r.useCallback(async t=>{if(!t)return Os([]),[];try{const{sessions:d}=await A.sessions.listByAgent(t,10);return Os(d),d}catch{return Os([]),[]}},[]),Un=r.useRef(0),Fi=r.useCallback(async()=>{if(!(dr||!Kr||!Gt.current)){Gr(!0);try{const t=je.current;if(O==="channel"||O==="dm"){const d=O==="dm"?Bn(i?.id??"",Je):Ne,c=await A.channels.getMessages(d,50,Gt.current),x=c.messages.map($=>Is($,i?.id));Un.current=x.length,Fn.current=!0,vt($=>{let B=[...x,...$];return B.length>500&&(B=B.slice(-500)),kt.set(t,B),B}),es(c.hasMore),c.messages[0]&&(Gt.current=new Date(c.messages[0].createdAt).toISOString())}else if(Pe){const d=await A.sessions.getMessages(Pe,50,Gt.current),c=d.messages.map(Dr);Un.current=c.length,Fn.current=!0,vt(x=>{let $=[...c,...x];return $.length>500&&($=$.slice(-500)),kt.set(t,$),$}),es(d.hasMore),d.messages[0]&&(Gt.current=new Date(d.messages[0].createdAt).toISOString())}}catch{}finally{Gr(!1)}}},[dr,Kr,O,Ne,Pe,i?.id,Je]);ca.current=Fi;const Sr=r.useRef(!1),Bi=r.useCallback(t=>{Sr.current||(Sr.current=!0,requestAnimationFrame(()=>{Sr.current=!1,t.target.scrollTop<100&&ca.current?.()}))},[]);r.useEffect(()=>{if(s)return;const t=Or(O,te,Ne,Je),d=je.current;je.current=t,d&&d!==t&&(_n.set(d,Rn),Pe&&_t.set(d,Pe)),d!==t&&(Xt.current=!0,Es(!1),_s.current=0,Ws(0));const c=kt.get(t),x=_n.get(t),$=_t.get(t),B=nt(t),S=$??Pe,F=ke(t)&&(O!=="direct"||!B||!S||B.has(S)),re=S??t,q=Ot.get(re)??[];if(Ut(F?q:[]),ot(F),O==="direct"&&te&&qn(te),x&&x.length>0&&Ct(x),Ms(!1),c!==void 0)if(F||En.completeLoad(t),ln(!1),vt(c),es(!1),$!==void 0&&ss($),(!x||x.length===0)&&Ct([]),O==="channel"||O==="dm"){const Y=O==="dm"?Bn(i?.id??"",Je):Ne;xa(Y,t)}else O==="direct"&&te&&$&&$!==We&&qs(te,$,t);else if(g(t),vt([]),es(!1),Gt.current=null,O==="channel"||O==="dm"){const Y=O==="dm"?Bn(i?.id??"",Je):Ne;xa(Y,t),(!x||x.length===0)&&Ct([])}else O==="direct"&&te&&qn(te).then(Y=>{if(je.current===t)if(Y.length>0){const ee=Y.find(J=>J.isMain),ce=gr(te),le=ee?[ee,...Y.filter(J=>!J.isMain&&!ce.has(J.id)).slice(0,4)]:Y.filter(J=>!ce.has(J.id)).slice(0,5);let de=x&&x.length>0?x:le;const Ce=wi(te),Te=$!==void 0?$:Ce??ee?.id??de[0].id;if(Te&&Te!==We&&!de.some(J=>J.id===Te)){const J=Y.find(he=>he.id===Te);J&&(de=[...de,J])}const Ie=Te&&de.some(J=>J.id===Te)?Te:de[0].id;ss(Ie),fr(te,Ie),Ct(de);const we=Y.find(J=>J.id===Ie)?.metadata?.modelOverride;Ln(we?.provider&&we?.model?{provider:we.provider,model:we.model}:null),ga(Ie,t).then(()=>{je.current===t&&te&&qs(te,Ie,t)})}else ss(null),Ln(null),(!x||x.length===0)&&Ct([])})},[s,O,te,Ne,Je,l.language,o]),r.useEffect(()=>s?void 0:Fe.on("chat:message",d=>{const c=d.payload,x=c.channel??"";if(!x)return;const $=c.senderType??"agent",B=c.text??c.message??"",S=c.senderId??c.agentId??"",F=c.senderName??c.agentId??o("page.fallbackAgent"),re=c.metadata,q=c.messageId??c.id??"";if(q&&Ns.current.has(q))return;const Y=$==="human"&&S===(i?.id??""),ee={id:q||`ws_${Date.now()}_${S}`,sender:Y?"user":"agent",text:B,time:new Date().toLocaleTimeString(),agentName:Y?void 0:F,agentId:Y?void 0:S,replyToId:c.replyToId??void 0,replyToSender:c.replyToSender??void 0,replyToText:c.replyToText??void 0};if(re&&$==="agent"){const le=[];if(re.thinking?.length&&le.push({type:"text",content:"",thinking:re.thinking.join(`
28
+
29
+ `)}),re.toolCalls?.length)for(let de=0;de<re.toolCalls.length;de++){const Ce=re.toolCalls[de];le.push({type:"tool",key:`${Ce.tool}_${de}`,tool:Ce.tool,status:Ce.status==="error"?"error":"done",args:Ce.arguments,result:Ce.result,durationMs:Ce.durationMs})}le.length>0&&(le.push({type:"text",content:B}),ee.segments=le)}let ce;if(x.startsWith("notes:"))ce=`dm:${x.slice(6)}`;else if(x.startsWith("dm:")){const le=x.slice(3).split(":");ce=`dm:${le.find(Ce=>Ce!==(i?.id??""))??le[0]??""}`}else ce=`ch:${x}`;Se(ce,le=>[...le,ee]),ce===je.current&&!Xt.current&&(_s.current+=1,Ws(_s.current),Es(!0)),$==="agent"&&ce===`ch:${Ne}`&&on(le=>{const de=le.filter(Ce=>Ce.id!==S);return de.length===0&&At.current&&(clearTimeout(At.current),At.current=null),de})}),[s,Se,i?.id,Ne]),r.useEffect(()=>s?void 0:Fe.on("chat:agent_no_response",d=>{const c=d.payload,x=c.channel??"",$=c.agentId??"";x&&$&&`ch:${Ne}`==`ch:${x}`&&on(B=>{const S=B.filter(F=>F.id!==$);return S.length===0&&At.current&&(clearTimeout(At.current),At.current=null),S})}),[s,Ne]),r.useEffect(()=>s?void 0:Fe.on("chat:proactive_message",d=>{const c=d.payload,x=c.targetUserId;if(x&&x!==i?.id)return;const $=c.agentId??"",B=c.agentName??o("page.fallbackAgent"),S=c.message??"",F=c.sessionId??"",re=c.messageId??"",q=c.metadata??{};if(!$||!S||S==="[cancelled]"||S==="[Stream cancelled]")return;const Y=q.role==="user",ee=!Y&&(!!q.activityLog||S.startsWith("[ACTIVITY:")),{cleaned:ce,priority:le}=Fo(S),de=!Y&&(!!q.notifyUser||ce!==S),Ce=Or("direct",$,"","");if(F&&je.current===Ce){const he=Pe;if(he&&he!==We&&he!==F)return}const Te=!!q.isMainSession&&!Y,Ie=F||Pe,xe=typeof q.userText=="string"?q.userText:"",we=typeof q.userMessageId=="string"?q.userMessageId:"",J={id:re||`proactive_${Date.now()}`,sender:Y?"user":"agent",text:ce,time:new Date().toLocaleTimeString(),...Y?{}:{agentName:B,agentId:$,...de?{isNotification:!0,notifyPriority:q.priority??le}:{},...ee?{isActivityLog:!0,activityType:q.activityType,outcome:q.outcome,mailboxItemId:q.mailboxItemId,taskId:q.taskId,requirementId:q.requirementId}:{},...!ee&&q.taskId?{taskId:q.taskId}:{},...!ee&&q.requirementId?{requirementId:q.requirementId}:{}}};Se(Ce,he=>{if(he.some(C=>C.id===J.id))return he;let ge=he;if(!Y&&xe&&(ge.some(U=>we&&U.id===we||U.sender==="user"&&U.text===xe)||(ge=[...ge,{id:we||`feishu_user_${J.id}`,sender:"user",text:xe,time:new Date().toLocaleTimeString()}])),Te)for(let C=ge.length-1;C>=0;C--){const U=ge[C];if(U.sender==="agent"&&U.agentId===$&&U.isStopped){const V=[...ge];return V[C]={...J,id:U.id},V}}return[...ge,J]},Ie||void 0)}),[s,Se,o,Pe]),On.find(t=>t.id===Ti),r.useEffect(()=>{Mi(null)},[te]);const zi=t=>$o(t),Wi=()=>{jt.current?.abort(),jt.current=null;const t=je.current;ze(t),Ot.delete(Pe??t),Pe&&lt(t,Pe),X(t),ot(!1),Ut([]),O==="direct"&&te&&A.agents.cancelProcessing(te).catch(()=>{})},vn=async(t,d)=>{const c=!t&&Kt.length>0?Kt.map(Y=>Y.content).join(`
30
+
31
+ `)+`
32
+
33
+ `:"",x=(t??c+Xe).trim();if(!x&&Bt.length===0||O==="direct"&&!te)return;if(Xt.current=!0,yt&&O==="direct"){if(Pe&&Pe!==We){jt.current?.abort(),jt.current=null,A.agents.cancelProcessing(te).catch(()=>{});const ee=je.current;ze(ee),Ot.delete(Pe??ee),X(ee),Se(ee,ce=>{const le=[...ce];for(let de=le.length-1;de>=0;de--)if(le[de].sender==="agent"&&!le[de].isStopped&&!le[de].isError){const Ce=le[de];if(!(Ce.text?.trim()||(Ce.segments??[]).some(Ie=>Ie.type==="text"&&(Ie.content||Ie.thinking)||Ie.type==="tool")))le.splice(de,1);else{const Ie=(Ce.segments??[]).map(xe=>xe.type==="tool"&&xe.status==="running"?{...xe,status:"stopped"}:xe);le[de]={...Ce,isStopped:!0,segments:Ie}}break}return le}),ot(!1),Ut([]),await new Promise(ce=>setTimeout(ce,50))}}else if(yt&&O!=="direct"){jt.current?.abort(),jt.current=null;const Y=je.current;ze(Y),Ot.delete(Y),X(Y),Se(Y,ee=>{const ce=[...ee];for(let le=ce.length-1;le>=0;le--)if(ce[le].sender==="agent"&&!ce[le].isStopped&&!ce[le].isError){const de=ce[le];if(!(de.text?.trim()||(de.segments??[]).some(Te=>Te.type==="text"&&(Te.content||Te.thinking)||Te.type==="tool")))ce.splice(le,1);else{const Te=(de.segments??[]).map(Ie=>Ie.type==="tool"&&Ie.status==="running"?{...Ie,status:"stopped"}:Ie);ce[le]={...de,isStopped:!0,segments:Te}}break}return ce}),ot(!1),Ut([]),await new Promise(ee=>setTimeout(ee,50))}const $=Bt.length>0?Bt.map(Y=>Y.dataUrl):void 0,B=Bt.length>0?Bt.map(Y=>Y.name):void 0,S=Or(O,te,Ne,Je),F=xs;t||(St(""),or([])),ur([]),xn(!1),Ke(null);const re=O==="dm";Ae(S);const q=Pe??S;if(Ot.set(q,[]),je.current===S&&!re&&(ot(!0),Ut([])),O==="dm"){const Y=Bn(i?.id??"",Je),ee=`opt_${Date.now()}`,ce={id:ee,sender:"user",text:x,time:new Date().toLocaleTimeString()};F&&(ce.replyToId=F.id,ce.replyToSender=F.sender,ce.replyToText=F.text),Se(S,le=>[...le,ce]);try{const le=await A.channels.sendMessage(Y,{text:x,senderName:i?.name??o("page.fallbackYou"),senderId:i?.id,mentions:[],orgId:"default",humanOnly:!0});le.userMessage&&$s(le.userMessage.id),Se(S,de=>{const Ce=de.filter(Ie=>Ie.id!==ee),Te=[];return le.userMessage&&Te.push(Is(le.userMessage,i?.id)),Te.length>0?[...Ce,...Te]:de})}catch(le){Zn(le)&&er(),Se(S,de=>[...de,{id:`err_${Date.now()}`,sender:"agent",text:o("page.errorWithMessage",{message:String(le)}),time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}])}Ue(S),je.current===S&&ot(!1)}else if(O==="channel"){const Y=`opt_${Date.now()}`,ee={id:Y,sender:"user",text:x,time:new Date().toLocaleTimeString()};F&&(ee.replyToId=F.id,ee.replyToSender=F.sender,ee.replyToText=F.text),Se(S,de=>[...de,ee]);const ce=zi(x),le=ut.find(de=>de.channelKey===Ne);if(Ne.startsWith("group:")){const de=[];if(le?.members){for(const Ce of le.members)if(Ce.type==="agent"){const Te=f.find(Ie=>Ie.id===Ce.id);Te&&de.push({id:Te.id,name:Te.name,avatarUrl:Te.avatarUrl})}}de.length>0&&(At.current&&clearTimeout(At.current),on(de),At.current=setTimeout(()=>on([]),12e4))}try{const de=F?`> **${F.sender}**: ${F.text}
34
+
35
+ ${x}`:x,Ce=await A.channels.sendMessage(Ne,{text:de,senderName:i?.name??o("page.fallbackYou"),mentions:ce,senderId:i?.id,orgId:"default",replyToId:F?.id});Ce.userMessage&&$s(Ce.userMessage.id),Ce.agentMessage&&$s(Ce.agentMessage.id),Se(S,Te=>{const Ie=Te.filter(we=>we.id!==Y),xe=[];return Ce.userMessage&&xe.push(Is(Ce.userMessage,i?.id)),Ce.agentMessage&&xe.push(Is(Ce.agentMessage,i?.id)),xe.length>0?[...Ie,...xe]:Te})}catch(de){Zn(de)&&er();const Ce=tr(de,o)||o("page.errorWithMessage",{message:String(de)});Se(S,Te=>[...Te,{id:`err_${Date.now()}`,sender:"agent",text:Ce,time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}]),At.current&&(clearTimeout(At.current),At.current=null),on([])}Ue(S),je.current===S&&ot(!1)}else{z(S);const Y=`a_${Date.now()}`;let ee=Pe===We?null:Pe;if(d?.isResume){const C=new Date().toISOString();Se(S,U=>[...U,{id:Y,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:C,segments:[]}],ee)}else{const C=new Date().toISOString(),U={id:`u_${Date.now()}`,sender:"user",text:x,time:new Date().toLocaleTimeString()};$?.length&&(U.images=$),F&&(U.replyToId=F.id,U.replyToSender=F.sender,U.replyToText=F.text),Se(S,V=>[...V,U,{id:Y,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:C,segments:[]}],ee)}let ce=!1;const le=C=>{gs.current=Date.now(),Zt(S,U=>{const V=[...U],se=V.findIndex(rs=>rs.id===Y);if(se<0)return U;const K=V[se].segments??[],W=K[K.length-1],fe=W?.type==="text"?W.thinking??"":"";let Me="",oe="",pe=C;for(;pe.length>0;)if(ce){const rs=pe.indexOf("</think>");rs>=0?(Me+=pe.slice(0,rs),pe=pe.slice(rs+8),ce=!1):(Me+=pe,pe="")}else{const rs=pe.indexOf("<think>");rs>=0?(oe+=pe.slice(0,rs),pe=pe.slice(rs+7),ce=!0):(oe+=pe,pe="")}const tt=fe+Me||void 0,hs=W?.type==="text"?[...K.slice(0,-1),{type:"text",content:W.content+oe,thinking:tt,createdAt:W.createdAt}]:[...K,{type:"text",content:oe,thinking:tt,createdAt:new Date().toISOString()}];return V[se]={...V[se],text:V[se].text+oe,segments:hs},V},ee)},de=C=>{if(gs.current=Date.now(),C.type==="session_start"&&C.sessionId){const U=ee;ee=C.sessionId,U&&U!==C.sessionId&&lt(S,U),Ye(S,C.sessionId),In&&A.sessions.setModelOverride(C.sessionId,In).catch(()=>{});const V=kt.get(S);if(V&&V.length>0&&ks.set(C.sessionId,V),je.current===S){const se=Pe;(!se||se===We||se===C.sessionId)&&(ss(C.sessionId),_t.set(S,C.sessionId),te&&fr(te,C.sessionId),Ct(K=>K.some(W=>W.id===We)?K.map(W=>W.id===We?{...W,id:C.sessionId}:W):K.some(W=>W.id===C.sessionId)?K:[...K,{id:C.sessionId,agentId:te??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}Se(S,U=>{const V=[...U],se=V.findIndex(W=>W.id===Y);if(se<0)return U;const K=[...V[se].committedSegments??[]];return C.type==="thinking_commit"?K.push({type:"text",content:"",thinking:C.content,createdAt:C.createdAt}):K.push({type:"text",content:C.content,createdAt:C.createdAt}),V[se]={...V[se],committedSegments:K},V},ee)},Ce=C=>{gs.current=Date.now(),C.phase!=="heartbeat"&&((C.phase==="start"||C.phase==="end")&&Ss(S,{...C,phase:C.phase,ts:Date.now()},ee),C.phase==="start"?Se(S,U=>{const V=[...U],se=V.findIndex(pe=>pe.id===Y);if(se<0)return U;const K=[...V[se].segments??[]];let W=!1;if(C.arguments)for(let pe=K.length-1;pe>=0;pe--){const tt=K[pe];if(tt.type==="tool"&&tt.tool===C.tool&&tt.status==="running"){K[pe]={...tt,args:C.arguments},W=!0;break}}const fe=`${C.tool}_${Date.now()}`,Me=new Date().toISOString();W||K.push({type:"tool",key:fe,tool:C.tool,status:"running",args:C.arguments,createdAt:Me});const oe=[...V[se].committedSegments??[]];return C.arguments!==void 0&&oe.push({type:"tool",key:fe,tool:C.tool,status:"running",args:C.arguments,createdAt:Me}),V[se]={...V[se],segments:K,committedSegments:oe},V},ee):C.phase==="output"?Zt(S,U=>{const V=[...U],se=V.findIndex(W=>W.id===Y);if(se<0)return U;const K=[...V[se].segments??[]];for(let W=K.length-1;W>=0;W--){const fe=K[W];if(fe.type==="tool"&&fe.tool===C.tool&&fe.status==="running"){K[W]={...fe,liveOutput:Wo(fe.liveOutput,C.output??"")};break}}return V[se]={...V[se],segments:K},V},ee):C.phase==="subagent_progress"&&C.subagentEvent?Zt(S,U=>{const V=[...U],se=V.findIndex(Me=>Me.id===Y);if(se<0)return U;const K=Me=>{const oe=[...Me];for(let pe=oe.length-1;pe>=0;pe--){const tt=oe[pe];if(tt.type==="tool"&&(tt.tool==="spawn_subagent"||tt.tool==="spawn_subagents")&&tt.status==="running"){oe[pe]={...tt,subagentLogs:_a(tt.subagentLogs,C.subagentEvent)};break}}return oe},W=K(V[se].segments??[]),fe=K(V[se].committedSegments??[]);return V[se]={...V[se],segments:W,committedSegments:fe},V},ee):Se(S,U=>{const V=[...U],se=V.findIndex(oe=>oe.id===Y);if(se<0)return U;const K=new Date().toISOString(),W=[...V[se].segments??[]];let fe;for(let oe=W.length-1;oe>=0;oe--){const pe=W[oe];if(pe.type==="tool"&&pe.tool===C.tool&&pe.status==="running"){fe=pe.subagentLogs,W[oe]={...pe,status:C.success===!1?"error":"done",args:C.arguments,result:C.result,error:C.error,durationMs:C.durationMs,liveOutput:void 0,createdAt:K};break}}const Me=[...V[se].committedSegments??[]];for(let oe=Me.length-1;oe>=0;oe--){const pe=Me[oe];if(pe.type==="tool"&&pe.tool===C.tool&&pe.status==="running"){Me[oe]={...pe,status:C.success===!1?"error":"done",args:C.arguments,result:C.result,error:C.error,durationMs:C.durationMs,liveOutput:void 0,createdAt:K,subagentLogs:fe??pe.subagentLogs};break}}return V[se]={...V[se],segments:W,committedSegments:Me},V},ee))},Te=new AbortController;jt.current=Te;const Ie=Pe;Ie&&Ye(S,Ie);try{gs.current=Date.now();const C=Pe===We?null:Pe,U=F?`> **${F.sender}**: ${F.text}
36
+
37
+ ${x}`:x,V=await A.agents.messageStream(te,U,le,Ce,Te.signal,$,C,d?.isRetry,d?.isResume,de,B,F,In);if(je.current===S){V.merged&&Se(S,K=>K.filter(W=>W.id!==Y),ee),!V.merged&&V.segments?.length&&Se(S,K=>{const W=[...K],fe=W.findIndex(pe=>pe.id===Y);if(fe<0)return K;const Me=Aa(V.segments,W[fe].segments);let oe=V.content||W[fe].text;return oe||(oe=Me.filter(pe=>pe.type==="text").map(pe=>pe.content).join("")),W[fe]={...W[fe],text:oe,segments:Me,committedSegments:Me},W},ee),!V.merged&&!V.segments?.length&&Se(S,K=>{const W=[...K],fe=W.findIndex(hs=>hs.id===Y);if(fe<0)return K;const Me=W[fe],oe=Me.committedSegments??[],tt=oe.filter(hs=>hs.type==="text"&&!!hs.content).map(hs=>hs.content).join("")||V.content||Me.text;return(oe.length>0||tt)&&(W[fe]={...Me,text:tt,segments:oe.length>0?oe:Me.segments}),W},ee),V.sessionId&&(ss(K=>!K||K===We||K===V.sessionId?V.sessionId:K),Ct(K=>K.some(W=>W.id===We)?K.map(W=>W.id===We?{...W,id:V.sessionId}:W):K.some(W=>W.id===V.sessionId)?K:[...K,{id:V.sessionId,agentId:te??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])),qn(te).then(K=>{if(je.current===S&&(Os(K),V.sessionId)){const W=K.find(fe=>fe.id===V.sessionId);W&&Ct(fe=>fe.some(oe=>oe.id===W.id)?fe.map(oe=>oe.id===W.id?W:oe):[W,...fe.filter(oe=>oe.id!==We)])}});const se=V.sessionId??(Ie&&Ie!==We?Ie:null);if(!Te.signal.aborted&&!V.merged&&V.segments===void 0&&O==="direct"&&te&&se)try{if((await A.sessions.streamStatus(te,se)).status==="streaming"){Se(S,W=>W.map(fe=>fe.id===Y?{...fe,isStreaming:!0,isStopped:!1,segments:(fe.segments??[]).map(Me=>Me.type==="tool"&&(Me.status==="stopped"||Me.status==="running")?{...Me,status:"running"}:Me)}:fe),se),Ue(S),jt.current===Te&&(jt.current=null),Ye(S,se),qs(te,se,S);return}}catch{}}}catch(C){const U=C?.sessionId;U&&O==="direct"&&je.current===S&&(ss(U),Ct(se=>se.map(K=>K.id===We?{...K,id:U}:K)),qn(te).then(se=>{if(je.current!==S)return;Os(se);const K=se.find(W=>W.id===U);K&&Ct(W=>W.some(Me=>Me.id===K.id)?W.map(Me=>Me.id===K.id?K:Me):[K,...W])})),Zn(C)&&er();const V=tr(C,o);V?Se(S,se=>{const K=[...se],W=K.findIndex(fe=>fe.id===Y);if(W>=0){const fe=K[W].segments??[];K[W]={...K[W],text:V,isError:!0,segments:[...fe,{type:"text",content:V}]}}return K},ee):Se(S,se=>{const K=[...se],W=K.findIndex(fe=>fe.id===Y);if(W>=0){const fe=K[W];if(!(fe.text||fe.segments&&fe.segments.length>0&&fe.segments.some(oe=>oe.type==="text"&&(oe.content||oe.thinking)||oe.type==="tool")))return se.filter(oe=>oe.id!==Y);K[W]={...fe,isStopped:!0}}return K},ee)}Se(S,C=>{const U=[...C],V=U.findIndex(se=>se.id===Y);if(V>=0){const se=(U[V].segments??[]).map(K=>K.type==="tool"&&K.status==="running"?{...K,status:"stopped"}:K);U[V]={...U[V],segments:se}}return U},ee),Te.signal.aborted&&Se(S,C=>{const U=[...C],V=U.findIndex(se=>se.id===Y);if(V>=0){const se=U[V];if(!(se.text||se.segments&&se.segments.length>0&&se.segments.some(W=>W.type==="text"&&(W.content||W.thinking)||W.type==="tool")))return C.filter(W=>W.id!==Y);U[V]={...se,isStopped:!0}}return U},ee);const we=(kt.get(S)??[]).find(C=>C.id===Y),J=Pe&&Pe!==We?Pe:null,he=we?.text||we?.segments?.some(C=>C.type==="text"&&C.content||C.type==="tool");we&&!he&&O==="direct"&&J&&!Te.signal.aborted&&await(async(U,V)=>{for(let se=0;se<U;se++){await new Promise(K=>setTimeout(K,V));try{const W=(await A.sessions.getMessages(J,2)).messages.find(fe=>fe.role==="assistant");if(W?.content){const fe=Dr(W);Se(S,Me=>{const oe=[...Me],pe=oe.findIndex(tt=>tt.id===Y);return pe>=0&&(oe[pe]={...oe[pe],text:fe.text,segments:fe.segments}),oe},ee);return}}catch{}}})(5,3e3);const ge=Ue(S);ee&&lt(S,ee),X(S),jt.current===Te||jt.current===null?(jt.current=null,Ot.delete(ee??S),je.current===S&&(ot(ge>0),ge===0&&Ut([]))):Ot.delete(ee??S)}};la.current=vn;const[Hi,ha]=r.useState(null),[Kn,Cr]=r.useState(null),Vi=r.useMemo(()=>{for(let t=qe.length-1;t>=0;t--)if(qe[t]?.sender==="agent"&&!qe[t]?.isActivityLog)return qe[t].id;return null},[qe]),qi=r.useCallback(t=>{const d=t.segments?t.segments.filter(c=>c.type==="text").map(c=>c.content).join(`
38
+ `):t.text;navigator.clipboard.writeText(d),ha(t.id),setTimeout(()=>ha(c=>c===t.id?null:c),2e3)},[]),Tr=r.useCallback((t,d,c)=>{const x=je.current,$=kt.get(x)??qe,B=$.findIndex(F=>F.id===t.id);if(B<0)return;const S=d&&B>0&&$[B-1]?.id===d.id;Se(x,F=>{const re=F.findIndex(q=>q.id===(S?d.id:t.id));return re>=0?F.slice(0,re):F}),vn(c,{isRetry:!0})},[qe,Se]),Ui=r.useCallback(t=>{const d=je.current,c=kt.get(d)??qe,x=c.findIndex(F=>F.id===t.id);if(x<0)return;let $=null;for(let F=x-1;F>=0;F--)if(c[F]?.sender==="user"){$=c[F];break}const B=$?.text??"";if(!B)return;if(x<c.length-1){const F=c.length-1-x;Cr({retryMsg:t,userMsg:$,retryText:B,followCount:F});return}Tr(t,$,B)},[qe,Tr]),Ki=r.useCallback(t=>{const d=je.current;(kt.get(d)??qe).findIndex($=>$.id===t.id)<0||(Se(d,$=>{const B=[...$],S=B.findIndex(q=>q.id===t.id);if(S<0)return $;const F=B[S],re=[...F.segments??[]];for(;re.length>0;){const q=re[re.length-1];if(q.type==="tool"&&(q.status==="stopped"||q.status==="running"))re.pop();else if(q.type==="text"&&!q.content)re.pop();else break}return B[S]={...F,segments:re,isStopped:!1,isError:!1},B}),vn("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0}))},[qe,Se]),Gi=r.useCallback(t=>{const d=t.sender==="user"?i?.name??o("page.fallbackYou"):t.agentName??o("page.fallbackAgent");if(Ke({id:t.id,sender:d,text:t.text}),O==="channel"&&t.sender==="agent"&&t.agentName){const c=`@${t.agentName} `;St(x=>x.startsWith(c)?x:c+x)}ts.current?.focus()},[i?.name,O,o]),Gn=async t=>{const d=Pe;ss(t.id),Ms(!1),es(!1),Gt.current=null,Xt.current=!0,Es(!1),_s.current=0,Ws(0);const c=je.current,x=nt(c),$=!!x&&(x.has(t.id)||x.has(We)),B=ke(c)&&$;ot(B),Ut(B?Ot.get(t.id)??[]:[]),_t.set(c,t.id),te&&fr(te,t.id),d&&d!==We&&Ft(c,d),et(c,t.id),Ct(F=>F.some(re=>re.id===t.id)?F:[...F,t]),te&&ji(te,t.id),await ga(t.id,c);const S=t.metadata?.modelOverride;Ln(S?.provider&&S?.model?{provider:S.provider,model:S.model}:null),te&&!B&&qs(te,t.id,c)},Yi=t=>{if(Ct(d=>d.filter(c=>c.id!==t)),te&&t!==We&&yi(te,t),Pe===t){const d=Rn.filter(c=>c.id!==t);d.length>0?Gn(d[d.length-1]):Mr()}},pa=r.useCallback(async t=>{if(t.length<2){fs([]);return}sa(!0);try{const d=O==="channel"?"channel":O==="direct"?"direct":"all",c=O==="channel"?Ne:void 0,{results:x}=await A.messages.search(t,{scope:d,channel:c,limit:30});fs(x)}catch{fs([])}sa(!1)},[O,Ne]),Xi=r.useCallback(t=>{Fs(t),jr.current&&clearTimeout(jr.current),jr.current=setTimeout(()=>pa(t),300)},[pa]),Qi=r.useCallback(t=>{mn(!1),Fs(""),fs([]),t.source==="channel"&&t.channel?(_e("channel"),pt(t.channel)):t.source==="direct"&&t.agentId&&(_e("direct"),st(t.agentId)),setTimeout(()=>{const d=document.getElementById(`msg-${t.id}`);d&&(d.scrollIntoView({behavior:"smooth",block:"center"}),d.classList.add("bg-brand-500/10"),setTimeout(()=>d.classList.remove("bg-brand-500/10"),2e3))},500)},[]),Mr=()=>{ss(We);const t=je.current;ue(t),vt([]),es(!1),Gt.current=null,Ms(!1),Ct(d=>{const c=d.filter(x=>x.id!==We);return[{id:We,agentId:te??"",userId:null,title:o("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...c]})},Ji=t=>{St(t);const d=ts.current?.selectionStart??t.length,c=t.slice(0,d),x=c.lastIndexOf("@");if(x>=0){const $=x===0?"":c[x-1];if(x===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test($)){const S=c.slice(x+1);if(!S.includes(" ")&&!S.includes(`
39
+ `)){Ai(),xn(!0),Pi(S.toLowerCase()),Bs(0);return}}}xn(!1)},Yn=(t,d,c)=>{const x=ts.current?.selectionStart??Xe.length,B=Xe.slice(0,x).lastIndexOf("@"),S=Xe.slice(x),F=d&&c?`@[${t}](${d}:${c})`:t.includes(" ")?`@[${t}]`:`@${t}`,re=Xe.slice(0,B)+F+" "+S;St(re),xn(!1),Bs(0);const q=B+F.length+1;requestAnimationFrame(()=>{ts.current?.setSelectionRange(q,q)})},Zi=10*1024*1024,ba=5,eo=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),Us=r.useCallback(t=>t.type.startsWith("image/")||eo.has(t.type),[]),Pr=t=>t.dataUrl.startsWith("data:image/"),to=(t,d)=>{if(Pr({dataUrl:d}))return null;const c=t.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[c]??"📁"},yn=r.useCallback(t=>{const d=Array.from(t).filter(Us);if(d.length!==0)for(const c of d){if(c.size>Zi)continue;const x=new FileReader;x.onload=()=>{const $=x.result;ur(B=>B.length>=ba||B.some(S=>S.dataUrl===$)?B:[...B,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:$,name:c.name}])},x.readAsDataURL(c)}},[Us]),so=r.useCallback(t=>{ur(d=>d.filter(c=>c.id!==t))},[]),no=r.useCallback(t=>{const d=t.clipboardData?.files;if(d&&d.length>0){const c=Array.from(d).filter(Us);c.length>0&&(t.preventDefault(),yn(c))}},[yn,Us]),ro=r.useCallback(t=>{t.preventDefault();const d=t.dataTransfer?.files;d&&d.length>0&&yn(Array.from(d).filter(Us))},[yn,Us]),ao=r.useCallback(t=>{t.preventDefault()},[]),Ge=f.find(t=>t.id===te),Er=i?.name??o("page.fallbackYou"),va=wt[wt.length-1],io=yt&&va?.sender==="agent",oo=lr&&va?.sender==="agent",ya=r.useMemo(()=>{if(O!=="channel")return null;if(Ne.startsWith("group:custom:")){const d=ut.find(c=>c.channelKey===Ne);return d?.members?new Set(d.members.filter(c=>c.type==="agent").map(c=>c.id)):null}if(!Qe)return null;const t=Yt.find(d=>d.id===Qe);return t?new Set(t.members.filter(d=>d.type==="agent").map(d=>d.id)):null},[O,Ne,Qe,Yt,ut]),ja=f.filter(t=>ya?ya.has(t.id):!0).filter(t=>t.name.toLowerCase().includes(ia)),wa=Ei.filter(t=>t.name.toLowerCase().includes(ia)),lo={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},As=r.useMemo(()=>[...ja.map(t=>({kind:"agent",agent:t})),...wa.map(t=>({kind:"entity",entity:t}))],[ja,wa]),_r=k.find(t=>t.id===Je),Ar=Je===i?.id||!Je,Lt=ut.find(t=>t.channelKey===Ne);r.useEffect(()=>{if(s||!Ne.startsWith("group:custom:"))return;const t=ut.find(d=>d.channelKey===Ne);!t||t.members||A.groupChats.getById(t.id).then(d=>{d.chat.members&&dn(c=>c.map(x=>x.id===t.id?{...x,members:d.chat.members}:x))}).catch(()=>{})},[s,Ne,ut]);const Ir=r.useCallback(async()=>{if(s||O!=="direct"||!te){hr([]);return}try{Po("/approvals");const{approvals:t}=await A.approvals.list("pending");hr(t.filter(d=>d.status==="pending"&&Array.isArray(d.questions)&&d.questions.length>0&&(d.details?.agentId??d.agentId)===te))}catch{}},[s,O,te]);r.useEffect(()=>{Ir();let t=null;const d=()=>{t||(t=setTimeout(()=>{t=null,Ir()},400))},c=Fe.on("approval:requested",d),x=Fe.on("notification",d),$=()=>d();return window.addEventListener("markus:notifications-changed",$),()=>{t&&clearTimeout(t),c(),x(),window.removeEventListener("markus:notifications-changed",$)}},[Ir]);const co=r.useCallback(async(t,d)=>{Jr(t);try{await A.approvals.respond(t,d.approved,i?.id,d.comment,d.selectedOption,d.answers),hr(c=>c.filter(x=>x.id!==t)),pr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}Jr(null)},[i?.id]),Na=O==="channel"?Lt?.name??Ne:O==="direct"?Ge?.name??o("page.selectAgent"):O==="dm"?Ar?o("chat.myNotes"):_r?.name??o("page.directMessage"):o("page.chatTitle"),uo=r.useMemo(()=>Math.floor(Math.random()*5),[te,Pe]),ka=te?o(`page.placeholder.directOptions.${uo}`):"",jn=O==="direct"&&!!Ge&&Ge.status==="offline",mo=O==="channel"?Lt?o("page.placeholder.channel",{name:Lt.name}):o("page.placeholder.channelWithMention",{name:Ne}):O==="dm"?Ar?o("page.placeholder.dmSelf"):o("page.placeholder.dmOther",{name:_r?.name??""}):o(jn?"page.placeholder.agentOffline":te?"page.placeholder.direct":"page.placeholder.noAgent"),xo=b&&h==="chat",wn=L==="chat"&&wt.length===0&&!yt&&!Yr;return e.jsxs("div",{ref:ae,className:"flex-1 overflow-hidden flex relative",children:[!w&&e.jsx(il,{authUser:i,agents:f,teams:Yt,humans:k,tasks:On,externalAgents:Si,groupChats:ut,chatMode:O,selectedAgent:te,activeChannel:Ne,activeDmUserId:Je,previewMode:s,onSelectAgent:t=>{_e("direct"),st(t),G("chat"),ct(!1),b&&M()},onSelectChannel:t=>{_e("channel"),pt(t),G("chat"),ct(!1),b&&M()},onSelectDm:t=>{_e("dm"),ws(t),G("chat"),ct(!1),b&&M()},onSelectTeam:t=>{const d=ut.find(x=>x.type==="team"&&x.teamId===t),c=d?.channelKey??`group:${t}`;b?P(t):(_e("channel"),pt(c),G("chat"),ct(!1),!Wt&&!Be&&xt(!0),d||(zs(),Tt()))},selectedTeamId:Qe??(O==="direct"&&Ge?.teamId?Ge.teamId:null),onRefreshTeams:Tt,onRefreshAgents:It,onRefreshHumans:bn,onRefreshGroupChats:zs,onViewProfile:ft,onManageGroupMembers:t=>{_e("channel"),pt(t),G("chat"),ct(!0),b&&M()},unreadByAgent:Wn,unreadByChannel:zn,width:b?void 0:Ee.width,onResizeStart:b?void 0:Ee.onResizeStart,hidden:b&&h!=="roster"||!b&&Le,onCollapse:()=>De(!0),initialLoading:E}),b&&h==="team"&&T&&(()=>{const t=Yt.find(x=>x.id===T);if(!t)return null;const d=f.filter(x=>x.teamId===T),c=ut.find(x=>x.type==="team"&&x.teamId===T);return e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[e.jsx("button",{onClick:()=>{window.location.hash=at.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:t.name}),e.jsx("p",{className:"text-[10px] text-fg-tertiary",children:o("chat.members_other",{count:t.members?.length||d.length})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[c&&(()=>{const x=zn[c.channelKey]??0;return e.jsxs("button",{onClick:()=>{_e("channel"),pt(c.channelKey),G("chat"),M()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:c.name}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("chat.groupChat")})]}),x>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:x}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:o("chat.agents")}),d.map(x=>{const $=Wn.get(x.id)??0,B=x.status==="offline";return e.jsxs("button",{onClick:()=>{_e("direct"),st(x.id),G("chat"),M()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${B?"opacity-50":""}`,children:[e.jsx(mt,{name:x.name||"Agent",avatarUrl:x.avatarUrl,size:36}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"text-sm font-medium text-fg-primary truncate flex items-center gap-1.5",children:[x.name,B&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:o("common:status.offline")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:x.role||x.status})]}),$>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:$}):e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${x.status==="idle"?"bg-green-500":x.status==="working"?"bg-blue-500":"bg-gray-400"}`})]},x.id)})]})]})]})})(),!w&&Wt&&!Be&&!b&&!Le&&(()=>{const t=Qe??(O==="direct"?Ge?.teamId:void 0);if(!t)return null;const d=Yt.find(x=>x.id===t);if(!d)return null;const c=ut.find(x=>x.type==="team"&&x.teamId===t);return e.jsx(Fa,{team:d,agents:f,humans:k,authUser:i,groupChat:c,chatMode:O,selectedAgent:te,activeChannel:Ne,teams:Yt,onSelectAgent:x=>{_e("direct"),st(x),G("chat"),ct(!1)},onSelectChannel:x=>{_e("channel"),pt(x),G("chat"),ct(!1)},onSelectDm:x=>{_e("dm"),ws(x),G("chat"),ct(!1)},onBack:()=>xt(!1),onViewProfile:ft,onRefreshAgents:It,onRefreshTeams:Tt,unreadByAgent:Wn,width:it.width,onResizeStart:it.onResizeStart})})(),!w&&Oe&&!b&&!Le&&(()=>{const t=Qe??(O==="direct"?Ge?.teamId:void 0);if(!t)return null;const d=Yt.find(x=>x.id===t);if(!d)return null;const c=ut.find(x=>x.type==="team"&&x.teamId===t);return e.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:Ee.width+6},children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>gt(!1)}),e.jsx("div",{className:"relative h-full",style:{width:it.width+8},children:e.jsx(Fa,{team:d,agents:f,humans:k,authUser:i,groupChat:c,chatMode:O,selectedAgent:te,activeChannel:Ne,teams:Yt,onSelectAgent:x=>{_e("direct"),st(x),G("chat"),ct(!1),gt(!1)},onSelectChannel:x=>{_e("channel"),pt(x),G("chat"),ct(!1),gt(!1)},onSelectDm:x=>{_e("dm"),ws(x),G("chat"),ct(!1),gt(!1)},onBack:()=>gt(!1),onViewProfile:x=>{ft(x),gt(!1)},onRefreshAgents:It,onRefreshTeams:Tt,unreadByAgent:Wn,width:it.width})})]})})(),!w&&(!b||xo)&&e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${b||ne?"min-w-0":"min-w-[400px]"}`,children:[e.jsxs("div",{className:"shrink-0 relative pb-2",children:[b?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[e.jsx("button",{onClick:()=>{window.location.hash=D.current},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("span",{className:"font-semibold text-sm truncate min-w-0 flex-1",children:Na}),O==="direct"&&Ge&&e.jsx(li,{agent:Ge,tasks:On,onViewProfile:ft,streamActive:Ur})]}),e.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[e.jsx("button",{onClick:()=>{as(L)?history.back():G("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${L==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o("page.chatTitle")}),e.jsx("button",{onClick:()=>{as(L)||ms()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${as(L)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o(O==="channel"?"page.teamTab":"page.profileTab")}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:()=>{mn(!Ps),Ps||(Fs(""),fs([]))},className:`p-1 rounded-md transition-colors shrink-0 ${Ps?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),O==="channel"&&Lt?.type==="custom"&&e.jsxs("button",{onClick:()=>ct(!un),className:`text-[11px] px-2 py-1 rounded-md font-medium shrink-0 flex items-center gap-1 ${un?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Lt.members?.length??Lt.memberCount??0]}),O==="direct"&&!as(L)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Mr,className:"text-[11px] text-brand-500 px-2 py-1 rounded-md bg-brand-500/10 font-medium shrink-0",children:o("page.newChatPlus")}),e.jsx("button",{ref:$n,onClick:()=>Ms(!Ts),className:`p-1 rounded-md transition-colors shrink-0 ${Ts?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}):(()=>{const t=Qe?Yt.find(q=>q.id===Qe):void 0,d=O==="direct"&&te?Ll:O==="channel"&&Qe?Dl:["chat"],c=async()=>{const q=Pn.trim();if(!q){Rt(!1);return}try{O==="direct"&&te?(await A.agents.updateConfig(te,{name:q}),It()):O==="channel"&&Qe&&(await A.teams.update(Qe,{name:q}),Tt())}catch{}Rt(!1)},x=async()=>{try{O==="direct"&&te?(await A.agents.updateConfig(te,{roleDescription:qt}),It()):O==="channel"&&Qe&&(await A.teams.update(Qe,{description:qt}),Tt())}catch{}nn(!1)},$=O==="direct"?Ge?.name:O==="channel"?t?.name??Lt?.name:_r?.name??"",B=O==="direct"?Ge?.role||"":O==="channel"&&t?.description||"",S=O==="direct"?Ge?.avatarUrl:void 0,F=$||"U",re=O==="direct"&&te||O==="channel"&&Qe;return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center px-4 h-14 gap-2.5",children:[Le&&!b&&e.jsx("button",{onClick:()=>De(!1),className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",title:o("page.toggleSidebar"),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),(!Wt||Be)&&(O==="channel"&&Qe||O==="direct"&&Ge?.teamId)&&e.jsx("button",{onClick:Xs,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${Oe?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),re&&(O==="channel"&&Qe?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):e.jsx(mt,{name:F,avatarUrl:S,size:36,className:"rounded-xl shrink-0"})),re?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Mt?e.jsx("input",{ref:Rs,value:Pn,onChange:q=>sn(q.target.value),onBlur:c,onKeyDown:q=>{q.key==="Enter"&&c(),q.key==="Escape"&&Rt(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):e.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{sn($??""),Rt(!0)},title:"Click to edit name",children:$}),O==="direct"&&Ge&&e.jsx(li,{agent:Ge,tasks:On,onViewProfile:ft,streamActive:Ur})]}),(O==="direct"||O==="channel"&&Qe)&&(Ds?e.jsx("input",{ref:Pt,value:qt,onChange:q=>ys(q.target.value),onBlur:x,onKeyDown:q=>{q.key==="Enter"&&x(),q.key==="Escape"&&nn(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add description...",autoFocus:!0}):e.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{ys(B),nn(!0)},title:"Click to edit description",children:B||"No description"}))]}):e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:Na}),O==="dm"&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:Ar?o("page.privateNotepad"):""})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>{mn(!Ps),Ps||(Fs(""),fs([]))},className:`p-1.5 rounded-md transition-colors ${Ps?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.searchMessages"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),O==="channel"&&Lt?.type==="custom"&&e.jsxs("button",{onClick:()=>ct(!un),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${un?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Lt.members?.length??Lt.memberCount??0]}),O==="direct"&&Ge&&L==="chat"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:Mr,className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:o("page.newChatButton")}),e.jsx("button",{ref:$n,onClick:()=>Ms(!Ts),className:`p-1.5 rounded-md transition-colors ${Ts?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),!b&&be&&e.jsx("button",{onClick:()=>be.toggleRightPanel(),className:`p-1.5 rounded-md transition-colors ${ne?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.rightPanelToggle",{defaultValue:"Toggle side panel"}),children:e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),e.jsx("path",{d:"M15 4v16"})]})})]})]}),d.length>1&&e.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:d.map(q=>e.jsxs("button",{onClick:()=>G(q),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${L===q?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{children:$l(q)}),Rl(q,o)]},q))})]})})(),Ps&&e.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/50 px-4 py-2 space-y-2 animate-in slide-in-from-top-2 duration-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),e.jsx("input",{autoFocus:!0,value:ea,onChange:t=>Xi(t.target.value),onKeyDown:t=>{t.key==="Escape"&&(mn(!1),Fs(""),fs([]))},placeholder:o("page.searchPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),e.jsx("button",{onClick:()=>{mn(!1),Fs(""),fs([])},className:"text-fg-tertiary hover:text-fg-secondary text-xs px-1",children:"✕"})]}),ta&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary py-1",children:[e.jsxs("svg",{className:"animate-spin h-3 w-3",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),o("page.searching")]}),!ta&&ea.length>=2&&yr.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:o("page.noSearchResults")}),yr.length>0&&e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:yr.map(t=>e.jsxs("button",{onClick:()=>Qi(t),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-surface-elevated transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-tertiary mb-0.5",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${t.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:t.source==="channel"?"#":"1:1"}),t.senderName&&e.jsx("span",{children:t.senderName}),e.jsx("span",{children:new Date(t.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),e.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 group-hover:text-fg-primary transition-colors",children:t.text.length>200?t.text.slice(0,200)+"…":t.text})]},t.id))})]}),O==="direct"&&te&&L==="chat"&&Rn.length>1&&e.jsx("div",{className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:Rn.map(t=>e.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${t.id===Pe?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(t.id===We){ss(We);const d=je.current;ue(d),vt([])}else Gn(t)},children:[t.isMain&&e.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),e.jsx("span",{className:"truncate",children:t.id===We?o("page.newChat"):t.isMain?o("page.sessionMain"):t.title||o("page.sessionConversation")}),!t.isMain&&e.jsx("button",{onClick:d=>{d.stopPropagation(),Yi(t.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},t.id))}),O==="channel"&&Lt?.type==="custom"&&un&&(()=>{const t=Lt,d=t.members??[],c=[];for(const x of f)d.some($=>$.id===x.id)||c.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of k)d.some($=>$.id===x.id)||c.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||""});return e.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",d.length,")"]}),e.jsx("button",{onClick:()=>ct(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.map(x=>e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${x.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[e.jsx(mt,{name:x.name,size:16,bgClass:x.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),x.name,x.id!==i?.id&&e.jsx("button",{onClick:async()=>{try{await A.groupChats.removeMember(t.id,x.id),dn($=>$.map(B=>B.id===t.id?{...B,members:(B.members??[]).filter(S=>S.id!==x.id),memberCount:(B.memberCount??1)-1}:B))}catch{}},className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},x.id))}),c.length>0&&e.jsx("div",{className:"mt-1",children:e.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:async x=>{const $=x.target.value;if(!$)return;const B=c.find(S=>S.id===$);if(B)try{await A.groupChats.addMember(t.id,B.id,B.type,B.name),dn(S=>S.map(F=>F.id===t.id?{...F,members:[...F.members??[],{id:B.id,name:B.name,type:B.type}],memberCount:(F.memberCount??0)+1}:F))}catch{}},children:[e.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),c.map(x=>e.jsxs("option",{value:x.id,children:["[",x.type==="agent"?"Agent":"Human","] ",x.name]},x.id))]})})]})})(),O==="direct"&&te&&Ts&&e.jsxs("div",{ref:br,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:o("page.historyTitle")}),e.jsx("button",{onClick:()=>Ms(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[Xr.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:o("page.noConversationsYet")}),(()=>{const t=new Date,d=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),c=d-864e5,x=d-7*864e5,$=[],B=[],S=[],F=[],re=[];for(const q of Xr){const Y=new Date(q.lastMessageAt).getTime();Y>=d?B.push(q):Y>=c?S.push(q):Y>=x?F.push(q):re.push(q)}return B.length>0&&$.push({label:o("page.dateToday"),items:B}),S.length>0&&$.push({label:o("page.dateYesterday"),items:S}),F.length>0&&$.push({label:o("page.datePrevious7Days"),items:F}),re.length>0&&$.push({label:o("page.dateOlder"),items:re}),$.map(q=>e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:q.label}),q.items.map(Y=>e.jsxs("button",{onClick:()=>{Gn(Y)},className:`w-full text-left px-3 py-2.5 rounded-lg text-xs mb-0.5 transition-colors ${Y.id===Pe?"bg-brand-600/20 text-brand-500":"text-fg-secondary hover:bg-surface-elevated"}`,children:[e.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[Y.isMain&&e.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),Y.isMain?o("page.sessionMain"):Y.title||o("page.sessionConversation")]}),e.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(Y.lastMessageAt).toLocaleString()})]},Y.id))]},q.label))})()]})]})]}),b&&L==="profile"&&O==="direct"&&te&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(za,{agentId:te,onBack:()=>G("chat"),inline:!0,defaultTab:Mn,highlightMailboxId:tn,onSwipeBack:()=>{as(me.current)?history.back():G("chat")},authUser:i})}),b&&L==="profile"&&O==="channel"&&Qe&&e.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:b?Et.onTouchStart:void 0,onTouchEnd:b?Et.onTouchEnd:void 0,children:e.jsx(ai,{teamId:Qe,onBack:()=>G("chat"),inline:!0,onSelectAgent:t=>{_e("direct"),st(t),G("chat")}})}),!b&&as(L)&&O==="direct"&&te&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(za,{agentId:te,onBack:()=>G("chat"),inline:!0,headless:!0,activeTab:L,highlightMailboxId:tn,authUser:i})}),!b&&as(L)&&O==="channel"&&Qe&&e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:e.jsx(ai,{teamId:Qe,onBack:()=>G("chat"),inline:!0,headless:!0,activeTab:L,onSelectAgent:t=>{_e("direct"),st(t),G("chat")}})}),e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${wn?"justify-center":""} ${L!=="chat"?"hidden":""}`,children:[Yr&&wt.length===0&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("svg",{className:"animate-spin h-5 w-5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}),dr&&e.jsxs("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center items-center gap-2 py-2 bg-gradient-to-b from-surface-primary/90 to-transparent pointer-events-none",children:[e.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.loadingEarlierMessages")})]}),e.jsxs("div",{ref:fn,className:`${wn?"hidden":"flex-1"} overflow-y-auto ${b?"p-2.5":`p-5 ${Z}`}`,onScroll:Bi,onTouchStart:b?Et.onTouchStart:void 0,onTouchEnd:b?Et.onTouchEnd:void 0,children:[wt.length>0&&e.jsx("div",{style:{height:ns.getTotalSize(),width:"100%",position:"relative"},children:ns.getVirtualItems().map(t=>{const d=t.index,c=wt[d],x=d>0?wt[d-1]:null,$=Ia(c.rawCreatedAt),B=x?Ia(x.rawCreatedAt):"",S=$&&$!==B,F=d===wt.length-1,q=io&&F&&yt||!!c.isStreaming,Y=oo&&F||q,ee=O==="channel"||!q||c.isStopped;return e.jsx("div",{"data-index":d,ref:ns.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${t.start}px)`},children:e.jsxs("div",{className:"pb-3",children:[S&&e.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[e.jsx("div",{className:"flex-1 h-px bg-border-default"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:Bo(c.rawCreatedAt,u)}),e.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),e.jsxs("div",{id:`msg-${c.id}`,className:"group/msg flex gap-3 transition-colors rounded-lg",children:[O==="channel"?e.jsx("div",{className:"shrink-0 cursor-pointer",onClick:ce=>{if(c.sender==="agent"&&c.agentId){const le=ce.currentTarget.getBoundingClientRect();Jt({agentId:c.agentId,top:le.top,left:le.right+8})}},children:e.jsx(mt,{name:c.sender==="user"?Er:c.agentName??o("page.fallbackAgent"),avatarUrl:c.sender==="user"?i?.avatarUrl:f.find(ce=>ce.id===c.agentId)?.avatarUrl,size:32,bgClass:c.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:c.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):e.jsx("div",{className:"shrink-0",children:e.jsx(mt,{name:c.sender==="user"?Er:c.agentName??(O==="direct"?Ge?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),avatarUrl:c.sender==="user"?i?.avatarUrl:f.find(ce=>ce.id===(c.agentId??(O==="direct"?Ge?.id:void 0)))?.avatarUrl,size:32,bgClass:c.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:c.sender==="user"?Er:O==="channel"?c.agentName??o("page.fallbackAgent"):e.jsx(Eo,{name:c.agentName??(O==="direct"?Ge?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),agentId:c.agentId??(O==="direct"?Ge?.id:void 0),agents:f,onViewProfile:ft})}),e.jsx("span",{className:"text-xs text-fg-tertiary",title:c.rawCreatedAt?new Date(c.rawCreatedAt).toLocaleString():"",children:zo(c.time,c.rawCreatedAt,u)})]}),c.replyToId&&c.replyToSender&&e.jsxs("button",{onClick:()=>{const ce=document.getElementById(`msg-${c.replyToId}`);ce&&(ce.scrollIntoView({behavior:"smooth",block:"center"}),ce.classList.add("bg-brand-500/10"),setTimeout(()=>ce.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[e.jsx("span",{className:"font-medium text-brand-500",children:c.replyToSender}),e.jsx("span",{className:"truncate max-w-[250px]",children:c.replyToText??"..."})]}),e.jsxs("div",{className:`mt-0.5 ${c.sender==="agent"?"py-1":"bg-surface-secondary rounded-2xl px-3.5 py-2.5 w-fit max-w-full"} ${c.isError||c.sender==="agent"&&c.text.startsWith("⚠")?"border-b-2 border-red-500/60":""} ${Y&&c.sender==="agent"?"streaming-bubble":""}`,children:[c.sender==="user"?e.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[c.images&&c.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:c.images.map((ce,le)=>e.jsx("img",{src:ce,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(ce,"_blank")},le))}),O==="channel"?Pa(c.text,f,(ce,le)=>{const de=le.currentTarget.getBoundingClientRect();Jt({agentId:ce.id,top:de.bottom,left:de.left})}):c.text&&e.jsx("span",{className:"leading-relaxed",children:Pa(c.text,f,(ce,le)=>{const de=le.currentTarget.getBoundingClientRect();Jt({agentId:ce.id,top:de.bottom,left:de.left})})})]}):c.sender==="agent"&&O==="channel"&&!(c.segments&&c.segments.length>0)?e.jsx(Ma,{resetKeys:[c.text],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:c.text}),children:e.jsx(sr,{content:c.text,className:"text-sm text-fg-secondary",onMentionClick:$t,knownNames:an})}):e.jsx(Ma,{resetKeys:[c.id,c.text,c.segments?.length,q],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:c.text}),children:e.jsx(_o,{msg:c,isStreaming:q,liveActivities:q?ir:[],onMentionClick:$t,knownNames:an})}),c.isNotification&&e.jsx(Ao,{priority:c.notifyPriority})]}),ee&&!s&&e.jsx("div",{className:`transition-opacity ${c.isStopped||b?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:e.jsx(Io,{msg:c,onCopy:qi,onRetry:Ui,onResume:Ki,onReply:Gi,isCopied:Hi===c.id,isLastAgentMsg:c.id===Vi})})]})]})]})},c.id)})}),O==="channel"&&qr.length>0&&e.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:qr.map(t=>e.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors group/think",onClick:()=>{_e("direct"),st(t.id),G("chat")},children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(mt,{name:t.name,avatarUrl:t.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-600"}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-secondary truncate",children:t.name}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.agentThinking")})]}),e.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary opacity-0 group-hover/think:opacity-100 transition-opacity",children:"→"})]},t.id))}),e.jsx("div",{ref:Ii})]}),Oi&&L==="chat"&&e.jsx("div",{className:`absolute ${b?"bottom-4":"bottom-28"} inset-x-0 z-10 pointer-events-none ${b?"px-3":`px-5 ${Z}`}`,children:e.jsx("div",{className:`${b?"":"max-w-3xl mx-auto"} flex justify-center`,children:e.jsxs("button",{onClick:()=>{Xt.current=!0,Vs("smooth"),Es(!1),_s.current=0,Ws(0)},className:"pointer-events-auto flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/95 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary",children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})}),da>0?o("page.newMessages",{count:da}):o("page.scrollToBottom")]})})}),bs&&(()=>{const t=f.find(d=>d.id===bs.agentId);return t?e.jsx(Lo,{agent:t,anchorRect:{top:bs.top,left:bs.left},onClose:()=>Jt(null),onViewProfile:ft}):null})(),wn&&ka&&e.jsx("div",{className:"text-center mb-4",children:e.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:ka})}),O==="direct"&&Qr.length>0&&e.jsx("div",{className:`${b?"px-3":"px-5"} pb-1 shrink-0 ${wn?"":Z}`,children:e.jsx("div",{className:`${b?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:Qr.map(t=>e.jsxs("button",{onClick:()=>pr(t),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[e.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"}),e.jsx("path",{d:"M12 8v4"}),e.jsx("path",{d:"M12 16h.01"})]})}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-fg-primary truncate",children:t.title}),e.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:o("page.userInputPrompt",{count:t.questions?.length??1,defaultValue:`${t.questions?.length??1} question(s) awaiting your response`})})]}),e.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[o("page.userInputRespond",{defaultValue:"Respond"}),e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},t.id))})}),cn&&e.jsx(Do,{approval:cn,submitting:Ni===cn.id,readOnly:cn.status!=="pending",onClose:()=>pr(null),onSubmit:t=>co(cn.id,t)}),Kn&&e.jsx(Sn,{variant:"primary",title:o("page.retry",{defaultValue:"Retry"}),message:Kn.followCount===1?o("page.retryConfirmSingular"):o("page.retryConfirmPlural",{count:Kn.followCount}),confirmLabel:o("common:confirm"),onConfirm:()=>{const t=Kn;Cr(null),Tr(t.retryMsg,t.userMsg,t.retryText)},onCancel:()=>Cr(null)}),e.jsx("div",{className:`${b?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${wn?"":Z}`,onDrop:ro,onDragOver:ao,children:e.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${b?"rounded-2xl p-3":"rounded-2xl p-3 max-w-3xl mx-auto"}`,children:[aa&&As.length>0&&e.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:o("page.mentionAgent")}),As.map((t,d)=>t.kind==="agent"?e.jsxs("button",{ref:c=>{d===gn&&c&&c.scrollIntoView({block:"nearest"})},onClick:()=>Yn(t.agent.name),onMouseEnter:()=>Bs(d),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${d===gn?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx(mt,{name:t.agent.name,avatarUrl:t.agent.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.agent.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.agent.role})]},`agt-${t.agent.id}`):e.jsxs("button",{ref:c=>{d===gn&&c&&c.scrollIntoView({block:"nearest"})},onClick:()=>Yn(t.entity.name,t.entity.entityType,t.entity.id),onMouseEnter:()=>Bs(d),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${d===gn?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("span",{className:"w-6 h-6 flex items-center justify-center text-sm shrink-0",children:lo[t.entity.entityType]??"📄"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.entity.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.entity.role})]},`${t.entity.entityType}-${t.entity.id}`))]}),Kt.length>0&&e.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:Kt.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 max-w-[240px] pl-2 pr-1 py-1 rounded-lg bg-brand-500/10 text-brand-500 text-xs border border-brand-500/20",title:t.content,children:[e.jsx("span",{className:"truncate",children:t.label}),e.jsx("button",{onClick:()=>or(d=>d.filter(c=>c.id!==t.id)),className:"w-4 h-4 flex items-center justify-center rounded hover:bg-brand-500/20 shrink-0","aria-label":o("common:remove",{defaultValue:"Remove"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},t.id))}),Bt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Bt.map(t=>e.jsxs("div",{className:"relative group/img shrink-0",children:[Pr(t)?e.jsx("img",{src:t.dataUrl,alt:t.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):e.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:t.name,children:[e.jsx("span",{className:"text-xl leading-none",children:to(t.name,t.dataUrl)}),e.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:t.name.split(".").pop()?.toUpperCase()})]}),e.jsx("button",{onClick:()=>so(t.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},t.id)),Bt.length<ba&&e.jsx("button",{onClick:()=>mr.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:o("page.addMoreFiles"),children:e.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),Bt.length>0&&Bt.some(t=>Pr(t))&&Ge&&Ge.modelSupportsVision===!1&&e.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[e.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),o("page.visionWarning")]}),e.jsx("input",{ref:mr,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:t=>{t.target.files&&yn(t.target.files),t.target.value=""}}),xs&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[e.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[e.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:xs.sender}),e.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:xs.text})]}),e.jsx("button",{onClick:()=>Ke(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("button",{onClick:()=>mr.current?.click(),disabled:O==="direct"&&(!te||jn),className:"px-2.5 py-2.5 text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated",title:o("page.attachFilesTitle"),children:e.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsxs("div",{className:"flex-1 relative min-w-0",children:[e.jsx("textarea",{ref:ts,value:Xe,onChange:t=>{Ji(t.target.value),xr()},onKeyDown:t=>{if(aa&&As.length>0){const d=t.key==="ArrowUp"||t.ctrlKey&&t.key==="p",c=t.key==="ArrowDown"||t.ctrlKey&&t.key==="n",x=t.key==="Enter"||t.key==="Tab",$=t.key==="Escape";if(d){t.preventDefault(),Bs(B=>(B-1+As.length)%As.length);return}if(c){t.preventDefault(),Bs(B=>(B+1)%As.length);return}if(x){t.preventDefault();const B=As[gn];B&&(B.kind==="agent"?Yn(B.agent.name):Yn(B.entity.name,B.entity.entityType,B.entity.id));return}if($){t.preventDefault(),xn(!1);return}}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),vn())},onPaste:no,placeholder:mo,disabled:O==="direct"&&(!te||jn),rows:2,className:"w-full px-4 py-3 pb-8 bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-hidden leading-relaxed placeholder:text-fg-secondary",style:{minHeight:"52px",maxHeight:"120px"}}),O==="direct"&&e.jsx("div",{className:"absolute right-1.5 bottom-1",children:e.jsx(Al,{value:In,disabled:!te||jn,onSelect:(t,d)=>{Ln(t);const c=Pe&&Pe!==We?Pe:null;Il(c,t,d).catch(()=>{}),c&&Os(x=>x.map($=>$.id===c?{...$,metadata:{...$.metadata??{},modelOverride:t}}:$))}})})]}),yt&&O!=="dm"&&e.jsx("button",{onClick:Wi,className:"px-3 py-2.5 bg-red-600 hover:bg-red-500 text-white text-sm rounded-xl transition-colors flex items-center gap-1.5",title:o("page.stopAgent"),children:e.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}),e.jsx("button",{onClick:()=>{vn()},disabled:O==="direct"&&(!te||jn)||!Xe.trim()&&Bt.length===0,className:"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:o("common:send")})]})]})})]})]}),!b&&ne&&Re&&e.jsx(ul,{payload:ne,onClose:Re,width:w?zt:ds,onResizeStart:rr,onAddToChat:Ls,tabs:v,activeTabId:H,onSelectTab:be?.setActiveRightPanelTab,onCloseTab:be?.closeRightPanelTab,onNewTab:()=>{if(!$e)return;const t=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;$e({kind:"url",url:"about:blank",title:"New Tab",browserId:t})},fullscreen:w,onToggleFullscreen:be?.toggleRightPanelFullscreen})]})}function li({agent:a,tasks:i,onViewProfile:s,streamActive:n}){const{t:o}=Ve(["team","common"]),[l,u]=r.useState(!1),m=r.useRef(null),f=r.useRef(null),y=a.status==="working"||!!n,k=a.status==="error",j=y?i.find(N=>N.assignedAgentId===a.id&&N.status==="in_progress"):null,E=a.currentActivity;r.useEffect(()=>{k&&a.lastError&&Zn(a.lastError)&&er()},[k,a.lastError]),r.useEffect(()=>{if(!l)return;const N=_=>{m.current&&!m.current.contains(_.target)&&u(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[l]),r.useLayoutEffect(()=>{if(!l||!f.current)return;const N=f.current,_=N.getBoundingClientRect(),h=window.innerWidth;_.right>h-8&&(N.style.left="auto",N.style.right="0"),_.left<8&&(N.style.left="0",N.style.right="auto");const T=h-16;_.width>T&&(N.style.width=`${T}px`)},[l]);const p=k?"bg-red-400 animate-pulse":y?"bg-blue-400 animate-pulse":"bg-green-400",b=o(k?"common:status.error":y?"common:status.working":"common:status.idle"),I=E?E.type==="heartbeat"?o("page.activityHeartbeat",{name:E.heartbeatName??E.label}):E.type==="chat"?E.label:E.type==="task"?o("page.activityTask",{label:E.label}):E.label:o("page.processing");return e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{onClick:()=>u(N=>!N),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors ${y?"bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20":k?"bg-red-500/10 border border-red-500/20 hover:bg-red-500/20":"bg-green-500/10 border border-green-500/20 hover:bg-green-500/20"}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${p}`}),e.jsx("span",{className:`text-xs ${k?"text-red-500":y?"text-blue-500":"text-green-600"}`,children:b}),a.mailboxDepth!=null&&a.mailboxDepth>0&&e.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:a.mailboxDepth})]}),l&&k&&e.jsxs("div",{ref:f,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:o("page.errorDetails")}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[e.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:tr(a.lastError,o)||a.lastError||o("page.agentErrorFallback")}),a.lastErrorAt&&e.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(a.lastErrorAt).toLocaleString()})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(a.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:o("page.viewAgentProfileArrow")})]}),l&&y&&e.jsxs("div",{ref:f,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:o("page.currentActivity")}),j?e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{u(!1),os.navigate(at.WORK,{openTask:j.id})},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-brand-500 truncate",children:j.title}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("page.workingOnTaskHint")})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${E?.type==="heartbeat"||E?.type==="chat","bg-blue-400 animate-pulse"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:I}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:E?.type==="heartbeat"?o("page.activityDescHeartbeat"):E?.type==="chat"?o("page.activityDescChat"):o("page.activityDescFallback")})]})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(a.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:o("page.viewMindArrow")})]})]})}export{Gl as TeamPage};