@markus-global/cli 0.9.7-rc.1 → 0.9.7

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 (62) hide show
  1. package/dist/markus.mjs +106 -40
  2. package/dist/web-ui/assets/{CommentInput-CIxUL6dU.js → CommentInput-JPZATTdP.js} +1 -1
  3. package/dist/web-ui/assets/{ContentRenderer-Bb_drUpO.js → ContentRenderer-gaxBn1N9.js} +2 -2
  4. package/dist/web-ui/assets/{DeliverableShareModal-BEeIlXig.js → DeliverableShareModal-B6qqZgFc.js} +1 -1
  5. package/dist/web-ui/assets/{Deliverables-CJFzxbLw.js → Deliverables-BUi9KGwf.js} +1 -1
  6. package/dist/web-ui/assets/{Notifications-Cz2LKhGE.js → Notifications-W-Mx_v6q.js} +1 -1
  7. package/dist/web-ui/assets/{Search-dq45wHQN.js → Search-Cxtd9r1S.js} +1 -1
  8. package/dist/web-ui/assets/{Settings-WAXEtxMR.js → Settings-Q87nTBy5.js} +1 -1
  9. package/dist/web-ui/assets/{Store-DOGCOxTK.js → Store-BK54Nx60.js} +1 -1
  10. package/dist/web-ui/assets/{Team-NM2SsmjN.js → Team-CWRLD5sM.js} +4 -4
  11. package/dist/web-ui/assets/{Work-ornw-1Zh.js → Work-xejZ7HCT.js} +1 -1
  12. package/dist/web-ui/assets/{arc-D4xcu8MX.js → arc-BqhlYS08.js} +1 -1
  13. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DP3EZPSb.js → architectureDiagram-3BPJPVTR-C8fUeKGJ.js} +1 -1
  14. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BnSHtwXa.js → blockDiagram-GPEHLZMM-eILAtQzQ.js} +1 -1
  15. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DpPSihlY.js → c4Diagram-AAUBKEIU-DdV7TyX_.js} +1 -1
  16. package/dist/web-ui/assets/channel-C-TW97LX.js +1 -0
  17. package/dist/web-ui/assets/{chunk-2J33WTMH-DD5lZIGF.js → chunk-2J33WTMH-BwuewEg2.js} +1 -1
  18. package/dist/web-ui/assets/{chunk-4BX2VUAB-D9wu9GG0.js → chunk-4BX2VUAB-Bv26FANh.js} +1 -1
  19. package/dist/web-ui/assets/{chunk-55IACEB6-p_n2ARjh.js → chunk-55IACEB6-DFTeZroI.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-727SXJPM-BiTqi43c.js → chunk-727SXJPM-i7IiTNSf.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-AQP2D5EJ-DVPMedje.js → chunk-AQP2D5EJ-BoPcIU1Z.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-FMBD7UC4-B53AqN8D.js → chunk-FMBD7UC4-DTXl3WfT.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-ND2GUHAM-sACe_lkd.js → chunk-ND2GUHAM-DdzR-Jnl.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-QZHKN3VN-B0qDAQUW.js → chunk-QZHKN3VN-DqSW43I1.js} +1 -1
  25. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C92nY4nN.js +1 -0
  26. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C92nY4nN.js +1 -0
  27. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BzZayQQf.js → cose-bilkent-S5V4N54A-C-UFRPSb.js} +1 -1
  28. package/dist/web-ui/assets/{dagre-BM42HDAG-DjcfWzm_.js → dagre-BM42HDAG-92ucBloh.js} +1 -1
  29. package/dist/web-ui/assets/{diagram-2AECGRRQ-CEK9T3rW.js → diagram-2AECGRRQ-B8zRoWWP.js} +1 -1
  30. package/dist/web-ui/assets/{diagram-5GNKFQAL-BJsJPwEI.js → diagram-5GNKFQAL-CM3pWtYN.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-KO2AKTUF-BZlki2qo.js → diagram-KO2AKTUF-V7UmwGTe.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-LMA3HP47-Bkmh3WcY.js → diagram-LMA3HP47-DG1RtUeD.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-OG6HWLK6-4THSXHiA.js → diagram-OG6HWLK6-BTwLdZJw.js} +1 -1
  34. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CPj2HGe-.js → erDiagram-TEJ5UH35-BNXeXKHH.js} +1 -1
  35. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Bu8HgFqR.js → flowDiagram-I6XJVG4X-VP_sRWgd.js} +1 -1
  36. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-C5gs9b9P.js → ganttDiagram-6RSMTGT7-CvnpoufX.js} +1 -1
  37. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DxnBgR_T.js → gitGraphDiagram-PVQCEYII-zO7DNQqQ.js} +1 -1
  38. package/dist/web-ui/assets/{index-CiAGgfZx.js → index-B1VN5yM1.js} +4 -4
  39. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-D4M-cR8I.js → infoDiagram-5YYISTIA-BSGbaVLq.js} +1 -1
  40. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Oiq6jknk.js → ishikawaDiagram-YF4QCWOH-BatvAQOH.js} +1 -1
  41. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-D2gmyCKv.js → journeyDiagram-JHISSGLW-Cajy4fZr.js} +1 -1
  42. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-DqjzkO8l.js → kanban-definition-UN3LZRKU-DLpKR4E5.js} +1 -1
  43. package/dist/web-ui/assets/{mermaid.core-N5tL3hIv.js → mermaid.core-B4fv65oQ.js} +5 -5
  44. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-ATHsVy0v.js → mindmap-definition-RKZ34NQL-C2HVqxfu.js} +1 -1
  45. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CprLr2Gv.js → pieDiagram-4H26LBE5-Bswg7SQl.js} +1 -1
  46. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-0uN86dlU.js → quadrantDiagram-W4KKPZXB-CyYiDqNE.js} +1 -1
  47. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CQmWbZXW.js → requirementDiagram-4Y6WPE33-BWZmKUo8.js} +1 -1
  48. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-D6kdJsQI.js → sankeyDiagram-5OEKKPKP-C3imZVxk.js} +1 -1
  49. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-1Y79snKt.js → sequenceDiagram-3UESZ5HK-BrySebCt.js} +1 -1
  50. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BqmCPSIN.js → stateDiagram-AJRCARHV-0Lp5CycE.js} +1 -1
  51. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-QVZbqffU.js +1 -0
  52. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-OG71KAzb.js → timeline-definition-PNZ67QCA-BIGJbkoS.js} +1 -1
  53. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-V9c-71bn.js → vennDiagram-CIIHVFJN-CS9GEvPk.js} +1 -1
  54. package/dist/web-ui/assets/{wardley-L42UT6IY-C3A6_LpL.js → wardley-L42UT6IY-BSNtMxtd.js} +1 -1
  55. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-B54ZiT7U.js → wardleyDiagram-YWT4CUSO-CaEGOjwH.js} +1 -1
  56. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-DpWlpUfV.js → xychartDiagram-2RQKCTM6-Cr_pwOHb.js} +1 -1
  57. package/dist/web-ui/index.html +1 -1
  58. package/package.json +8 -1
  59. package/dist/web-ui/assets/channel-DSB2MBEK.js +0 -1
  60. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D5cDjaiz.js +0 -1
  61. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D5cDjaiz.js +0 -1
  62. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DRaoGsBn.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CiAGgfZx.js","assets/index-BbQpGkiM.css"])))=>i.map(i=>d[i]);
2
- import{r as C,k as Qx,u as At,z as h_,j as h,q as Oa,$ as d_,a as jf,b as Ef,P as Kt,c as nh,l as K,w as yt,M as u_,A as js,n as Qr,D as _o,i as $x,a0 as f_,a1 as p_,a2 as m_,a3 as Mm,a4 as Tl,o as Lm,h as Rf,d as jx,a5 as Ex,a6 as wc,a7 as g_,a8 as O_,a9 as Nm,aa as x_,Q as b_,V as Rx,U as Ax,F as v_,ab as y_,ac as S_,_ as Mx,m as Dm,ad as Sn,ae as __,af as w_,ag as hd,ah as Im,ai as k_,aj as dd,ak as Bm,al as Wm,am as C_,an as Xm,B as qm,ao as zm,ap as P_,aq as T_,ar as Q_,as as Zm,at as $_,au as j_,av as E_,aw as R_,ax as A_,ay as M_,az as L_,p as N_,aA as oc,aB as ac,aC as D_}from"./index-CiAGgfZx.js";import{r as Vm,p as I_}from"./CommentInput-CIxUL6dU.js";import{ContentRenderer as vu,resolveFormat as B_}from"./ContentRenderer-Bb_drUpO.js";import{c as W_,D as X_}from"./DeliverableShareModal-BEeIlXig.js";function Yn(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,c;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let g;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(g=Date.now()),i=e(...u),t.key&&((c=t.debug)!=null&&c.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-g)*100)/100,m=b/16,O=(p,x)=>{for(p=String(p);p.length<x;)p=" "+p;return p};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B1VN5yM1.js","assets/index-BbQpGkiM.css"])))=>i.map(i=>d[i]);
2
+ import{r as C,k as Qx,u as At,z as h_,j as h,q as Oa,$ as d_,a as jf,b as Ef,P as Kt,c as nh,l as K,w as yt,M as u_,A as js,n as Qr,D as _o,i as $x,a0 as f_,a1 as p_,a2 as m_,a3 as Mm,a4 as Tl,o as Lm,h as Rf,d as jx,a5 as Ex,a6 as wc,a7 as g_,a8 as O_,a9 as Nm,aa as x_,Q as b_,V as Rx,U as Ax,F as v_,ab as y_,ac as S_,_ as Mx,m as Dm,ad as Sn,ae as __,af as w_,ag as hd,ah as Im,ai as k_,aj as dd,ak as Bm,al as Wm,am as C_,an as Xm,B as qm,ao as zm,ap as P_,aq as T_,ar as Q_,as as Zm,at as $_,au as j_,av as E_,aw as R_,ax as A_,ay as M_,az as L_,p as N_,aA as oc,aB as ac,aC as D_}from"./index-B1VN5yM1.js";import{r as Vm,p as I_}from"./CommentInput-JPZATTdP.js";import{ContentRenderer as vu,resolveFormat as B_}from"./ContentRenderer-gaxBn1N9.js";import{c as W_,D as X_}from"./DeliverableShareModal-B6qqZgFc.js";function Yn(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,c;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let g;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(g=Date.now()),i=e(...u),t.key&&((c=t.debug)!=null&&c.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-g)*100)/100,m=b/16,O=(p,x)=>{for(p=String(p);p.length<x;)p=" "+p;return p};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
3
3
  font-size: .6rem;
4
4
  font-weight: bold;
5
5
  color: hsl(${Math.max(0,Math.min(120-120*m,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function Fm(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const q_=(s,e)=>Math.abs(s-e)<1.01,z_=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},Ym=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},Z_=s=>s,V_=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),r=[];for(let i=e;i<=t;i++)r.push(i);return r},F_=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;const i=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(i(Ym(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const c=l.borderBoxSize[0];if(c){i({width:c.inlineSize,height:c.blockSize});return}}i(Ym(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},Um={passive:!0},Hm=typeof window>"u"?!0:"onscrollend"in window,Y_=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&Hm?()=>{}:z_(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;i=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,Um);const c=s.options.useScrollendEvent&&Hm;return c&&t.addEventListener("scrollend",l,Um),()=>{t.removeEventListener("scroll",o),c&&t.removeEventListener("scrollend",l)}},U_=(s,e,t)=>{if(e?.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},H_=(s,{adjustments:e=0,behavior:t},r)=>{var i,n;const a=s+e;(n=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||n.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:t})};class G_{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,r,i;return((i=(r=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let t=null;const r=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),t=null},observe:i=>{var n;return(n=r())==null?void 0:n.observe(i,{box:"border-box"})},unobserve:i=>{var n;return(n=r())==null?void 0:n.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([r,i])=>{typeof i>"u"&&delete t[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Z_,rangeExtractor:V_,onChange:()=>{},measureElement:U_,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,t)},this.maybeNotify=Yn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,r)=>{const i=new Map,n=new Map;for(let a=r-1;a>=0;a--){const o=t[a];if(i.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&i.set(o.lane,!0),i.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=Yn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,r,i,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=Yn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},c)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const g of this.laneAssignments.keys())g>=t&&this.laneAssignments.delete(g);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(g=>{this.itemSizeCache.set(g.key,g.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let g=0;g<d;g++){const v=u[g];v&&(f[v.lane]=g)}for(let g=d;g<t;g++){const v=n(g),b=this.laneAssignments.get(g);let m,O;const p=l==="estimate"||c.has(v);if(b!==void 0&&this.options.lanes>1){m=b;const k=f[m],w=k!==void 0?u[k]:void 0;O=w?w.end+this.options.gap:r+i}else{const k=this.options.lanes===1?u[g-1]:this.getFurthestMeasurement(u,g);O=k?k.end+this.options.gap:r+i,m=k?k.lane:g%this.options.lanes,this.options.lanes>1&&p&&this.laneAssignments.set(g,m)}const x=c.get(v),y=typeof x=="number"?x:this.options.estimateSize(g),_=O+y;u[g]={index:g,start:O,size:y,end:_,key:v,lane:m},f[m]=g}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Yn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?K_({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Yn(()=>{let t=null,r=null;const i=this.calculateRange();return i&&(t=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,r]},(t,r,i,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const r=this.options.indexAttribute,i=t.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,i-n),o=Math.min(this.options.count-1,i+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const r=this.indexFromElement(t),i=this.options.getItemKey(r),n=this.elementsCache.get(i);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,r)=>{var i;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=r-a;o!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,r)),this.notify(!1))},this.getVirtualItems=Yn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,r)=>{const i=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=r[o];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const r=this.getMeasurements();if(r.length!==0)return Fm(r[Lx(0,r.length-1,i=>Fm(r[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,r,i=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=t>=a+n?"end":"start"),r==="center"?t+=(i-n)/2:r==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,r="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const i=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(r==="auto")if(a.end>=n+i-this.options.scrollPaddingEnd)r="end";else if(a.start<=n+this.options.scrollPaddingStart)r="start";else return[n,r];if(r==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),r];const o=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,r,a.size),r]},this.scrollToOffset=(t,{align:r="start",behavior:i="auto"}={})=>{const n=this.getOffsetForAlignment(t,r),a=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:r="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,r);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:i,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:n,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=r[r.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&n.some(o=>o===null);){const o=r[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}i=Math.max(...n.filter(o=>o!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:r,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,n=1,a=i!==this.scrollState.lastTargetOffset;if(!a&&q_(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Lx=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function K_({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=Lx(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const c=Array(r).fill(t+e);for(;a>=0&&c.some(d=>d>=t);){const d=s[a];c[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const Gm=typeof document<"u"?C.useLayoutEffect:C.useEffect;function J_({useFlushSync:s=!0,...e}){const t=C.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Qx.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=C.useState(()=>new G_(r));return i.setOptions(r),Gm(()=>i._didMount(),[]),Gm(()=>i._willUpdate()),i}function ew(s){return J_({observeElementRect:F_,observeElementOffset:Y_,scrollToFn:H_,...s})}const Km={urgent:"bg-red-500/15 text-red-500",high:"bg-amber-500/15 text-amber-600",normal:"bg-blue-500/15 text-blue-500",low:"bg-surface-overlay text-fg-tertiary"};function tw({notification:s,agentName:e,acknowledging:t,onClose:r,onAcknowledge:i}){const{t:n}=At(["team","common"]);h_(!0);const a=s.priority||"normal",o=s.metadata??{},l=e||(typeof o.agentName=="string"?o.agentName:void 0);return Qx.createPortal(h.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:c=>{c.target===c.currentTarget&&r()},children:h.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[h.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[h.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),h.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),h.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[l&&h.jsx("p",{className:"text-xs text-fg-tertiary",children:l}),a!=="normal"&&h.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${Km[a]??Km.normal}`,children:a})]})]}),h.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 6L6 18"}),h.jsx("path",{d:"M6 6l12 12"})]})})]}),h.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:h.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:h.jsx(Oa,{content:s.body||""})})}),h.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[h.jsx("button",{onClick:r,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:close")}),h.jsx("button",{onClick:()=>{i()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?n("common:loading"):n("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"})})]})]})}),document.body)}function xa({children:s,onClose:e,title:t,width:r="w-[440px]"}){return h.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:h.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[h.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function so({label:s,children:e}){return h.jsxs("div",{children:[h.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function sw({onClose:s,onCreate:e}){const{t}=At(["team","common"]),[r,i]=C.useState(""),[n,a]=C.useState("");return h.jsx(xa,{onClose:s,title:t("team:modals.createTeam.title"),children:h.jsxs("div",{className:"space-y-4",children:[h.jsx(so,{label:t("team:modals.createTeam.teamName"),children:h.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),h.jsx(so,{label:t("team:modals.createTeam.description"),children:h.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),h.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),h.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:h.jsx(d_,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:h.jsx("span",{className:"text-brand-400 font-medium"}),1:h.jsx("span",{className:"text-brand-400"})}})}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function rw({onClose:s,onAdd:e}){const{t}=At(["team","common"]),[r,i]=C.useState(""),[n,a]=C.useState("member"),[o,l]=C.useState(""),[c,d]=C.useState(""),[u,f]=C.useState(!1),[g,v]=C.useState(null),[b,m]=C.useState(!1),O=g?.inviteToken?`${window.location.origin}/#invite?token=${g.inviteToken}`:null,p=async()=>{if(d(""),!r.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(r.trim(),n,o.trim());v({...y,userName:r.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),m(!0),setTimeout(()=>m(!1),2e3))};return g?h.jsxs(xa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[h.jsxs("div",{className:"text-center py-4",children:[h.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:h.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:h.jsx("polyline",{points:"20 6 9 17 4 12"})})}),h.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:g.userName})}),O?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),h.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),h.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),h.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${b?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(b?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):h.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),h.jsx("div",{className:"flex justify-end pt-3",children:h.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):h.jsx(xa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[h.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),h.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",h.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),h.jsx(so,{label:t("team:modals.addHuman.name"),children:h.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),h.jsx(so,{label:t("team:modals.addHuman.role"),children:h.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[h.jsx("option",{value:"owner",children:t("common:role.owner")}),h.jsx("option",{value:"admin",children:t("common:role.admin")}),h.jsx("option",{value:"member",children:t("common:role.member")}),h.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),h.jsx(so,{label:t("team:modals.addHuman.emailRequired"),children:h.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),h.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),c&&h.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:c}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:p,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function iw({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=At(["team","common"]);return h.jsx(xa,{onClose:t,title:i("team:modals.addExisting.title"),children:h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?h.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):h.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>h.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[h.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),h.jsxs("div",{className:"flex-1",children:[h.jsx("div",{className:"font-medium text-sm",children:n.name}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&h.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function nw({onClose:s,onConnected:e}){const{t}=At(["team","common"]),[r,i]=C.useState(""),[n,a]=C.useState(""),[o,l]=C.useState(!1),[c,d]=C.useState(null),[u,f]=C.useState(null),g=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const m=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!m.ok){const p=await m.json().catch(()=>({}));throw new Error(p.error??`HTTP ${m.status}`)}const O=await m.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(m){a(String(m))}l(!1)},v=(b,m)=>{navigator.clipboard.writeText(b),f(m),setTimeout(()=>f(null),2e3)};return h.jsx(xa,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:c?(()=>{const b=c.gatewayUrl??`${window.location.origin}/api/gateway`,m=c.token?t("team:modals.openClaw.bearerTokenLine",{token:c.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:c.externalAgentId,tokenSection:m});return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"text-center py-6",children:[h.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),h.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),h.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:h.jsx("strong",{children:r})})]}),h.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[h.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),h.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),h.jsx("div",{className:"flex justify-end pt-5",children:h.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),h.jsxs("div",{className:"space-y-4",children:[h.jsx(so,{label:t("team:modals.openClaw.agentName"),children:h.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&h.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),h.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[h.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),h.jsx("button",{onClick:g,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let Ql=new Map;function ow({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=At(["team","common"]),[a,o]=C.useState(""),[l,c]=C.useState(new Set),[d,u]=C.useState(""),[f,g]=C.useState(!1),v=C.useMemo(()=>{const p=[];for(const x of s)p.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&p.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return p},[s,e,t]),b=C.useMemo(()=>{if(!d)return v;const p=d.toLowerCase();return v.filter(x=>x.name.toLowerCase().includes(p)||x.subtitle.toLowerCase().includes(p))},[v,d]),m=p=>{c(x=>{const y=new Set(x);return y.has(p)?y.delete(p):y.add(p),y})},O=async()=>{if(!a.trim()||l.size===0)return;g(!0);const p=[...l],x={},y={};for(const _ of p){const k=v.find(w=>w.id===_);k&&(x[_]=k.type,y[_]=k.name)}await i(a.trim(),p,x,y),g(!1)};return h.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:h.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[h.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[h.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),h.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),h.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:h.jsx("input",{value:a,onChange:p=>o(p.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),h.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:h.jsx("input",{value:d,onChange:p=>u(p.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),h.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&h.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(p=>h.jsxs("button",{onClick:()=>m(p.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(p.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[h.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(p.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(p.id)&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"20 6 9 17 4 12"})})}),h.jsx(js,{name:p.name,size:20,bgClass:p.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate text-[11px] font-medium block",children:p.name}),h.jsx("span",{className:"text-[9px] text-fg-tertiary",children:p.subtitle})]}),h.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${p.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:p.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},p.id))]}),h.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),h.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const aw=C.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:c,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:g,onSelectDm:v,onSelectTeam:b,selectedTeamId:m,onRefreshTeams:O,onRefreshAgents:p,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:_,onManageGroupMembers:k,unreadByAgent:w,unreadByChannel:S,width:Q,onResizeStart:N,hidden:L,onCollapse:$,initialLoading:j,previewMode:I,focused:V,l2Available:Z}){const{t:z}=At(["team","common"]),J=jf(),T=Ef(Kt.TEAM),A=nh(),B=e?.role==="owner"||e?.role==="admin",q=C.useMemo(()=>new Set(a.map(W=>W.markusAgentId).filter(Boolean)),[a]),[H,te]=C.useState([]),[ue,ke]=C.useState(new Set),[U,D]=C.useState(!1),[se,F]=C.useState(!1),[G,ee]=C.useState(null),[we,Ae]=C.useState(!1),[xe,me]=C.useState(!1),[ge,He]=C.useState(null),[nt,Ct]=C.useState(null),[pt,Xt]=C.useState(null),[wt,Et]=C.useState(!1),[Pt,he]=C.useState(""),[Xe,Oe]=C.useState(null),[Ke,Ne]=C.useState(null),[bt,ot]=C.useState(null),[ir,ts]=C.useState(!1),Ka=C.useRef(null),[Ja,el]=C.useState(null),rn=C.useRef(null),si=C.useRef(null),[Qo,tl]=C.useState(null),ji=(W,le="success")=>{tl({message:W,type:le}),setTimeout(()=>tl(null),3e3)},[nr,Ei]=C.useState(null),[Dn,$o]=C.useState(!1),nn=C.useRef(!1);C.useEffect(()=>{if(I)return;K.governance.getSystemStatus().then(pe=>{nn.current=!0,Ei(pe.globalPaused)}).catch(()=>{nn.current=!0,Ei(!1)});const W=yt.on("system:pause-all",()=>{nn.current&&Ei(!0)}),le=yt.on("system:resume-all",()=>{nn.current&&Ei(!1)});return()=>{W(),le()}},[]),C.useEffect(()=>{if(!I)return;const W=setTimeout(()=>{const le=si.current,pe=rn.current;le&&pe&&pe.scrollTo({top:le.offsetTop-pe.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(W)},[I]);const wh=C.useCallback(()=>{nr!==null&&Ri({title:z(nr?"modals.resumeAll.title":"modals.pauseAll.title"),message:z(nr?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:z(nr?"chat.resume":"chat.pause"),onConfirm:async()=>{$o(!0);try{nr?(await K.governance.resumeAll(),Ei(!1)):(await K.governance.pauseAll(),Ei(!0))}catch{}$o(!1)}})},[nr]),[Lr,Ri]=C.useState(null),on=(W,le,pe,je,Ge)=>{Ri({title:W,message:le,onConfirm:pe,confirmLabel:je,checkboxes:Ge})},[or,sl]=C.useState(null),[vr,jo]=C.useState(null),ri=C.useRef(null),Nr=C.useRef(null),[us,Eo]=C.useState(!1),[rl,ie]=C.useState(null),[gt,be]=C.useState(""),Yt=C.useCallback((W,le=176,pe=220)=>{const je=window.innerWidth,Ge=window.innerHeight,tt=8;let Ot=W.clientX,St=W.clientY;return Ot+le>je-tt&&(Ot=Math.max(tt,je-le-tt)),St+pe>Ge-tt&&(St=Math.max(tt,Ge-pe-tt)),Ot=Math.max(tt,Math.min(Ot,je-le-tt)),St=Math.max(tt,Math.min(St,Ge-pe-tt)),{x:Ot,y:St}},[]),[mt,ks]=C.useState(Ql),Ut=C.useMemo(()=>t.map(W=>W.id).sort().join(","),[t]);C.useEffect(()=>{if(!t.length||!T)return;let W=!1;(async()=>{const St=[];await Promise.allSettled(t.map(async Ye=>{if(!Ql.has(Ye.id))try{const{sessions:ns}=await K.sessions.listByAgent(Ye.id,1);if(!ns.length)return;const{messages:Ls}=await K.sessions.getMessages(ns[0].id,1);if(Ls.length){const Mt=Ls[0],xs=Mt.metadata?.segments;let Ht=Mt.content;if(xs&&xs.length>0){const _r=[...xs].reverse().find(Mi=>Mi.type==="text");_r&&_r.type==="text"&&(Ht=_r.content)}const Ts=Ht.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);Ts&&St.push([Ye.id,Ts])}}catch{}})),!W&&St.length&&ks(Ye=>{const ns=new Map(Ye);for(const[Ls,Mt]of St)ns.set(Ls,Mt);return Ql=ns,ns})})();const pe=new Set(t.map(St=>St.id)),je=St=>St.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ge=(St,Ye)=>{if(!St||!Ye||!pe.has(St))return;const ns=je(Ye);ns&&ks(Ls=>{const Mt=new Map(Ls);return Mt.set(St,ns),Ql=Mt,Mt})},tt=yt.on("chat:proactive_message",St=>{const Ye=St.payload;Ge(Ye.agentId??"",Ye.message??"")}),Ot=yt.on("chat:message",St=>{const Ye=St.payload,ns=Ye.senderId??Ye.agentId??"",Ls=Ye.text??Ye.message??"";Ge(ns,Ls)});return()=>{W=!0,tt(),Ot()}},[Ut,T]);const gs=C.useCallback(()=>{I||K.teams.list().then(W=>te(W.ungrouped)).catch(()=>{})},[I]);C.useEffect(()=>{gs()},[gs]),C.useEffect(()=>{if(!T)return;const W=yt.on("team:update",gs),le=yt.on("agent:removed",gs);return()=>{W(),le()}},[gs,T]),C.useEffect(()=>{if(!nt&&!pt&&!Xe&&!ir&&!bt)return;const W=()=>{Ct(null),Xt(null),Oe(null),ot(null),ts(!1)},le=setTimeout(()=>document.addEventListener("click",W),0);return()=>{clearTimeout(le),document.removeEventListener("click",W)}},[nt,pt,Xe,ir,bt]);const il=(W,le)=>{on(`${z("common:delete")} "${le}"?`,z("modals.deleteTeam.message"),async pe=>{const je=pe?.deleteMembers??!0,Ge=pe?.purgeFiles??!1;await K.teams.delete(W,je,{purgeFiles:Ge}),O(),gs(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},z("contextMenu.deleteTeam"),[{id:"deleteMembers",label:z("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:z("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Ai=async(W,le)=>{try{const je=await(le==="start"?K.teams.startAll:K.teams.stopAll)(W),Ge=je.success?.length??0,tt=je.failed?.length??0;tt>0?ji(z("batchAction.failed",{action:z(`batchAction.operation.${le}`),ok:Ge,fail:tt}),"error"):Ge>0&&ji(z("batchAction.succeeded",{count:Ge,action:z(`batchAction.past.${le}`)}),"success"),p()}catch(pe){ji(z("batchAction.failedToRun",{action:z(`batchAction.operation.${le}`),error:pe instanceof Error?pe.message:String(pe)}),"error")}},Ro=async(W,le,pe)=>{await K.teams.update(W,{managerId:le,managerType:pe}),O()},nl=async W=>{if(!gt.trim()){ie(null);return}await K.teams.update(W,{name:gt.trim()}),ie(null),O()},ol=async(W,le)=>{le==="offline"?await K.agents.start(W):await K.agents.stop(W),p()},zt=(W,le)=>{on(z("modals.removeFromTeam.title"),z("modals.removeFromTeam.message"),async()=>{await K.teams.removeMember(W,le),O(),gs()},z("common:remove"))},Cs=(W,le,pe,je)=>{on(`${z("common:remove")} "${le}"?`,z(pe==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ge=>{if(pe==="agent"&&je){const tt=o.find(Ot=>Ot.type==="team"&&Ot.teamId===je);tt?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+tt.channelKey)}if(pe==="agent"){const tt=Ge?.purgeFiles??!1;await K.agents.remove(W,{purgeFiles:tt})}else await K.users.remove(W);p(),O(),x?.(),gs(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},z("common:remove"),pe==="agent"?[{id:"purgeFiles",label:z("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},Ms=W=>{if(W.isOrgSecretary||W.protected)return!0;if(W.teamId)return!1;const le=(W.role??"").toLowerCase().trim(),pe=(W.name??"").trim();return pe==="Secretary"||pe==="秘书"||le==="secretary"||le.startsWith("secretary")},Os=(W,le,pe)=>{const je=t.find(Ge=>Ge.id===le);je&&Ms(je)||(Nr.current={x:W.clientX,y:W.clientY},ri.current=setTimeout(()=>{sl({agentId:le,fromTeamId:pe}),Eo(!0)},200))},kh=W=>{if(!Nr.current||!ri.current)return;const le=Math.abs(W.clientX-Nr.current.x),pe=Math.abs(W.clientY-Nr.current.y);(le>5||pe>5)&&(us||(clearTimeout(ri.current),ri.current=null))},yr=async()=>{if(ri.current&&(clearTimeout(ri.current),ri.current=null),Nr.current=null,us&&or&&vr){const W=vr==="_ungrouped"?void 0:vr;try{if(or.fromTeamId&&or.fromTeamId!==W&&await K.teams.removeMember(or.fromTeamId,or.agentId),W&&W!==or.fromTeamId){const le=t.find(pe=>pe.id===or.agentId);await K.teams.addMember(W,or.agentId,"agent")}O(),p(),gs()}catch(le){ji(z("batchAction.moveFailed",{error:le instanceof Error?le.message:String(le)}),"error")}}sl(null),jo(null),Eo(!1)},ss=C.useMemo(()=>new Map(r.map(W=>[W.id,W])),[r]),ar=C.useMemo(()=>{const W=new Map,le=[];for(const pe of t)if(pe.teamId&&ss.has(pe.teamId)){const je=W.get(pe.teamId)??[];je.push(pe),W.set(pe.teamId,je)}else le.push(pe);return{byTeam:W,ungrouped:le}},[t,ss]),ii=(W,le)=>{const pe=l==="direct"&&c===W.id,je=q.has(W.id),Ge=W.status==="offline",tt=W.status==="idle"?"bg-green-500":W.status==="working"?"bg-blue-500 animate-pulse":W.status==="error"?"bg-red-500":"bg-gray-600",St=(void 0)?.managerId===W.id,Ye=W.role?.toLowerCase().replace(/[-_]/g," ").trim(),ns=W.name.toLowerCase().trim(),Ls=Ye&&Ye!==ns,Mt=mt.get(W.id)||W.currentActivity?.label?.slice(0,60)||"",xs=W.status==="idle"?z("common:status.online"):W.status==="working"?z("common:status.working"):W.status==="error"?z("common:status.error"):z("common:status.offline");return h.jsx("div",{className:`relative mb-0.5 ${us&&or?.agentId===W.id?"opacity-40":""}`,onPointerDown:Ht=>Os(Ht,W.id,le),onPointerMove:kh,onPointerUp:yr,children:h.jsxs("button",{"data-l1-nav-id":`agent:${W.id}`,onClick:()=>{us||f(W.id)},onContextMenu:Ht=>{if(!B)return;Ht.preventDefault();const Ts=Yt(Ht);Et(!1),he(""),Xt({agentId:W.id,teamId:le,...Ts})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${J?"":"touch-none"} ${Ge?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ps(pe)}`,children:[h.jsx(js,{name:W.name,avatarUrl:W.avatarUrl,size:28,bgClass:Ge?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:W.name}),Ls&&h.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",W.role,")"]}),St&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:h.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),je&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ge&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:z("common:status.offline")})]}),h.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Mt||" "})]}),h.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(w?.get(W.id)??0)>0&&h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:w.get(W.id)}),W.mailboxDepth!=null&&W.mailboxDepth>0&&h.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:W.mailboxDepth}),h.jsx("span",{title:xs,onClick:Ht=>{Ht.stopPropagation(),_(W.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${tt}`}),J&&B&&h.jsx("span",{role:"button",tabIndex:0,onClick:Ht=>{if(Ht.stopPropagation(),pt?.agentId===W.id)Xt(null);else{const Ts=Yt(Ht);Et(!1),he(""),Xt({agentId:W.id,teamId:le,...Ts})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:z("chat.moreOptions"),children:h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"1"}),h.jsx("circle",{cx:"12",cy:"5",r:"1"}),h.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},W.id)},Sr=(W,le,pe,je)=>{const Ge=us&&vr===W&&or?.fromTeamId!==W,tt=Ja===W,Ot=m===W,St=w?(ar.byTeam.get(W)??[]).reduce((Wt,wr)=>Wt+(w.get(wr.id)??0),0):0,Ye=o.find(Wt=>Wt.type==="team"&&Wt.teamId===W),ns=Ye&&S?S[Ye.channelKey]??0:0,Ls=St+ns,Mt=ar.byTeam.get(W)??[],xs=Mt.filter(Wt=>Wt.status==="offline").length,Ht=Mt.length,Ts=Ht>0&&xs===Ht,_r=xs>0&&!Ts,Mi=Ts?"bg-gray-500":_r?"bg-amber-500":"bg-green-500";return h.jsxs("div",{"data-team-id":W,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ge?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${tt?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{us&&jo(W)},onPointerLeave:()=>{us&&vr===W&&jo(null)},children:[h.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[h.jsxs("button",{"data-l1-nav-id":`team:${W}`,onClick:()=>{b&&W!=="_ungrouped"&&b(W)},onContextMenu:Wt=>{if(!B||!le)return;Wt.preventDefault();const wr=Yt(Wt);Ct({teamId:W,...wr})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${Ts?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ps(Ot)}`,children:[h.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${Ts?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[le?.avatarUrl?h.jsx("img",{src:le.avatarUrl,alt:je,className:"w-full h-full rounded-full object-cover",onError:Wt=>{Wt.target.style.display="none",Wt.target.nextElementSibling?.classList.remove("hidden")}}):null,h.jsxs("svg",{className:`w-3 h-3 ${le?.avatarUrl?"hidden":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ht>0&&h.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${Mi}`})]}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[rl===W?h.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:gt,onChange:Wt=>be(Wt.target.value),onBlur:()=>nl(W),onKeyDown:Wt=>{Wt.key==="Enter"&&nl(W),Wt.key==="Escape"&&ie(null)},onClick:Wt=>Wt.stopPropagation(),autoFocus:!0}):h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:je}),h.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[z("chat.members_other",{count:pe}),Ts&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:z("common:status.offline")}),_r&&h.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[xs,"/",Ht]})]})]}),Ls>0&&h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:Ls}),h.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:h.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),B&&le&&h.jsx("button",{onClick:Wt=>{if(Wt.stopPropagation(),nt?.teamId===W)Ct(null);else{const wr=Yt(Wt);Ct({teamId:W,...wr})}},className:"w-7 h-7 flex items-center justify-center text-fg-muted hover:text-fg-primary rounded-md hover:bg-white/[0.08] transition-colors shrink-0",title:z("chat.moreOptions"),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"1"}),h.jsx("circle",{cx:"12",cy:"5",r:"1"}),h.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ge&&us&&h.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:z("chat.dropHere")})]},W)},Ws=C.useMemo(()=>{const W=new Map,le=[],pe=[],je=[];for(const Ge of o)if(Ge.channelKey.startsWith("dm:a2a:"))je.push(Ge);else if(Ge.type==="custom")pe.push(Ge);else if(Ge.teamId){const tt=W.get(Ge.teamId)??[];tt.push(Ge),W.set(Ge.teamId,tt)}else{const tt=r.find(Ot=>Ge.name.toLowerCase().includes(Ot.name.toLowerCase())||Ot.name.toLowerCase().includes(Ge.name.toLowerCase()));if(tt){const Ot=W.get(tt.id)??[];Ot.push(Ge),W.set(tt.id,Ot)}else le.push(Ge)}return{byTeam:W,unmatched:le,custom:pe,dmChannels:je}},[o,r]),[at,ft]=C.useState(!1),ni=l==="channel"&&Ws.dmChannels.some(W=>W.channelKey===d);C.useEffect(()=>{ni&&ft(!0)},[ni]);const an=C.useMemo(()=>{const W=[];e&&W.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const pe of i)pe.id!==e?.id&&W.push({kind:"dm",id:`dm:${pe.id}`,userId:pe.id});for(const pe of Ws.custom)W.push({kind:"channel",id:`channel:${pe.channelKey}`,channelKey:pe.channelKey});for(const pe of Ws.unmatched)W.push({kind:"channel",id:`channel:${pe.channelKey}`,channelKey:pe.channelKey});const le=ar.ungrouped.length>0?ar.ungrouped:r.length===0?t:[];for(const pe of le)W.push({kind:"agent",id:`agent:${pe.id}`,agentId:pe.id});for(const pe of r)W.push({kind:"team",id:`team:${pe.id}`,teamId:pe.id});if(at)for(const pe of Ws.dmChannels)W.push({kind:"channel",id:`channel:${pe.channelKey}`,channelKey:pe.channelKey});return W},[e,i,Ws,ar,r,t,at]),al=C.useRef(an);al.current=an;const ln=C.useCallback(W=>{W.kind==="dm"?v(W.userId):W.kind==="channel"?g(W.channelKey):W.kind==="agent"?f(W.agentId):W.kind==="team"&&b?.(W.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${W.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,g,f,b]);C.useEffect(()=>{if(I||J||!T||L)return;const W=le=>{const pe=A?.keyboardPane??"content";if(pe==="l0"||pe==="l2"||le.metaKey||le.ctrlKey||le.altKey||$x(le.target))return;const je=le.key.length===1?le.key.toLowerCase():le.key;if(je==="h"||je==="ArrowLeft"){if(pe!=="l1")return;le.preventDefault(),le.stopPropagation(),A?.setL0FocusPageId(Kt.TEAM),A?.setLeftCollapsed(!1),A?.setKeyboardPane("l0");return}if(je==="l"||je==="ArrowRight"){if(pe!=="l1")return;le.preventDefault(),le.stopPropagation(),Z&&A?.setKeyboardPane("l2");return}if(pe!=="l1"&&!(V&&(je==="j"||je==="k"||je==="ArrowDown"||je==="ArrowUp")))return;const Ge=je==="j"||je==="ArrowDown"?1:je==="k"||je==="ArrowUp"?-1:0;if(!Ge)return;le.preventDefault(),le.stopPropagation(),A?.setKeyboardPane("l1");const tt=al.current;if(tt.length===0)return;let Ot=-1;if(l==="dm"){const Ye=u||e?.id;Ye&&(Ot=tt.findIndex(ns=>ns.kind==="dm"&&ns.userId===Ye))}else l==="direct"?Ot=tt.findIndex(Ye=>Ye.kind==="agent"&&Ye.agentId===c):l==="channel"&&(Ot=tt.findIndex(Ye=>Ye.kind==="channel"&&Ye.channelKey===d),Ot<0&&m&&(Ot=tt.findIndex(Ye=>Ye.kind==="team"&&Ye.teamId===m)));Ot<0&&(Ot=Ge>0?-1:0);const St=Math.max(0,Math.min(tt.length-1,Ot+Ge));ln(tt[St])};return document.addEventListener("keydown",W,!0),()=>document.removeEventListener("keydown",W,!0)},[I,J,T,L,A,V,Z,l,u,e?.id,c,d,m,ln]);const Ps=W=>W?V?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return h.jsxs(h.Fragment,{children:[h.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${Q!=null?"shrink-0":"flex-1 min-w-0"} ${V?"ring-1 ring-inset ring-brand-500/30":""}`,style:L?{display:"none"}:Q!=null?{width:Q}:void 0,children:[h.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[J&&h.jsx(u_,{}),!J&&$&&h.jsx("button",{onClick:$,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),h.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),h.jsx("h2",{className:"text-lg font-semibold",children:z("chat.title")}),B&&h.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ka,children:[h.jsxs("button",{onClick:()=>ts(!ir),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[h.jsx("span",{className:"text-brand-500",children:"+"})," ",z("chat.manage"),h.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${ir?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:h.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),ir&&h.jsxs("div",{ref:W=>{if(!W)return;const le=W.getBoundingClientRect(),pe=window.innerWidth,je=8;le.right>pe-je&&(W.style.left="auto",W.style.right="0"),le.left<je&&(W.style.left="0",W.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[h.jsxs("button",{onClick:()=>{ts(!1),He("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),h.jsx("circle",{cx:"12",cy:"5",r:"2"}),h.jsx("path",{d:"M12 7v4"}),h.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),h.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),z("chat.addAgent")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.addAgentDesc")})]}),h.jsxs("button",{onClick:()=>{ts(!1),He("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),h.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),z("chat.newTeam")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.newTeamDesc")})]}),h.jsxs("button",{onClick:()=>{ts(!1),F(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M20 8v6"}),h.jsx("path",{d:"M23 11h-6"})]}),z("chat.addHuman")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.addHumanDesc")})]}),h.jsxs("button",{onClick:()=>{ts(!1),me(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[h.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),h.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),z("chat.newGroupChat")]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.newGroupChatDesc")})]}),nr!==null&&h.jsxs("button",{onClick:()=>{ts(!1),wh()},disabled:Dn,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 ${nr?"text-green-600":"text-red-500"}`,children:[h.jsx("div",{className:"font-medium flex items-center gap-1.5",children:nr?h.jsxs(h.Fragment,{children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",z("chat.resume")]}):h.jsxs(h.Fragment,{children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",z("contextMenu.stopAll")]})}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z(nr?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),h.jsxs("div",{ref:rn,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:z("chat.people")}),e&&h.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ps(l==="dm"&&(u===e.id||!u))}`,children:[h.jsx(js,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:z("chat.myNotes")})]}),h.jsx("span",{className:"text-fg-secondary shrink-0",children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),h.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(W=>W.id!==e?.id).map(W=>{const le=e?.id?`dm:${[e.id,W.id].sort().join(":")}`:"",pe=le&&S?S[le]??0:0;return h.jsxs("button",{"data-l1-nav-id":`dm:${W.id}`,onClick:()=>v(W.id),onContextMenu:je=>{if(!B||W.id===e?.id)return;je.preventDefault();const Ge=Yt(je);Oe({userId:W.id,...Ge})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${l==="dm"&&u===W.id?V?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[h.jsx(js,{name:W.name,avatarUrl:W.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:W.name}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:W.email||W.role})]}),pe>0?h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:pe}):h.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},W.id)})]}),Ws.custom.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:z("chat.groups")}),Ws.custom.map(W=>{const le=l==="channel"&&d===W.channelKey;return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.channelKey),onContextMenu:pe=>{pe.preventDefault();const je=Yt(pe);ot({gcId:W.id,...je})},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 ${Ps(le)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:W.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:z("chat.members_other",{count:W.memberCount??0})})]})]},W.id)})]}),j?h.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((W,le)=>h.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[h.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),h.jsxs("div",{className:"flex-1 space-y-1.5",children:[h.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),h.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),h.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},le))}):t.length===0&&r.length===0?h.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:z("chat.noAgentsYet")}):null,Ws.unmatched.map(W=>{const le=S?.[W.channelKey]??0;return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ps(l==="channel"&&d===W.channelKey)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:W.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:z("chat.groupChat")})]}),le>0?h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:le}):W.memberCount!==void 0&&W.memberCount>0?h.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:W.memberCount}):null]},W.id)}),ar.ungrouped.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:z("chat.agents")}),ar.ungrouped.map(W=>ii(W))]}),r.length>0&&h.jsxs("div",{className:"mb-2",ref:si,children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:z("chat.teams")}),r.map(W=>{const le=ar.byTeam.get(W.id)??[],pe=W.members?.length||le.length;return Sr(W.id,W,pe,W.name)})]}),r.length===0&&ar.ungrouped.length===0&&t.length>0&&t.map(W=>ii(W)),Ws.dmChannels.length>0&&h.jsxs("div",{className:"mb-2",children:[h.jsxs("button",{onClick:()=>ft(W=>!W),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[h.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${at?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:h.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),z("chat.agentDMs"),h.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Ws.dmChannels.length})]}),at&&Ws.dmChannels.map(W=>{const le=l==="channel"&&d===W.channelKey,pe=S?.[W.channelKey]??0,je=W.name.replace(/^DM:\s*/,"");return h.jsxs("button",{"data-l1-nav-id":`channel:${W.channelKey}`,onClick:()=>g(W.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ps(le)}`,children:[h.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),h.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:je}),pe>0&&h.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:pe})]},W.id)})]})]})]}),N&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:N,children:h.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),nt&&(()=>{const W=ar.byTeam.get(nt.teamId)??[],le=W.some(je=>je.status==="offline"),pe=W.some(je=>je.status!=="offline");return h.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:nt.x,top:nt.y},onClick:je=>je.stopPropagation(),children:[h.jsxs("button",{onClick:()=>{const je=ss.get(nt.teamId);je&&(ie(nt.teamId),be(je.name)),Ct(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),h.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),z("contextMenu.renameTeam")]}),le&&h.jsxs("button",{onClick:()=>{Ai(nt.teamId,"start"),Ct(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),z("contextMenu.startAll")]}),pe&&h.jsxs("button",{onClick:()=>{Ai(nt.teamId,"stop"),Ct(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),z("contextMenu.stopAll")]}),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{Ct(null),Qr.navigate(Kt.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),z("chat.addAgent")]}),H.length>0&&h.jsxs("button",{onClick:()=>{Ct(null),ee(nt.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),h.jsx("polyline",{points:"17 11 19 13 23 9"})]}),z("contextMenu.addExisting")]}),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{const je=ss.get(nt.teamId);je&&il(nt.teamId,je.name),Ct(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.deleteTeam")]})]})})(),pt&&(()=>{const W=t.find(tt=>tt.id===pt.agentId);if(!W||!B)return null;const pe=(pt.teamId?ss.get(pt.teamId):void 0)?.managerId===W.id,je=W.id===e?.id,Ge=Ms(W);return h.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:pt.x,top:pt.y,maxHeight:Math.max(160,window.innerHeight-pt.y-8)},onClick:tt=>tt.stopPropagation(),children:[Ge&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:z("contextMenu.orgSecretaryProtected")}),h.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),h.jsxs("button",{onClick:()=>{Xt(null),_(W.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),z("contextMenu.viewProfile")]}),W.status==="offline"?h.jsxs("button",{onClick:()=>{ol(W.id,"offline"),Xt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),z("contextMenu.start")]}):h.jsxs("button",{onClick:()=>{ol(W.id,W.status??"idle"),Xt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),z("contextMenu.stop")]}),!Ge&&pt.teamId&&!pe&&h.jsxs("button",{onClick:()=>{Ro(pt.teamId,W.id,"agent"),Xt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),z("contextMenu.setAsManager")]}),!Ge&&pt.teamId&&h.jsxs("button",{onClick:()=>{zt(pt.teamId,W.id),Xt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"9 14 4 9 9 4"}),h.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),z("contextMenu.removeFromTeam")]}),!Ge&&(()=>{const tt=r.filter(Ye=>Ye.id!==pt.teamId);if(tt.length===0)return null;const Ot=Pt.trim().toLowerCase(),St=Ot?tt.filter(Ye=>Ye.name.toLowerCase().includes(Ot)):tt;return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{type:"button",onClick:()=>Et(Ye=>!Ye),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M5 12h14"}),h.jsx("path",{d:"M12 5l7 7-7 7"})]}),h.jsx("span",{className:"flex-1",children:z("contextMenu.moveTo")}),h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${wt?"rotate-180":""}`,children:h.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),wt&&h.jsxs("div",{className:"px-2 pb-1.5",onClick:Ye=>Ye.stopPropagation(),children:[h.jsx("input",{autoFocus:!0,value:Pt,onChange:Ye=>he(Ye.target.value),onKeyDown:Ye=>Ye.stopPropagation(),placeholder:z("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),h.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:St.length===0?h.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:z("contextMenu.moveToEmpty")}):St.map(Ye=>h.jsx("button",{type:"button",onClick:async()=>{pt.teamId&&await K.teams.removeMember(pt.teamId,W.id),await K.teams.addMember(Ye.id,W.id,"agent"),O(),p(),gs(),Xt(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))})]})]})})(),!Ge&&!je&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{Cs(W.id,W.name,"agent",pt.teamId),Xt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.removeFromOrg")]})]})]})})(),Xe&&(()=>{const W=i.find(le=>le.id===Xe.userId);return!W||!B?null:h.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Xe.x,top:Xe.y},onClick:le=>le.stopPropagation(),children:h.jsxs("button",{onClick:()=>{Cs(W.id,W.name,"human"),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:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.removeFromOrg")]})})})(),U&&h.jsx(sw,{onClose:()=>D(!1),onCreate:async(W,le)=>{try{const{team:pe}=await K.teams.create(W,le);D(!1),O(),el(pe.id),setTimeout(()=>{document.querySelector(`[data-team-id="${pe.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>el(null),3e3)}catch(pe){ji(z("chat.failedToCreateTeam",{message:pe instanceof Error?pe.message:String(pe)}),"error")}}}),se&&h.jsx(rw,{onClose:()=>{F(!1),x?.()},onAdd:async(W,le,pe)=>{const{inviteToken:je}=await K.users.create(W,le,void 0,pe);return x?.(),{inviteToken:je}}}),G!==null&&h.jsx(iw,{teamId:G,ungrouped:H,onClose:()=>ee(null),onAdd:async(W,le)=>{await K.teams.addMember(G,W,le),ee(null),O(),gs()}}),we&&h.jsx(nw,{onClose:()=>Ae(!1),onConnected:()=>{Ae(!1),p(),O()}}),bt&&(()=>{const W=o.find(le=>le.id===bt.gcId);return W?h.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:bt.x,top:bt.y},onClick:le=>le.stopPropagation(),children:[W.type==="custom"&&h.jsxs("button",{onClick:()=>{ot(null),k?k(W.channelKey):g(W.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),z("contextMenu.manageMembers")]}),h.jsxs("button",{onClick:async()=>{ot(null),on(z("modals.deleteGroupChat.title"),z("modals.deleteGroupChat.message",{name:W.name}),async()=>{await K.groupChats.delete(W.id),y()},z("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("modals.deleteGroupChat.menuLabel")]})]}):null})(),xe&&h.jsx(ow,{agents:t,humans:i,authUser:e,onClose:()=>me(!1),onCreate:async(W,le,pe,je)=>{await K.groupChats.create({name:W,memberIds:le,memberTypes:pe,memberNames:je,creatorId:e?.id,creatorName:e?.name}),me(!1),y()}}),ge&&h.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>He(null),children:h.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:W=>W.stopPropagation(),children:[h.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[h.jsx("h3",{className:"text-sm font-semibold",children:z(ge==="agent"?"chat.addAgent":"chat.newTeam")}),h.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:z("chat.methodChoiceSubtitle")})]}),h.jsxs("div",{className:"p-3 space-y-2",children:[h.jsxs("button",{onClick:()=>{const W=ge;He(null);const le=t.find(pe=>pe.role==="secretary")??t.find(pe=>pe.name?.toLowerCase().includes("secretary"));le?(f(le.id),Qr.navigate(Kt.TEAM,{agentId:le.id,prefillMessage:z(W==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):W==="agent"?Qr.navigate(Kt.STORE):D(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[h.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),h.jsx("path",{d:"M20 3v4"}),h.jsx("path",{d:"M22 5h-4"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:z("chat.methodSecretary")}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:z("chat.methodSecretaryDesc")})]}),h.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:z("chat.recommended")})]}),h.jsxs("button",{onClick:()=>{const W=ge;He(null),W==="agent"?Qr.navigate(Kt.STORE):D(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[h.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:z("chat.methodManual")}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:z(ge==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),h.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:h.jsx("button",{onClick:()=>He(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:z("common:cancel")})})]})}),Lr&&h.jsx(_o,{title:Lr.title,message:Lr.message,confirmLabel:Lr.confirmLabel,checkboxes:Lr.checkboxes,onConfirm:W=>{Lr.onConfirm(W),Ri(null)},onCancel:()=>Ri(null)}),Qo&&h.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${Qo.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:Qo.message})]})});function Jm({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:c,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:g,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:m,unreadByAgent:O,width:p,onResizeStart:x,focused:y}){const{t:_}=At(["team","common"]),k=nh(),w=Ef(Kt.TEAM),S=r?.role==="owner"||r?.role==="admin",Q=C.useMemo(()=>e.filter(F=>F.teamId===s.id),[e,s.id]),N=C.useMemo(()=>{const F=new Set((s.members??[]).filter(G=>G.type==="human").map(G=>G.id));return t.filter(G=>F.has(G.id))},[s.members,t]),L=i&&n==="channel"&&o===i.channelKey,$=C.useMemo(()=>{const F=[];i&&F.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const G of Q)F.push({kind:"agent",id:`agent:${G.id}`,agentId:G.id});for(const G of N)F.push({kind:"dm",id:`dm:${G.id}`,userId:G.id});return F},[i,Q,N]),j=C.useRef($);j.current=$;const I=C.useCallback(F=>{F.kind==="channel"?u(F.channelKey):F.kind==="agent"?d(F.agentId):f(F.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${F.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);C.useEffect(()=>{if(!w)return;const F=G=>{if((k?.keyboardPane??"content")!=="l2"||G.metaKey||G.ctrlKey||G.altKey||$x(G.target))return;const we=G.key.length===1?G.key.toLowerCase():G.key;if(we==="h"||we==="ArrowLeft"){G.preventDefault(),G.stopPropagation(),k?.setKeyboardPane("l1");return}if(we==="l"||we==="ArrowRight"){G.preventDefault(),G.stopPropagation();return}const Ae=we==="j"||we==="ArrowDown"?1:we==="k"||we==="ArrowUp"?-1:0;if(!Ae)return;G.preventDefault(),G.stopPropagation();const xe=j.current;if(xe.length===0)return;let me=-1;n==="channel"?me=xe.findIndex(He=>He.kind==="channel"&&He.channelKey===o):n==="direct"?me=xe.findIndex(He=>He.kind==="agent"&&He.agentId===a):n==="dm"&&l&&(me=xe.findIndex(He=>He.kind==="dm"&&He.userId===l)),me<0&&(me=Ae>0?-1:0);const ge=Math.max(0,Math.min(xe.length-1,me+Ae));I(xe[ge])};return document.addEventListener("keydown",F,!0),()=>document.removeEventListener("keydown",F,!0)},[w,k,n,o,a,l,I]);const V=F=>F?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[Z,z]=C.useState(null),[J,T]=C.useState(!1),[A,B]=C.useState(""),[q,H]=C.useState(null),te=(F,G,ee,we,Ae)=>{H({title:F,message:G,onConfirm:ee,confirmLabel:we,checkboxes:Ae})},ue=C.useCallback((F,G=176,ee=220)=>{const we=window.innerWidth,Ae=window.innerHeight,xe=8;let me=F.clientX,ge=F.clientY;return me+G>we-xe&&(me=Math.max(xe,we-G-xe)),ge+ee>Ae-xe&&(ge=Math.max(xe,Ae-ee-xe)),me=Math.max(xe,Math.min(me,we-G-xe)),ge=Math.max(xe,Math.min(ge,Ae-ee-xe)),{x:me,y:ge}},[]);C.useEffect(()=>{if(!Z)return;const F=()=>z(null),G=setTimeout(()=>document.addEventListener("click",F),0);return()=>{clearTimeout(G),document.removeEventListener("click",F)}},[Z]);const ke=C.useCallback(async(F,G)=>{G==="offline"?await K.agents.start(F):await K.agents.stop(F),b()},[b]),U=C.useCallback(async F=>{await K.teams.update(s.id,{managerId:F,managerType:"agent"}),m()},[s.id,m]),D=C.useCallback(async F=>{await K.teams.removeMember(s.id,F),m(),b()},[s.id,m,b]),se=C.useCallback(async(F,G)=>{await K.teams.removeMember(s.id,F),await K.teams.addMember(G,F,"agent"),m(),b()},[s.id,m,b]);return h.jsxs(h.Fragment,{children:[h.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:p!=null?{width:p}:{width:260},children:[h.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[h.jsx("button",{onClick:g,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:_("common:back",{defaultValue:"Back"}),children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),h.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&h.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&h.jsxs("div",{className:"mb-3",children:[h.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:_("chat.groupChat",{defaultValue:"Group Chat"})}),h.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${V(!!L)}`,children:[h.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),h.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:_("chat.members_other",{count:i.memberCount||Q.length+N.length})})]})]})]}),Q.length>0&&h.jsxs("div",{className:"mb-3",children:[h.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.agents",{defaultValue:"Agents"}),h.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:Q.length})]}),Q.map(F=>{const G=n==="direct"&&a===F.id,ee=s.managerId===F.id,we=F.status==="offline",Ae=F.status==="idle"?"bg-green-500":F.status==="working"?"bg-blue-500 animate-pulse":F.status==="error"?"bg-red-500":"bg-gray-600";return h.jsxs("button",{"data-l2-nav-id":`agent:${F.id}`,onClick:()=>d(F.id),onContextMenu:xe=>{if(!S)return;xe.preventDefault();const me=ue(xe);T(!1),B(""),z({agentId:F.id,...me})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${we?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${V(G)}`,children:[h.jsx(js,{name:F.name,avatarUrl:F.avatarUrl,size:28,bgClass:we?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:F.name}),ee&&h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:h.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),we&&h.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:_("common:status.offline")})]}),h.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:F.role||" "})]}),(O?.get(F.id)??0)>0&&h.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(F.id)}),h.jsx("span",{title:F.status,onClick:xe=>{xe.stopPropagation(),v(F.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${Ae}`})]},F.id)})]}),N.length>0&&h.jsxs("div",{className:"mb-3",children:[h.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[_("chat.people"),h.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:N.length})]}),N.map(F=>{const G=F.id===r?.id,ee=n==="dm"&&l===F.id;return h.jsxs("button",{"data-l2-nav-id":`dm:${F.id}`,onClick:()=>f(F.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 ${V(ee)}`,children:[h.jsx(js,{name:F.name,avatarUrl:F.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),h.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[h.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[F.name,G?` (${_("chat.you",{defaultValue:"You"})})`:""]}),h.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:F.email||F.role})]}),h.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},F.id)})]}),Q.length===0&&N.length===0&&h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:_("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:h.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),Z&&(()=>{const F=Q.find(ee=>ee.id===Z.agentId);if(!F||!S)return null;const G=s.managerId===F.id;return h.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:Z.x,top:Z.y,maxHeight:Math.max(160,window.innerHeight-Z.y-8)},onClick:ee=>ee.stopPropagation(),children:[h.jsxs("button",{onClick:()=>{z(null),v(F.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),_("contextMenu.viewProfile")]}),F.status==="offline"?h.jsxs("button",{onClick:()=>{ke(F.id,"offline"),z(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),_("contextMenu.start")]}):h.jsxs("button",{onClick:()=>{ke(F.id,F.status??"idle"),z(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),_("contextMenu.stop")]}),!G&&h.jsxs("button",{onClick:()=>{U(F.id),z(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:h.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),_("contextMenu.setAsManager")]}),h.jsxs("button",{onClick:()=>{D(F.id),z(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"9 14 4 9 9 4"}),h.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),_("contextMenu.removeFromTeam")]}),(()=>{const ee=c.filter(xe=>xe.id!==s.id);if(ee.length===0)return null;const we=A.trim().toLowerCase(),Ae=we?ee.filter(xe=>xe.name.toLowerCase().includes(we)):ee;return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{type:"button",onClick:()=>T(xe=>!xe),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M5 12h14"}),h.jsx("path",{d:"M12 5l7 7-7 7"})]}),h.jsx("span",{className:"flex-1",children:_("contextMenu.moveTo")}),h.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${J?"rotate-180":""}`,children:h.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),J&&h.jsxs("div",{className:"px-2 pb-1.5",onClick:xe=>xe.stopPropagation(),children:[h.jsx("input",{autoFocus:!0,value:A,onChange:xe=>B(xe.target.value),onKeyDown:xe=>xe.stopPropagation(),placeholder:_("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),h.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Ae.length===0?h.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:_("contextMenu.moveToEmpty")}):Ae.map(xe=>h.jsx("button",{type:"button",onClick:()=>{se(F.id,xe.id),z(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:xe.name,children:xe.name},xe.id))})]})]})})(),h.jsx("div",{className:"border-t border-border-default/50 my-1"}),h.jsxs("button",{onClick:()=>{te(`${_("common:remove")} "${F.name}"?`,_("modals.removeAgent.message"),async ee=>{const we=ee?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await K.agents.remove(F.id,{purgeFiles:we}),b(),z(null)},_("common:remove"),[{id:"purgeFiles",label:_("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[h.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),_("contextMenu.removeFromOrg")]})]})})(),q&&h.jsx(_o,{title:q.title,message:q.message,confirmLabel:q.confirmLabel,checkboxes:q.checkboxes,onConfirm:F=>{q.onConfirm(F),H(null)},onCancel:()=>H(null)})]})}function yu(){return yu=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},yu.apply(null,arguments)}function lw(s,e){if(s==null)return{};var t={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(e.indexOf(r)!==-1)continue;t[r]=s[r]}return t}let Su=[],Nx=[];(()=>{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<s.length;e++)(e%2?Nx:Su).push(t=t+s[e])})();function cw(s){if(s<768)return!1;for(let e=0,t=Su.length;;){let r=e+t>>1;if(s<Su[r])t=r;else if(s>=Nx[r])e=r+1;else return!0;if(e==t)return!1}}function eg(s){return s>=127462&&s<=127487}const tg=8205;function hw(s,e,t=!0,r=!0){return(t?Dx:dw)(s,e,r)}function Dx(s,e,t){if(e==s.length)return e;e&&Ix(s.charCodeAt(e))&&Bx(s.charCodeAt(e-1))&&e--;let r=ud(s,e);for(e+=sg(r);e<s.length;){let i=ud(s,e);if(r==tg||i==tg||t&&cw(i))e+=sg(i),r=i;else if(eg(i)){let n=0,a=e-2;for(;a>=0&&eg(ud(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function dw(s,e,t){for(;e>1;){let r=Dx(s,e-2,t);if(r<e)return r;e--}return 0}function ud(s,e){let t=s.charCodeAt(e);if(!Bx(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return Ix(r)?(t-55296<<10)+(r-56320)+65536:t}function Ix(s){return s>=56320&&s<57344}function Bx(s){return s>=55296&&s<56320}function sg(s){return s<65536?1:2}let kt=class Wx{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,r){[e,t]=fo(this,e,t);let i=[];return this.decompose(0,e,i,2),r.length&&r.decompose(0,r.length,i,3),this.decompose(t,this.length,i,1),Zr.from(i,this.length-(t-e)+r.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=fo(this,e,t);let r=[];return this.decompose(e,t,r,0),Zr.from(r,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),r=this.length-this.scanIdentical(e,-1),i=new la(this),n=new la(e);for(let a=t,o=t;;){if(i.next(a),n.next(a),a=0,i.lineBreak!=n.lineBreak||i.done!=n.done||i.value!=n.value)return!1;if(o+=i.value.length,i.done||o>=r)return!0}}iter(e=1){return new la(this,e)}iterRange(e,t=this.length){return new Xx(this,e,t)}iterLines(e,t){let r;if(e==null)r=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;r=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new qx(r)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Wx.empty:e.length<=32?new is(e):Zr.from(is.split(e,[]))}};class is extends kt{constructor(e,t=uw(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.text[n],o=i+a.length;if((t?r:o)>=e)return new fw(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new is(rg(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=lc(n.text,a.text.slice(),0,n.length);if(o.length<=32)r.push(new is(o,a.length+n.length));else{let l=o.length>>1;r.push(new is(o.slice(0,l)),new is(o.slice(l)))}}else r.push(n)}replace(e,t,r){if(!(r instanceof is))return super.replace(e,t,r);[e,t]=fo(this,e,t);let i=lc(this.text,lc(r.text,rg(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new is(i,n):Zr.from(is.split(i,[]),n)}sliceString(e,t=this.length,r=`
@@ -52,7 +52,7 @@ WARNING: This link could potentially be dangerous`)){const O=window.open();if(O)
52
52
  """
53
53
  ${he}
54
54
  """`}},[ue,se,p,s]),G=C.useCallback((he,Xe)=>{!he.trim()||!i||(i(F(he.trim(),Xe)),$(null),window.getSelection()?.removeAllRanges(),q.current?.clearSelection())},[i,F]),ee=C.useCallback(async()=>{if(!i||s.kind!=="terminal")return;const he=(await q.current?.getRecentOutput(80))?.trim();if(!he)return;const Xe=he.length>40?`${he.slice(0,24)}…${he.slice(-12)}`:he;i({label:`⌘ ${Xe}`,content:["[terminal-output]",`Terminal: ${s.title||"Terminal"} (${s.terminalId})`,s.cwd?`Cwd: ${s.cwd}`:"",'"""',he,'"""'].filter(Boolean).join(`
55
- `)})},[i,s]);C.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),Xe=Oe=>{if(!(he?Oe.metaKey&&!Oe.ctrlKey:Oe.ctrlKey&&!Oe.metaKey)||!Oe.shiftKey||Oe.altKey||Oe.key.toLowerCase()!=="a")return;const Ne=q.current?.getSelection()?.trim();Ne&&(Oe.preventDefault(),G(Ne))};return window.addEventListener("keydown",Xe),()=>window.removeEventListener("keydown",Xe)},[s.kind,i,G]);const we=C.useCallback(he=>{if(!he.text.trim()||!i)return;const Xe=T.current?.querySelector("iframe")?.getBoundingClientRect(),Oe=(Xe?.left??0)+he.rect.x+he.rect.width/2,Ke=(Xe?.top??0)+he.rect.y;$({x:Oe,y:Ke,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);C.useEffect(()=>{const he=T.current;if(!he||!i)return;const Xe=()=>{requestAnimationFrame(()=>{const Ke=window.getSelection(),Ne=Ke?.toString().trim();if(!Ne||!Ke?.rangeCount){$(null);return}const bt=Ke.getRangeAt(0);if(!he.contains(bt.commonAncestorContainer)){$(null);return}const ot=bt.getBoundingClientRect();$({x:ot.left+ot.width/2,y:ot.top,text:Ne})})},Oe=Ke=>{const Ne=document.getElementById("right-panel-selection-toolbar");Ne&&Ne.contains(Ke.target)||$(null)};return he.addEventListener("mouseup",Xe),document.addEventListener("mousedown",Oe),()=>{he.removeEventListener("mouseup",Xe),document.removeEventListener("mousedown",Oe)}},[i,x.mode]);const Ae=()=>{K.files.reveal(ue).catch(()=>{})},xe=()=>{navigator.clipboard?.writeText(ue).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},me=C.useCallback(async()=>{if(s.kind==="deliverable"){Qr.navigate(Kt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let Xe=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const Oe=await window.markusDesktop.browser.getState(s.browserId);if(Oe.ok){if(Oe.directoryPath){await K.system.openPath(Oe.directoryPath).catch(()=>K.files.reveal(Oe.directoryPath));return}Oe.url&&Oe.url!=="about:blank"&&(Xe=Oe.url)}}catch{}if(!Xe||Xe==="about:blank")return;if(/^https?:\/\//i.test(Xe)||/^file:\/\//i.test(Xe)){Tl(Xe);return}await K.system.openPath(Xe).catch(()=>Tl(ox(Xe)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){Tl(he);return}await K.system.openPath(he).catch(()=>Tl(ox(he)))}},[s]),ge=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,He=s.kind==="deliverable"?p("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):p("common:openInSystemBrowser"),nt=!!ue&&!sc(ue)&&(s.kind==="file"||s.kind==="deliverable"),Ct=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!ue&&!sc(ue)&&!s.deliverable.artifactType,pt=s.kind==="deliverable"?{...s.deliverable,hubShareId:Q?.id??s.deliverable.hubShareId??null,shareStatus:Q?.status??s.deliverable.shareStatus??null,shareUrl:Q?.url??s.deliverable.shareUrl??null,shareVisibility:Q?.visibility??s.deliverable.shareVisibility??null}:null,Xt=C.useCallback(he=>{N(he)},[]),wt=C.useMemo(()=>W_(Lm,Rf.getUrl()),[]),Et=s.kind==="deliverable"?s.deliverable.id:null;C.useEffect(()=>{if(!Et||!Lm())return;let he=!1;const Xe=async()=>{try{const Ke=await wt.listMine();if(he)return;const Ne=s.kind==="deliverable"?s.deliverable:null;if(!Ne)return;const bt=Ne.hubShareId&&Ke.find(ts=>ts.id===Ne.hubShareId)||Ke.find(ts=>ts.localId===Ne.id);if(!bt)return;N(ts=>ts&&ts.id===bt.id&&ts.status===bt.status?ts:bt);const ot={hubShareId:Ne.hubShareId??bt.id??null,shareStatus:bt.status??null,shareUrl:bt.url??null,shareVisibility:Ne.shareVisibility??bt.visibility??null};(Ne.shareStatus!==ot.shareStatus||Ne.hubShareId!==ot.hubShareId||Ne.shareUrl!==ot.shareUrl||Ne.shareVisibility!==ot.shareVisibility)&&Ne.id&&K.deliverables.update(Ne.id,ot).catch(ts=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ts)})}catch{}};Xe();const Oe=setInterval(Xe,3e4);return()=>{he=!0,clearInterval(Oe)}},[wt,Et,s]);const Pt=pt?.shareStatus??null;return h.jsxs(h.Fragment,{children:[!d&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:h.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),h.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[h.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[h.jsx("button",{type:"button",onClick:()=>v("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":g==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),h.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),h.jsx("button",{type:"button",onClick:()=>v("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":g==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 17 10 11 4 5"}),h.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||c?h.jsxs("div",{"data-no-drag":!0,ref:A,role:"tablist",className:"flex-1 min-w-0 flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-thin",onWheel:he=>{const Xe=he.currentTarget;Xe.scrollWidth<=Xe.clientWidth||Math.abs(he.deltaY)<=Math.abs(he.deltaX)||(Xe.scrollLeft+=he.deltaY,he.preventDefault())},children:[n?.map(he=>{const Xe=he.id===a,Oe=he.payload.kind==="url"?he.payload.pageId:void 0,Ke=he.payload.kind==="terminal"?he.payload.terminalId:void 0,Ne=Oe!=null?j[Oe]:Ke?V[Ke]:void 0,bt=Ne?`${he.title} — ${p("common:browserTabControlledBy",{name:Ne.agentName})}`:he.title;return h.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${Xe?Ne?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Ne?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[h.jsxs("button",{type:"button",role:"tab","aria-selected":Xe,ref:Xe?B:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:bt,onPointerDown:ot=>{ot.button===0&&(he.id!==a&&!te()||o?.(he.id))},onClick:()=>{he.id!==a&&!te()||o?.(he.id)},children:[Ne&&h.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:p("common:browserTabControlledBy",{name:Ne.agentName}),children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),h.jsx("span",{className:"truncate",children:Ne.agentName})]}),h.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&h.jsx("button",{type:"button",onPointerDown:ot=>{ot.button===0&&(ot.preventDefault(),ot.stopPropagation(),!(he.id===a&&!te())&&l(he.id))},onClick:ot=>{ot.preventDefault(),ot.stopPropagation(),!(he.id===a&&!te())&&l(he.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${Xe?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:p("common:closeTab",{defaultValue:"Close tab"}),"aria-label":p("common:closeTab",{defaultValue:"Close tab"}),children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),c&&h.jsx("button",{type:"button",onClick:c,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):h.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:ue||ke,children:ke}),h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&i&&h.jsx("button",{type:"button",onClick:()=>{ee()},title:p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),Ct&&h.jsxs("button",{type:"button",onClick:()=>S(!0),title:p("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":p("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Pt==="published"?"text-green-500 hover:text-green-400":Pt==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"18",cy:"5",r:"3"}),h.jsx("circle",{cx:"6",cy:"12",r:"3"}),h.jsx("circle",{cx:"18",cy:"19",r:"3"}),h.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),h.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(Pt==="published"||Pt==="pending_review"||Pt==="rejected")&&h.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${Pt==="published"?"bg-green-500":Pt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),ge&&h.jsx("button",{type:"button",onClick:()=>{me()},title:He,"aria-label":He,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),nt&&h.jsx("button",{onClick:Ae,title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&h.jsx("button",{onClick:u,title:d?p("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):p("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 14 10 14 10 20"}),h.jsx("polyline",{points:"20 10 14 10 14 4"}),h.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("polyline",{points:"9 21 3 21 3 15"}),h.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),h.jsx("button",{onClick:()=>{te()&&e()},title:p("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":p("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),h.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&h.jsxs("div",{className:"animate-pulse space-y-3",children:[h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),h.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[h.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M9 18V5l12-2v13"}),h.jsx("circle",{cx:"6",cy:"18",r:"3"}),h.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${xu(x.size)}`:""]})]})]}),h.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[h.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),h.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${xu(x.size)}`:""]})]}),x.mode==="binary"&&h.jsxs("div",{className:"space-y-4 py-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${xu(x.size)}`:""]})]})]}),x.reference&&h.jsx("div",{className:"flex items-center gap-2",children:h.jsx("button",{onClick:()=>{K.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="content"&&(()=>{const he=ue?ue.replace(/[/\\][^/\\]+$/,""):void 0,Xe=ue&&!sc(ue)?ue:"",Oe=x.format;return Xe&&(Oe==="code"||Oe==="json"||Oe==="text")?h.jsx("div",{ref:T,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(iS,{path:Xe,initialContent:x.content,language:Wp(Xe,Oe),onDirtyChange:J})}):Xe&&(Oe==="markdown"||Oe==="html")?h.jsx("div",{ref:T,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(YA,{path:Xe,content:x.content,format:Oe,basePath:he,onHtmlSelection:we,onDirtyChange:J})}):h.jsx("div",{ref:T,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:h.jsx(vu,{content:x.content,format:Oe,className:"text-fg-secondary text-sm",onHtmlSelection:we,basePath:he})})})(),x.mode==="artifact"&&h.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:h.jsx(vu,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(KA,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(aM,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:q,onMeta:b,onOpenUrl:m,onOpenPath:O,onSelection:he=>{if(!he||!i){$(null);return}$({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="unpreviewable"&&h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?p("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):p("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:Ae,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),h.jsx("button",{onClick:Ae,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:p("common:open",{defaultValue:"Open"})}),h.jsx("button",{onClick:xe,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${_?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:_?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},D)]}),L&&i&&h.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:L.x,top:L.y-8},children:h.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),G(L.text,L.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),w&&pt&&h.jsx(X_,{item:pt,onClose:()=>S(!1),onShared:Xt})]})}const uM=C.lazy(()=>Mx(()=>import("./index-CiAGgfZx.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Xp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Qf(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function cS(s,e){const r={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[s];return r?e(r):s}const hS={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function Kn(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function ax({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:c}=At(["agent","common"]),d=jf(),[u,f]=C.useState(null),[g,v]=C.useState(null),[b,m]=C.useState(r??"overview"),O=o&&l?l:b,[p,x]=C.useState(null),y=C.useMemo(()=>Xp.map($=>({...$,label:c(`agent:tabs.${$.key}`)})),[c]),_=C.useMemo(()=>y.map($=>({id:$.key})),[y]),k=C.useMemo(()=>({onSwipeOutLeft:i}),[i]),w=jx(_,b,m,k),S=C.useRef(null);C.useEffect(()=>{const $=S.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[b]);const Q=C.useCallback(()=>{K.agents.get(s).then(f).catch(()=>{})},[s]);if(C.useEffect(()=>(m(r??"overview"),x(null),Q(),K.externalAgents.list().then(j=>{const I=j.agents.find(V=>V.markusAgentId===s);x(I??null)}).catch(()=>{}),yt.on("agent:update",j=>{j.payload.agentId===s&&Q()})),[s,Q]),!u)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:c("agent:profilePage.loadingAgent")});const N=hS[u.state.status]??"bg-gray-500",L=a?.role==="owner"||a?.role==="admin";return o?h.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:h.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(lx,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:L}),h.jsx("div",{className:"mt-6",children:h.jsx(Sx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:L,onAgentStateChange:Q})})]}),O==="files"&&h.jsx(dx,{agentId:s}),O==="tools"&&h.jsx(ux,{tools:u.tools??[],agent:u}),O==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(px,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(fx,{agentId:s})})]}),O==="deliverables"&&h.jsx(_x,{agentId:s})]})}):h.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(js,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:u.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${N}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:cS(u.state.status,c)}),p&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:c("agent:profilePage.badges.external")}),u.agentRole==="manager"&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:c("agent:profilePage.badges.manager")})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),h.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&h.jsxs("button",{onClick:()=>Qr.navigate(Kt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[h.jsx("span",{children:"◈"})," ",c("agent:profilePage.chat")]}),L&&h.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await K.agents.getFilesMap(s),j={type:"agent",name:Ex(u.name,u.name),displayName:u.name,version:"1.0.0",description:u.roleDescription??u.role,author:"",category:"general",tags:[],agent:{roleName:u.role,agentRole:u.agentRole},dependencies:{skills:u.skills??[]}};await Rf.publishViaProxy({itemType:"agent",name:u.name,description:j.description,category:"general",config:j,files:$}),v({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){v({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishFailed",{error:String($)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:c("agent:profilePage.publishTitle"),children:[h.jsx("span",{children:"↑"})," ",c("agent:profilePage.hub")]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),h.jsx("div",{ref:S,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>h.jsxs("button",{onClick:()=>m($.key),"data-active":b===$.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${b===$.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[h.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),h.jsxs("div",{className:"p-5",onTouchStart:d?w.onTouchStart:void 0,onTouchEnd:d?w.onTouchEnd:void 0,children:[(b==="overview"||b==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(lx,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:L}),h.jsx("div",{className:"mt-6",children:h.jsx(Sx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:L,onAgentStateChange:Q})})]}),b==="files"&&h.jsx(dx,{agentId:s}),b==="tools"&&h.jsx(ux,{tools:u.tools??[],agent:u}),b==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(px,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(fx,{agentId:s})})]}),b==="deliverables"&&h.jsx(_x,{agentId:s})]}),g&&h.jsx(_o,{alertOnly:!0,variant:g.variant??"primary",title:g.title,message:g.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function lx({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i}){const[n,a]=C.useState(null),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(null),[g,v]=C.useState(""),[b,m]=C.useState([]);C.useEffect(()=>{K.usage.agents().then(w=>{const S=w.agents.find(Q=>Q.agentId===s.id);S&&a(S)}).catch(()=>{}),K.agents.getRecentActivities(s.id).then(w=>l(w.activities)).catch(()=>{}),K.system.storage().then(w=>{v(w.dataDir+"/agents/"+s.id);const S=w.agents.find(Q=>Q.id===s.id);S&&f(S)}).catch(()=>{}),s.state.activeTaskIds?.length&&K.tasks.list({assignedAgentId:s.id}).then(w=>{m(w.tasks.filter(S=>s.state.activeTaskIds?.includes(S.id)))}).catch(()=>{})},[s.id,s.state.activeTaskIds]);const O=()=>{s.state.status==="offline"?K.agents.start(s.id).then(e):K.agents.stop(s.id).then(e)},p=C.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),x=C.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return h.jsxs("div",{className:"space-y-4",children:[h.jsx(as,{title:r("agent:profilePage.overview.identity"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.connectionStatus"),children:h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.externalAgentDetails"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.syncContextTitle"),children:h.jsx("div",{className:"space-y-1.5",children:x.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:w.field}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:w.desc})]},w.field))})}),h.jsx(as,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:h.jsx("div",{className:"space-y-1.5",children:p.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${w.method==="POST"?"text-amber-600":"text-green-600"}`,children:w.method}),h.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:w.path}),h.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:w.desc})]},w.path))})})]});const y=o.filter(w=>w.type==="heartbeat").length,_=o.filter(w=>w.type==="chat").length,k=s.state.activeTaskIds?.length??0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${hS[s.state.status]||"bg-gray-500"}`}),h.jsx("span",{className:`text-sm font-semibold ${s.state.status==="idle"?"text-green-500":s.state.status==="working"?"text-blue-400":s.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:cS(s.state.status,r)})]}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Kn(s.state.tokensUsedToday)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(k),color:k>0?"blue":void 0}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),i&&h.jsx("button",{onClick:O,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&h.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&h.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),h.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:wc(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&k>0&&h.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:h.jsx("div",{className:"space-y-1",children:b.map(w=>h.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),h.jsx("span",{className:"text-fg-secondary truncate flex-1",children:w.title}),h.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Qf(w.status,r)})]},w.id))})}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Kn(n.totalTokens)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.promptTokens"),value:Kn(n.promptTokens)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.completionTokens"),value:Kn(n.completionTokens)}),h.jsx(fs,{label:"CU Used",value:Kn(n.cuUsed??0)})]})]}),u&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.storage"),value:xx(u.size)}),u.subItems.filter(w=>w.size>0).map(w=>h.jsx(fs,{label:w.name,value:xx(w.size)},w.name)),h.jsxs("button",{onClick:()=>{K.system.openPath(g)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),y>0&&h.jsx(as,{title:r("agent:profilePage.overview.recentHeartbeats"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:y})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="heartbeat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s.id,activityId:w.id})})]},w.id)})})}),_>0&&h.jsx(as,{title:r("agent:profilePage.overview.recentA2A"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:_})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="chat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s.id,activityId:w.id})})]},w.id)})})})]})}function fM(s,e){const t=s.split(`
55
+ `)})},[i,s]);C.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),Xe=Oe=>{if(!(he?Oe.metaKey&&!Oe.ctrlKey:Oe.ctrlKey&&!Oe.metaKey)||!Oe.shiftKey||Oe.altKey||Oe.key.toLowerCase()!=="a")return;const Ne=q.current?.getSelection()?.trim();Ne&&(Oe.preventDefault(),G(Ne))};return window.addEventListener("keydown",Xe),()=>window.removeEventListener("keydown",Xe)},[s.kind,i,G]);const we=C.useCallback(he=>{if(!he.text.trim()||!i)return;const Xe=T.current?.querySelector("iframe")?.getBoundingClientRect(),Oe=(Xe?.left??0)+he.rect.x+he.rect.width/2,Ke=(Xe?.top??0)+he.rect.y;$({x:Oe,y:Ke,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);C.useEffect(()=>{const he=T.current;if(!he||!i)return;const Xe=()=>{requestAnimationFrame(()=>{const Ke=window.getSelection(),Ne=Ke?.toString().trim();if(!Ne||!Ke?.rangeCount){$(null);return}const bt=Ke.getRangeAt(0);if(!he.contains(bt.commonAncestorContainer)){$(null);return}const ot=bt.getBoundingClientRect();$({x:ot.left+ot.width/2,y:ot.top,text:Ne})})},Oe=Ke=>{const Ne=document.getElementById("right-panel-selection-toolbar");Ne&&Ne.contains(Ke.target)||$(null)};return he.addEventListener("mouseup",Xe),document.addEventListener("mousedown",Oe),()=>{he.removeEventListener("mouseup",Xe),document.removeEventListener("mousedown",Oe)}},[i,x.mode]);const Ae=()=>{K.files.reveal(ue).catch(()=>{})},xe=()=>{navigator.clipboard?.writeText(ue).then(()=>{k(!0),setTimeout(()=>k(!1),1500)}).catch(()=>{})},me=C.useCallback(async()=>{if(s.kind==="deliverable"){Qr.navigate(Kt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let Xe=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const Oe=await window.markusDesktop.browser.getState(s.browserId);if(Oe.ok){if(Oe.directoryPath){await K.system.openPath(Oe.directoryPath).catch(()=>K.files.reveal(Oe.directoryPath));return}Oe.url&&Oe.url!=="about:blank"&&(Xe=Oe.url)}}catch{}if(!Xe||Xe==="about:blank")return;if(/^https?:\/\//i.test(Xe)||/^file:\/\//i.test(Xe)){Tl(Xe);return}await K.system.openPath(Xe).catch(()=>Tl(ox(Xe)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){Tl(he);return}await K.system.openPath(he).catch(()=>Tl(ox(he)))}},[s]),ge=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,He=s.kind==="deliverable"?p("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):p("common:openInSystemBrowser"),nt=!!ue&&!sc(ue)&&(s.kind==="file"||s.kind==="deliverable"),Ct=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!ue&&!sc(ue)&&!s.deliverable.artifactType,pt=s.kind==="deliverable"?{...s.deliverable,hubShareId:Q?.id??s.deliverable.hubShareId??null,shareStatus:Q?.status??s.deliverable.shareStatus??null,shareUrl:Q?.url??s.deliverable.shareUrl??null,shareVisibility:Q?.visibility??s.deliverable.shareVisibility??null}:null,Xt=C.useCallback(he=>{N(he)},[]),wt=C.useMemo(()=>W_(Lm,Rf.getUrl()),[]),Et=s.kind==="deliverable"?s.deliverable.id:null;C.useEffect(()=>{if(!Et||!Lm())return;let he=!1;const Xe=async()=>{try{const Ke=await wt.listMine();if(he)return;const Ne=s.kind==="deliverable"?s.deliverable:null;if(!Ne)return;const bt=Ne.hubShareId&&Ke.find(ts=>ts.id===Ne.hubShareId)||Ke.find(ts=>ts.localId===Ne.id);if(!bt)return;N(ts=>ts&&ts.id===bt.id&&ts.status===bt.status?ts:bt);const ot={hubShareId:Ne.hubShareId??bt.id??null,shareStatus:bt.status??null,shareUrl:bt.url??null,shareVisibility:Ne.shareVisibility??bt.visibility??null};(Ne.shareStatus!==ot.shareStatus||Ne.hubShareId!==ot.hubShareId||Ne.shareUrl!==ot.shareUrl||Ne.shareVisibility!==ot.shareVisibility)&&Ne.id&&K.deliverables.update(Ne.id,ot).catch(ts=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ts)})}catch{}};Xe();const Oe=setInterval(Xe,3e4);return()=>{he=!0,clearInterval(Oe)}},[wt,Et,s]);const Pt=pt?.shareStatus??null;return h.jsxs(h.Fragment,{children:[!d&&h.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:h.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),h.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[h.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[h.jsx("button",{type:"button",onClick:()=>v("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":g==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),h.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),h.jsx("button",{type:"button",onClick:()=>v("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":g==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${g==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 17 10 11 4 5"}),h.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||c?h.jsxs("div",{"data-no-drag":!0,ref:A,role:"tablist",className:"flex-1 min-w-0 flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-thin",onWheel:he=>{const Xe=he.currentTarget;Xe.scrollWidth<=Xe.clientWidth||Math.abs(he.deltaY)<=Math.abs(he.deltaX)||(Xe.scrollLeft+=he.deltaY,he.preventDefault())},children:[n?.map(he=>{const Xe=he.id===a,Oe=he.payload.kind==="url"?he.payload.pageId:void 0,Ke=he.payload.kind==="terminal"?he.payload.terminalId:void 0,Ne=Oe!=null?j[Oe]:Ke?V[Ke]:void 0,bt=Ne?`${he.title} — ${p("common:browserTabControlledBy",{name:Ne.agentName})}`:he.title;return h.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${Xe?Ne?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Ne?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[h.jsxs("button",{type:"button",role:"tab","aria-selected":Xe,ref:Xe?B:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:bt,onPointerDown:ot=>{ot.button===0&&(he.id!==a&&!te()||o?.(he.id))},onClick:()=>{he.id!==a&&!te()||o?.(he.id)},children:[Ne&&h.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:p("common:browserTabControlledBy",{name:Ne.agentName}),children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),h.jsx("span",{className:"truncate",children:Ne.agentName})]}),h.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&h.jsx("button",{type:"button",onPointerDown:ot=>{ot.button===0&&(ot.preventDefault(),ot.stopPropagation(),!(he.id===a&&!te())&&l(he.id))},onClick:ot=>{ot.preventDefault(),ot.stopPropagation(),!(he.id===a&&!te())&&l(he.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${Xe?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:p("common:closeTab",{defaultValue:"Close tab"}),"aria-label":p("common:closeTab",{defaultValue:"Close tab"}),children:h.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),c&&h.jsx("button",{type:"button",onClick:c,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):h.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:ue||ke,children:ke}),h.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&i&&h.jsx("button",{type:"button",onClick:()=>{ee()},title:p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":p("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),Ct&&h.jsxs("button",{type:"button",onClick:()=>S(!0),title:p("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":p("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Pt==="published"?"text-green-500 hover:text-green-400":Pt==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"18",cy:"5",r:"3"}),h.jsx("circle",{cx:"6",cy:"12",r:"3"}),h.jsx("circle",{cx:"18",cy:"19",r:"3"}),h.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),h.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(Pt==="published"||Pt==="pending_review"||Pt==="rejected")&&h.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${Pt==="published"?"bg-green-500":Pt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),ge&&h.jsx("button",{type:"button",onClick:()=>{me()},title:He,"aria-label":He,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),nt&&h.jsx("button",{onClick:Ae,title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&h.jsx("button",{onClick:u,title:d?p("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):p("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"4 14 10 14 10 20"}),h.jsx("polyline",{points:"20 10 14 10 14 4"}),h.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polyline",{points:"15 3 21 3 21 9"}),h.jsx("polyline",{points:"9 21 3 21 3 15"}),h.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),h.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),h.jsx("button",{onClick:()=>{te()&&e()},title:p("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":p("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),h.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),h.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&h.jsxs("div",{className:"animate-pulse space-y-3",children:[h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),h.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),h.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&h.jsxs("div",{className:"flex flex-col items-center gap-2",children:[h.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:h.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M9 18V5l12-2v13"}),h.jsx("circle",{cx:"6",cy:"18",r:"3"}),h.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${xu(x.size)}`:""]})]})]}),h.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&h.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[h.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),h.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${xu(x.size)}`:""]})]}),x.mode==="binary"&&h.jsxs("div",{className:"space-y-4 py-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),h.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${xu(x.size)}`:""]})]})]}),x.reference&&h.jsx("div",{className:"flex items-center gap-2",children:h.jsx("button",{onClick:()=>{K.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="content"&&(()=>{const he=ue?ue.replace(/[/\\][^/\\]+$/,""):void 0,Xe=ue&&!sc(ue)?ue:"",Oe=x.format;return Xe&&(Oe==="code"||Oe==="json"||Oe==="text")?h.jsx("div",{ref:T,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(iS,{path:Xe,initialContent:x.content,language:Wp(Xe,Oe),onDirtyChange:J})}):Xe&&(Oe==="markdown"||Oe==="html")?h.jsx("div",{ref:T,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(YA,{path:Xe,content:x.content,format:Oe,basePath:he,onHtmlSelection:we,onDirtyChange:J})}):h.jsx("div",{ref:T,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:h.jsx(vu,{content:x.content,format:Oe,className:"text-fg-secondary text-sm",onHtmlSelection:we,basePath:he})})})(),x.mode==="artifact"&&h.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:h.jsx(vu,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(KA,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&h.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:h.jsx(aM,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:q,onMeta:b,onOpenUrl:m,onOpenPath:O,onSelection:he=>{if(!he||!i){$(null);return}$({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="unpreviewable"&&h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?p("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):p("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:Ae,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:p("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),h.jsx("button",{onClick:Ae,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:p("common:open",{defaultValue:"Open"})}),h.jsx("button",{onClick:xe,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${_?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:_?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},D)]}),L&&i&&h.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:L.x,top:L.y-8},children:h.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),G(L.text,L.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),w&&pt&&h.jsx(X_,{item:pt,onClose:()=>S(!1),onShared:Xt})]})}const uM=C.lazy(()=>Mx(()=>import("./index-B1VN5yM1.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Xp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Qf(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function cS(s,e){const r={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[s];return r?e(r):s}const hS={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function Kn(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function ax({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:c}=At(["agent","common"]),d=jf(),[u,f]=C.useState(null),[g,v]=C.useState(null),[b,m]=C.useState(r??"overview"),O=o&&l?l:b,[p,x]=C.useState(null),y=C.useMemo(()=>Xp.map($=>({...$,label:c(`agent:tabs.${$.key}`)})),[c]),_=C.useMemo(()=>y.map($=>({id:$.key})),[y]),k=C.useMemo(()=>({onSwipeOutLeft:i}),[i]),w=jx(_,b,m,k),S=C.useRef(null);C.useEffect(()=>{const $=S.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[b]);const Q=C.useCallback(()=>{K.agents.get(s).then(f).catch(()=>{})},[s]);if(C.useEffect(()=>(m(r??"overview"),x(null),Q(),K.externalAgents.list().then(j=>{const I=j.agents.find(V=>V.markusAgentId===s);x(I??null)}).catch(()=>{}),yt.on("agent:update",j=>{j.payload.agentId===s&&Q()})),[s,Q]),!u)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:c("agent:profilePage.loadingAgent")});const N=hS[u.state.status]??"bg-gray-500",L=a?.role==="owner"||a?.role==="admin";return o?h.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:h.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(lx,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:L}),h.jsx("div",{className:"mt-6",children:h.jsx(Sx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:L,onAgentStateChange:Q})})]}),O==="files"&&h.jsx(dx,{agentId:s}),O==="tools"&&h.jsx(ux,{tools:u.tools??[],agent:u}),O==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(px,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(fx,{agentId:s})})]}),O==="deliverables"&&h.jsx(_x,{agentId:s})]})}):h.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(js,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:u.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${N}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:cS(u.state.status,c)}),p&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:c("agent:profilePage.badges.external")}),u.agentRole==="manager"&&h.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:c("agent:profilePage.badges.manager")})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),h.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&h.jsxs("button",{onClick:()=>Qr.navigate(Kt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[h.jsx("span",{children:"◈"})," ",c("agent:profilePage.chat")]}),L&&h.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await K.agents.getFilesMap(s),j={type:"agent",name:Ex(u.name,u.name),displayName:u.name,version:"1.0.0",description:u.roleDescription??u.role,author:"",category:"general",tags:[],agent:{roleName:u.role,agentRole:u.agentRole},dependencies:{skills:u.skills??[]}};await Rf.publishViaProxy({itemType:"agent",name:u.name,description:j.description,category:"general",config:j,files:$}),v({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){v({title:c("agent:profilePage.hub"),message:c("agent:profilePage.publishFailed",{error:String($)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:c("agent:profilePage.publishTitle"),children:[h.jsx("span",{children:"↑"})," ",c("agent:profilePage.hub")]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),h.jsx("div",{ref:S,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>h.jsxs("button",{onClick:()=>m($.key),"data-active":b===$.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${b===$.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[h.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),h.jsxs("div",{className:"p-5",onTouchStart:d?w.onTouchStart:void 0,onTouchEnd:d?w.onTouchEnd:void 0,children:[(b==="overview"||b==="mind")&&h.jsxs(h.Fragment,{children:[h.jsx(lx,{agent:u,onUpdate:Q,externalInfo:p,t:c,canManageAgents:L}),h.jsx("div",{className:"mt-6",children:h.jsx(Sx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:L,onAgentStateChange:Q})})]}),b==="files"&&h.jsx(dx,{agentId:s}),b==="tools"&&h.jsx(ux,{tools:u.tools??[],agent:u}),b==="memory"&&h.jsxs(h.Fragment,{children:[h.jsx(px,{agentId:s,initialData:u.heartbeat}),h.jsx("div",{className:"mt-6",children:h.jsx(fx,{agentId:s})})]}),b==="deliverables"&&h.jsx(_x,{agentId:s})]}),g&&h.jsx(_o,{alertOnly:!0,variant:g.variant??"primary",title:g.title,message:g.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function lx({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i}){const[n,a]=C.useState(null),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(null),[g,v]=C.useState(""),[b,m]=C.useState([]);C.useEffect(()=>{K.usage.agents().then(w=>{const S=w.agents.find(Q=>Q.agentId===s.id);S&&a(S)}).catch(()=>{}),K.agents.getRecentActivities(s.id).then(w=>l(w.activities)).catch(()=>{}),K.system.storage().then(w=>{v(w.dataDir+"/agents/"+s.id);const S=w.agents.find(Q=>Q.id===s.id);S&&f(S)}).catch(()=>{}),s.state.activeTaskIds?.length&&K.tasks.list({assignedAgentId:s.id}).then(w=>{m(w.tasks.filter(S=>s.state.activeTaskIds?.includes(S.id)))}).catch(()=>{})},[s.id,s.state.activeTaskIds]);const O=()=>{s.state.status==="offline"?K.agents.start(s.id).then(e):K.agents.stop(s.id).then(e)},p=C.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),x=C.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return h.jsxs("div",{className:"space-y-4",children:[h.jsx(as,{title:r("agent:profilePage.overview.identity"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.connectionStatus"),children:h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.externalAgentDetails"),children:h.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),h.jsx(as,{title:r("agent:profilePage.overview.syncContextTitle"),children:h.jsx("div",{className:"space-y-1.5",children:x.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:w.field}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:w.desc})]},w.field))})}),h.jsx(as,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:h.jsx("div",{className:"space-y-1.5",children:p.map(w=>h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[h.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${w.method==="POST"?"text-amber-600":"text-green-600"}`,children:w.method}),h.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:w.path}),h.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:w.desc})]},w.path))})})]});const y=o.filter(w=>w.type==="heartbeat").length,_=o.filter(w=>w.type==="chat").length,k=s.state.activeTaskIds?.length??0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:h.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),h.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),h.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${hS[s.state.status]||"bg-gray-500"}`}),h.jsx("span",{className:`text-sm font-semibold ${s.state.status==="idle"?"text-green-500":s.state.status==="working"?"text-blue-400":s.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:cS(s.state.status,r)})]}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Kn(s.state.tokensUsedToday)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(k),color:k>0?"blue":void 0}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),i&&h.jsx("button",{onClick:O,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&h.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&h.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),h.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:wc(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&k>0&&h.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:h.jsx("div",{className:"space-y-1",children:b.map(w=>h.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),h.jsx("span",{className:"text-fg-secondary truncate flex-1",children:w.title}),h.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Qf(w.status,r)})]},w.id))})}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Kn(n.totalTokens)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.promptTokens"),value:Kn(n.promptTokens)}),h.jsx(fs,{label:r("agent:profilePage.overview.labels.completionTokens"),value:Kn(n.completionTokens)}),h.jsx(fs,{label:"CU Used",value:Kn(n.cuUsed??0)})]})]}),u&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"border-t border-border-default/40"}),h.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[h.jsx(fs,{label:r("agent:profilePage.overview.storage"),value:xx(u.size)}),u.subItems.filter(w=>w.size>0).map(w=>h.jsx(fs,{label:w.name,value:xx(w.size)},w.name)),h.jsxs("button",{onClick:()=>{K.system.openPath(g)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),y>0&&h.jsx(as,{title:r("agent:profilePage.overview.recentHeartbeats"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:y})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="heartbeat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s.id,activityId:w.id})})]},w.id)})})}),_>0&&h.jsx(as,{title:r("agent:profilePage.overview.recentA2A"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:_})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(w=>w.type==="chat").map(w=>{const S=c===w.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(S?null:w.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:w.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(w.startedAt).toLocaleString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:S?"▲":"▼"})]}),S&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s.id,activityId:w.id})})]},w.id)})})})]})}function fM(s,e){const t=s.split(`
56
56
  `),r=e.split(`
57
57
  `),i=t.length,n=r.length,a=Array.from({length:i+1},()=>new Array(n+1).fill(0));for(let f=i-1;f>=0;f--)for(let g=n-1;g>=0;g--)a[f][g]=t[f]===r[g]?a[f+1][g+1]+1:Math.max(a[f+1][g],a[f][g+1]);const o=[];let l=0,c=0,d=1,u=1;for(;l<i||c<n;)l<i&&c<n&&t[l]===r[c]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,c++):c<n&&(l>=i||a[l][c+1]>=a[l+1][c])?(o.push({type:"add",content:r[c],lineNum:u++}),c++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function cx(s){return s.match(/\S+|\s+/g)??[""]}function hx({oldText:s,newText:e,mode:t}){const r=cx(s),i=cx(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=r[u]===i[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let c=0,d=0;for(;c<n||d<a;)c<n&&d<a&&r[c]===i[d]?(l.push({text:t==="remove"?r[c]:i[d],changed:!1}),c++,d++):d<a&&(c>=n||o[c][d+1]>=o[c+1][d])?(t==="add"&&l.push({text:i[d],changed:!0}),d++):(t==="remove"&&l.push({text:r[c],changed:!0}),c++);return h.jsx("span",{children:l.map((u,f)=>u.changed?h.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):h.jsx("span",{children:u.text},f))})}function pM({agent:s,template:e,templateId:t}){const{t:r}=At(["agent","common"]),i=C.useMemo(()=>fM(s,e),[s,e]),[n,a]=C.useState(!0),o=3,l=C.useMemo(()=>{const g=i.map((O,p)=>O.type!=="equal"?p:-1).filter(O=>O>=0);if(g.length===0)return[];const v=[];let b=Math.max(0,g[0]-o),m=Math.min(i.length-1,g[0]+o);for(let O=1;O<g.length;O++){const p=Math.max(0,g[O]-o),x=Math.min(i.length-1,g[O]+o);p<=m+1||(v.push({start:b,end:m}),b=p),m=x}return v.push({start:b,end:m}),v},[i]),c=(g,v,b)=>{const m=g.type==="add"?"+":g.type==="remove"?"-":" ",O=g.type==="add"?"bg-green-500/8":g.type==="remove"?"bg-red-500/8":"",p=g.type==="add"?"text-green-600/90":g.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=g.type==="add"?"text-green-500":g.type==="remove"?"text-red-500":"text-fg-muted",y=g.type==="remove"?g.oldLineNum:g.lineNum;let _=null;return g.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?_=h.jsx(hx,{oldText:g.content,newText:b[v+1].content,mode:"remove"}):g.type==="add"&&v>0&&b[v-1].type==="remove"&&(_=h.jsx(hx,{oldText:b[v-1].content,newText:g.content,mode:"add"})),h.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[h.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),h.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:m}),h.jsxs("span",{className:`flex-1 text-[11px] font-mono ${p} whitespace-pre-wrap break-words leading-[20px]`,children:[_??g.content,g.content===""&&" "]})]},v)},d=i.filter(g=>g.type==="add").length,u=i.filter(g=>g.type==="remove").length,f=n?l.flatMap(g=>{const v=[];for(let b=g.start;b<=g.end;b++)v.push({...i[b],_idx:b});return v}):i.map((g,v)=>({...g,_idx:v}));return h.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),h.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),h.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),h.jsx("button",{onClick:()=>a(g=>!g),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),h.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&h.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((g,v)=>{const b=v>0?f[v-1]:null,m=n&&b&&g._idx-b._idx>1;return h.jsxs("div",{children:[m&&h.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),c(g,g._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&h.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function mM(s,e){const t=s.split(`
58
58
  `),r=e.split(`
@@ -69,7 +69,7 @@ ${he}
69
69
  `+J.join(`
70
70
  ---
71
71
 
72
- `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Qr.navigate(Kt.TEAM,{agentId:s,prefillMessage:T})},L=async Z=>{if(y?.file===Z){_(null);return}try{const z=await K.agents.roleDiff(s,Z);z.agentContent!=null&&z.templateContent!=null&&_({file:Z,agent:z.agentContent,template:z.templateContent})}catch{}};if(i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},j=Z=>{const z=$[Z];return z?e(`agent:profilePage.filesTab.fileLabels.${z}`):Z},I=p?.hasTemplate&&!p.isUpToDate,V=a?Q.some(Z=>Z.file===a):!1;return h.jsxs("div",{className:"space-y-4",children:[I&&h.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[h.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),h.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:Q.length,templateId:p.templateId})," ",Q.map(Z=>Z.file).join(", ")]})]}),h.jsx("button",{onClick:()=>N(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),h.jsxs(as,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",h.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[h.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(Z=>{const z=Q.some(J=>J.file===Z.name);return h.jsxs("button",{onClick:()=>w(Z.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===Z.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[Z.name,z&&h.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.name)})}),a&&h.jsxs("div",{children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("div",{className:"text-xs text-fg-secondary",children:j(a)}),h.jsxs("div",{className:"flex gap-2 items-center",children:[V&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),h.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&h.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[h.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),g(!0),setTimeout(()=>g(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),h.jsx("button",{onClick:()=>{K.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&h.jsx(pM,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),h.jsx(gM,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{c(Z),O(!0)},dirty:m,onSave:S}),a==="ROLE.md"&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&h.jsx(ih,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function gM({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=C.useState(!1),o=C.useRef(null);return C.useEffect(()=>{n&&o.current?.focus()},[n]),C.useEffect(()=>{a(!1)},[s]),n||r?h.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):h.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[h.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(uM,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const OM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_"]}];function xM(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of OM){const l=e(`agent:toolCategories.${a}`),c=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));c.length>0&&(t.set(l,c),c.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),c=e("agent:toolCategories.mcp",{server:l});t.has(c)||t.set(c,[]),t.get(c).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function bM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function vM({tools:s}){const{t:e}=At(["agent","common"]),t=xM(s,e);return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>h.jsx(as,{title:`${r.category} (${r.tools.length})`,children:h.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=y_(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,c=bM(i.description||"");return h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[h.jsx(S_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&h.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&h.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),c&&h.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:c,children:c})]})]},i.name)})})},r.category)),s.length===0&&h.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function yM({agent:s}){const{t:e}=At(["agent","common"]),t=s.proficiency??{},[r,i]=C.useState(null),[n,a]=C.useState(null),[o,l]=C.useState(!1),c=s.availableSkills??[],d=new Map;for(const m of c){const O=m.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(m)}const u=async m=>{if(r===m){i(null),a(null);return}i(m),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(m)}`);if(O.ok){const p=await O.json();a(p.skill)}else a(null)}catch{a(null)}l(!1)},f={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},g=m=>{const O=t[m.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:O.uses,successes:O.successes}),O.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(O.lastUsed).toLocaleDateString()})]}),y=r===m.name;return h.jsxs("div",{children:[h.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(m.name),children:[h.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:m.name}),m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),m.builtIn&&!m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!m.builtIn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:m.description}),x]}),p!==null&&h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:h.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&h.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(_=>h.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:_},_))]}),n.description&&h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&h.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(_=>h.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",_]},_))}),(n.toolDetails??n.tools??[]).length>0&&h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),h.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(_=>h.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:_.name}),_.description&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:_.description})]},_.name))})]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},m.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],b=[...d.entries()].sort((m,O)=>{const p=v.indexOf(m[0]),x=v.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:c.length})})}),b.map(([m,O])=>h.jsx(as,{title:h.jsxs("span",{className:"capitalize",children:[m," ",h.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:h.jsx("div",{className:"space-y-2",children:O.map(p=>g(p))})},m)),c.length===0&&h.jsx(ih,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function ux({tools:s,agent:e}){const{t}=At(["agent","common"]),[r,i]=C.useState("tools");return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>h.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?h.jsx(vM,{tools:s}):h.jsx(yM,{agent:e})]})}function fx({agentId:s}){const{t:e}=At(["agent","common"]),[t,r]=C.useState(null),[i,n]=C.useState(!0),[a,o]=C.useState("longterm"),[l,c]=C.useState(""),[d,u]=C.useState(""),[f,g]=C.useState(!1),[v,b]=C.useState(null),[m,O]=C.useState(null),[p,x]=C.useState([]),[y,_]=C.useState(!1),k=C.useCallback(()=>{n(!0),K.agents.getMemory(s).then($=>{r($),c($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);C.useEffect(()=>{k()},[k]);const w=async()=>{g(!0),await K.agents.updateDailyMemory(s,l).catch(()=>{}),g(!1),k()},S=async()=>{g(!0),await K.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),g(!1),k()},Q=l!==(t?.recentDailyLogs??""),N=d!==(t?.longTermMemory??"");if(i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex gap-2",children:L.map($=>h.jsx("button",{onClick:()=>o($.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===$.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:$.label},$.key))}),a==="entries"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?h.jsx(ih,{text:e("agent:profilePage.memoryTab.noEntries")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,j)=>{const I=v===j;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>b(I?null:j),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.type==="fact"?"bg-blue-500/15 text-blue-600":$.type==="task"?"bg-green-500/15 text-green-600":$.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:$.type}),h.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${I?"":"line-clamp-2"}`,children:$.content}),h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&h.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${$.importance>=7?"bg-red-500/15 text-red-500":$.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",$.importance]}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:I?"▲":"▼"})]})]}),I&&h.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[h.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),h.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[h.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&h.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),h.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},j)})})}),a==="sessions"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?h.jsx(ih,{text:e("agent:profilePage.memoryTab.noSessions")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const j=m===$.id,I=async()=>{if(j){O(null),x([]);return}O($.id),_(!0);try{const V=await K.agents.getMemorySession(s,$.id);x(V.messages)}catch{x([])}_(!1)};return h.jsxs("div",{children:[h.jsxs("button",{onClick:I,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[h.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:j?"▲":"▼"})]}),j&&h.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const V=new Map;for(const Z of p)Z.role==="tool"&&Z.toolCallId&&V.set(Z.toolCallId,Z.content);return h.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(Z=>Z.role!=="tool").map((Z,z)=>h.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.role==="system")&&h.jsxs("div",{children:[h.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(Oa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&h.jsxs("div",{className:"space-y-1",children:[Z.content&&h.jsxs("div",{children:[h.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(Oa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&h.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(J=>{let T;try{T=JSON.parse(J.arguments)}catch{}const A={tool:J.name,status:"done",args:T,result:V.get(J.id)};return h.jsx(g_,{entry:{type:"tool",info:A}},J.id)})})]})]},z))})})()})]},$.id)})})}),a==="daily"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:Q?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>c(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:w,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:l,onChange:$=>c($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:N?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:S,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:d,onChange:$=>u($.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function px({agentId:s,initialData:e}){const{t}=At(["agent","common"]),[r,i]=C.useState(e??null),[n,a]=C.useState(!e),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(!1),[g,v]=C.useState(null),b=C.useCallback(()=>Promise.all([K.agents.getHeartbeat(s).then(i).catch(()=>{}),K.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);C.useEffect(()=>{a(!0),b().finally(()=>a(!1))},[b]),C.useEffect(()=>yt.on("agent:update",_=>{_.payload?.agentId===s&&b()}),[s,b]);const m=async()=>{f(!0),v(null);try{const y=await K.agents.triggerHeartbeat(s);v(y.message),setTimeout(()=>v(null),4e3),setTimeout(b,2e3)}catch(y){v(String(y).replace("Error: ",""))}f(!1)},O=async y=>{try{await K.agents.cancelWakeup(s,y),b()}catch{}};if(n)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=y=>y?y<1e3?`${y}ms`:y<6e4?`${(y/1e3).toFixed(1)}s`:`${(y/6e4).toFixed(1)}m`:null,x=y=>{if(!y)return null;const _=Date.now()-new Date(y).getTime();if(_<0){const k=Math.abs(_);return k<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(k/1e3)}):k<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(k/6e4)}):t("agent:profilePage.relative.inHours",{hours:(k/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return h.jsxs("div",{className:"space-y-4",children:[h.jsxs(as,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:b,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),h.jsx("button",{onClick:m,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[h.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[h.jsx(fs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),h.jsx(_M,{agentId:s,intervalMs:r.intervalMs,onChanged:b}),h.jsx(fs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?x(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),h.jsx(fs,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?x(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),h.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),g&&h.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:g})]}),r.wakeups&&r.wakeups.length>0&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[x(y.wakeAt)??new Date(y.wakeAt).toLocaleString(),y.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${y.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),h.jsx("button",{onClick:()=>O(y.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},y.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${y.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${x(y.timeoutAt)??new Date(y.timeoutAt).toLocaleString()}`]})]})]},y.id))})}),r.lastSummary&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:h.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:h.jsx(Oa,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?h.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const _=c===y.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(_?null:y.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),h.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:h.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s,activityId:y.id})})]},y.id)})})}):r.lastHeartbeat?null:h.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:h.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[h.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),h.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),h.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&h.jsx("button",{onClick:m,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function SM({taskId:s,isLive:e}){const{t}=At("agent"),[r,i]=C.useState([]),[n,a]=C.useState(""),[o,l]=C.useState(!0),[c,d]=C.useState("compact");if(C.useEffect(()=>{l(!0),a(""),K.tasks.getLogs(s).then(g=>{i(g.logs),l(!1)}).catch(()=>l(!1))},[s]),C.useEffect(()=>{if(!e)return;const g=yt.on("task:log",b=>{const m=b.payload;if(m.taskId!==s)return;const O={id:m.id,taskId:m.taskId,agentId:m.agentId,seq:m.seq,type:m.logType,content:m.content,metadata:m.metadata,createdAt:m.createdAt};i(p=>O.id&&p.some(x=>x.id===O.id)?p:[...p,O]),O.type==="text"&&a("")}),v=yt.on("task:log:delta",b=>{const m=b.payload;m.taskId===s&&a(O=>O+m.text)});return()=>{g(),v()}},[s,e]),o)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(g=>v_(g)),f=new Set(u.filter(g=>g.executionRound!=null).map(g=>g.executionRound)).size>1;return h.jsx("div",{className:"px-3 py-2",children:c==="compact"?h.jsx(Rx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):h.jsx(Ax,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Xa({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=At("agent"),[i,n]=C.useState([]),[a,o]=C.useState(!0),[l,c]=C.useState("compact");if(C.useEffect(()=>{o(!0),K.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),C.useEffect(()=>t?yt.on("agent:activity_log",f=>{const g=f.payload;if(g.agentId!==s||g.activityId!==e)return;const v={seq:g.seq,type:g.type,content:g.content,metadata:g.metadata,createdAt:g.createdAt};n(b=>b.some(m=>m.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>b_(u,e,s)).filter(u=>u!==null);return h.jsx("div",{className:"px-3 py-2",children:l==="compact"?h.jsx(Rx,{entries:d,isActive:t,onExpand:()=>c("full")}):h.jsx(Ax,{entries:d,isActive:t,onCollapse:()=>c("compact")})})}function as({title:s,action:e,children:t}){return h.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[h.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),h.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function fs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return h.jsxs("div",{className:"flex items-baseline gap-1.5",children:[h.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const mx=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],gx=5,Ox=1440;function _M({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=At(["agent","common"]),[i,n]=C.useState(!1),[a,o]=C.useState(null),[l,c]=C.useState(!1),[d,u]=C.useState(String(Math.round(e/6e4))),f=p=>p%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),g=async p=>{n(!0),o(null);try{await K.agents.updateConfig(s,{heartbeatIntervalMs:p}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=p=>{if(p.target.value==="custom"){c(!0);return}c(!1),g(Number(p.target.value))},b=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<gx||p>Ox){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}g(p*60*1e3)},m=mx.includes(e),O=l||!m?"custom":String(e);return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),h.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!m&&h.jsx("option",{value:String(e),children:f(e)}),mx.map(p=>h.jsx("option",{value:String(p),children:f(p)},p)),h.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!m)&&h.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[h.jsx("input",{type:"number",min:gx,max:Ox,value:d,onChange:p=>u(p.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),h.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&h.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function ih({text:s}){return h.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function xx(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const bx={0:"0",1:"1",2:"2",3:"3",4:"4"},vx={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},wM={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"},kM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},rc={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},CM=["all","interaction","task","notification","system"],PM={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"]},TM={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"},QM={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 bu(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function yx(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Qf(d,e),g=Qf(u,e),v=QM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:g}),badge:{label:g,color:v}}}const c=r.match(/^Task:\s*(.+)/);return c?{title:c[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=bu(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=bu(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=bu(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function Sx({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r,onAgentStateChange:i}){const{t:n}=At(["agent","common","team"]),[a,o]=C.useState(null),[l,c]=C.useState(null),[d,u]=C.useState(!0),[f,g]=C.useState("all"),[v,b]=C.useState("all"),[m,O]=C.useState(e??null),[p,x]=C.useState(e??null),[y,_]=C.useState(!1),[k,w]=C.useState(!0),[S,Q]=C.useState(null),N=50,L=3,$=C.useCallback(async(T=!0)=>{T&&u(!0);try{const A=f==="all"?void 0:f,B=v==="all"?void 0:v,[q,H]=await Promise.all([K.agents.getMindState(s),K.agents.getMailbox(s,{limit:N,category:A,status:B})]);o(q),c(H),w((H.history?.length??0)>=N)}catch{}u(!1)},[s,f,v]),j=C.useCallback(async()=>{if(!l)return;const T=f==="all"?void 0:f,A=v==="all"?void 0:v;try{const B=await K.agents.getMailbox(s,{limit:N,offset:l.history.length,category:T,status:A});c(q=>q?{...q,history:[...q.history,...B.history]}:B),w((B.history?.length??0)>=N)}catch{}},[s,l,f,v]);C.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const I=C.useRef(!1);if(C.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){I.current=!1;const A=document.getElementById(`mbx-${p}`);if(A){setTimeout(()=>A.scrollIntoView({behavior:"smooth",block:"center"}),100);const B=setTimeout(()=>x(null),3e3);return()=>clearTimeout(B)}}else k&&!I.current&&(I.current=!0,(async()=>{let A=l?.history??[],B=k;for(;B;)try{const q=await K.agents.getMailbox(s,{limit:N,offset:A.length}),H=[...A,...q.history];A=H,B=(q.history?.length??0)>=N;const te=q.history.some(ue=>ue.id===p);if(c(ue=>ue?{...ue,history:H}:q),w(B),te||!B)break}catch{break}I.current=!1})())},[p,d,l,k,s]),C.useEffect(()=>{let T=null;const A=q=>{q.payload?.agentId===s&&(T&&clearTimeout(T),T=setTimeout(()=>{T=null,$(!1)},500))},B=[yt.on("agent:mailbox",A),yt.on("agent:decision",A),yt.on("agent:attention",A),yt.on("agent:focus",A),yt.on("agent:update",A),yt.on("agent:triage",A)];return()=>{T&&clearTimeout(T),B.forEach(q=>q())}},[s,$]),d&&!a)return h.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:n("agent:profilePage.mind.loading")});const V=a?.mailboxDepth??a?.queuedItems?.length??0,Z=(()=>{const T=a?.attentionState??"idle";return T==="deciding"||T==="idle"&&V>0?"deciding":T!=="idle"&&!a?.currentFocus?"idle":T})(),z=Z==="idle"&&l?.history?.some(T=>T.status==="processing"),J=(a?.attentionState??"idle")==="idle"&&V>0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[h.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${kM[Z]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${Z}`)}),a?.currentFocus?(()=>{const T=yx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return h.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[h.jsxs("span",{children:[rc[a.currentFocus.type]??"●"," ",h.jsx("span",{className:"text-fg-primary font-medium",children:T.title}),T.subtitle&&h.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:T.subtitle}),h.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&h.jsxs("button",{onClick:()=>Q(a.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]})})():J?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.queuedButIdle",{count:V,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):Z==="deciding"?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:V})}):h.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&t==="offline"&&h.jsxs("button",{onClick:()=>{K.agents.start(s).then(()=>{i?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-green-500/15 text-green-500 hover:bg-green-500/25 transition-colors",children:["▶ ",n("agent:profilePage.mind.continueBtn")]}),r&&(t==="working"||t==="idle")&&h.jsxs("button",{onClick:()=>{K.agents.stop(s).then(()=>{i?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors",children:["■ ",n("team:contextMenu.stop")]}),h.jsx("button",{onClick:()=>{$()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:n("agent:profilePage.mind.refresh")})]})]}),z&&h.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[h.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),h.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const T=a.queuedItems,A=T.length>L,B=A&&!y?T.slice(0,L):T,q=T.reduce((H,te)=>(H[te.sourceType]=(H[te.sourceType]??0)+1,H),{});return h.jsxs("div",{className:"mb-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:T.length})}),h.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(q).map(([H,te])=>h.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[rc[H]??"●"," ",te]},H))})]}),h.jsxs("div",{className:"space-y-1",children:[B.map((H,te)=>h.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[h.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:te+1}),h.jsx("span",{className:"text-sm",children:rc[H.sourceType]??"●"}),h.jsx("span",{className:`text-[10px] ${vx[H.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${bx[H.priority]??H.priority}`,{defaultValue:`P${H.priority}`})}),h.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:H.summary}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(H.queuedAt).toLocaleTimeString()})]},H.id)),A&&h.jsx("button",{onClick:()=>_(!y),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:y?n("agent:profilePage.mind.collapseQueue"):n("agent:profilePage.mind.expandQueue",{count:T.length-L})})]})]})})()]}),(a?.notebook?.length??0)>0&&h.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:h.jsxs("details",{open:!0,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"📓"}),h.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),h.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),h.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(T=>{const A=Date.now()-T.updatedAt,B=A<6e4?`${Math.round(A/1e3)}s ago`:A<36e5?`${Math.round(A/6e4)}min ago`:`${(A/36e5).toFixed(1)}h ago`,q=T.managed==="system"?"text-blue-400":T.managed==="cpp"?"text-purple-400":"text-emerald-400";return h.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary",children:T.key}),h.jsxs("span",{className:`text-[10px] ${q}`,children:["[",T.managed,"]"]}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:B})]}),h.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:T.text.length>500?T.text.slice(0,500)+"…":T.text})]},T.key)})})]})}),a?.deliberationActivity&&h.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),h.jsx(Xa,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return h.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:h.jsxs("details",{open:!A,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),h.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:n("agent:profilePage.mind.deferred",{count:a.lastTriage.deferredItemIds.length})}),a.lastTriage.droppedItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:n("agent:profilePage.mind.dropped",{count:a.lastTriage.droppedItemIds.length})}),(a.lastTriage.inlineCompletedIds?.length??0)>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:n("agent:profilePage.mind.inlineCompleted",{count:a.lastTriage.inlineCompletedIds.length})})]})]})})})(),h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),h.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:CM.map(T=>{const A=l?.sourceTypeCounts,B=T==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?(PM[T]??[]).reduce((q,H)=>q+(A[H]??0),0):void 0;return h.jsxs("button",{onClick:()=>g(T),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===T?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[n(`agent:profilePage.mind.categoryFilters.${T}`),B!=null&&B>0&&h.jsx("span",{className:"ml-1 opacity-60",children:B})]},T)})})]}),h.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(T=>{const A=l?.statusCounts,B=T.key==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?.[T.key];return h.jsxs("button",{onClick:()=>b(T.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===T.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[T.dot&&h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T.dot}`}),n(`agent:profilePage.mind.statusFilters.${T.key}`),B!=null&&B>0&&h.jsx("span",{className:"ml-1 opacity-60",children:B})]},T.key)})}),(!l?.history||l.history.length===0)&&!d&&h.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),h.jsx("div",{className:"space-y-1",children:l?.history?.map(T=>{const A=m===T.id,B=rc[T.sourceType]??"●",q=yx(T,n),H=T.metadata?.senderName,te=T.metadata?.senderRole,ue=p===T.id;return h.jsxs("div",{id:`mbx-${T.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${ue?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[h.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>O(A?null:T.id),children:[h.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),h.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${TM[T.status]??"bg-gray-400"}`}),h.jsx("span",{className:"text-sm",children:B}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:q.title}),q.badge&&h.jsx("span",{className:`text-[10px] font-medium shrink-0 ${q.badge.color}`,children:q.badge.label}),h.jsx("span",{className:`text-[10px] shrink-0 ${vx[T.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${bx[T.priority]??T.priority}`,{defaultValue:""})})]}),q.subtitle&&h.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:q.subtitle}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[h.jsx("span",{children:new Date(T.queuedAt).toLocaleString()}),T.completedAt&&h.jsxs("span",{children:["→ ",new Date(T.completedAt).toLocaleTimeString()]}),T.activity&&h.jsxs(h.Fragment,{children:[T.activity.totalTokens>0&&h.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:Kn(T.activity.totalTokens)})}),T.activity.totalTools>0&&h.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:T.activity.totalTools})})]})]})]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:T.sourceType}),r&&T.status==="processing"&&h.jsxs("button",{onClick:ke=>{ke.stopPropagation(),Q(T.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]}),A&&h.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[H&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",h.jsx("span",{className:"text-fg-secondary",children:H}),te&&h.jsxs("span",{className:"text-fg-tertiary",children:[" (",te,")"]})]}),T.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(T.sourceType)&&h.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:T.payload.content}),T.decisions&&T.decisions.length>0&&h.jsxs("div",{children:[h.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),h.jsx("div",{className:"space-y-1",children:T.decisions.map(ke=>h.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${wM[ke.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:ke.decisionType}),h.jsx("span",{className:"text-fg-secondary flex-1",children:ke.reasoning}),h.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(ke.createdAt).toLocaleTimeString()})]},ke.id))})]}),T.activity?h.jsxs("div",{children:[h.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:T.activity.label}),h.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${T.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:T.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),T.activity.type==="task"&&T.payload?.taskId?h.jsx(SM,{taskId:T.payload.taskId,isLive:!T.activity.endedAt}):h.jsx(Xa,{agentId:s,activityId:T.activity.id,isLive:!T.activity.endedAt})]}):T.status==="processing"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):T.status==="completed"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},T.id)})}),k&&(l?.history?.length??0)>0&&h.jsx("div",{className:"text-center mt-3",children:h.jsx("button",{onClick:j,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),S&&h.jsx(_o,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{Q(null),K.agents.cancelProcessing(s).then(()=>{let T=0;const A=()=>{T+=1,$(),T<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>Q(null)})]})}function _x({agentId:s}){const{t:e}=At(["agent","common"]),t=nh(),[r,i]=C.useState([]),[n,a]=C.useState(!0),[o,l]=C.useState(null),c=C.useCallback(u=>{t?.openRightPanel?t.openRightPanel({kind:"deliverable",deliverable:u}):l(u)},[t]),d=C.useCallback(async()=>{a(!0);try{const{results:u}=await K.deliverables.search({agentId:s,limit:200});i(u)}catch{i([])}a(!1)},[s]);return C.useEffect(()=>{d()},[d]),C.useEffect(()=>{const u=yt.on("deliverable:created",()=>d()),f=yt.on("deliverable:updated",()=>d()),g=yt.on("deliverable:removed",()=>d());return()=>{u(),f(),g()}},[d]),n?h.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(u=>h.jsxs("div",{className:"animate-pulse space-y-2",children:[h.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),h.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},u))}):r.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[h.jsx("span",{className:"text-3xl mb-3",children:"📦"}),h.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),h.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(u=>{const f=O_[u.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},g=Nm[u.status]??Nm.active;return h.jsxs("button",{onClick:()=>c(u),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[h.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${f.color}`,children:f.icon}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:u.title}),h.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${g.color}`,children:u.status})]}),u.summary&&h.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:u.summary}),h.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[h.jsx("span",{children:new Date(u.createdAt).toLocaleDateString()}),u.tags.length>0&&h.jsx("span",{children:u.tags.slice(0,3).join(", ")})]})]}),h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},u.id)})]}),o&&h.jsx(x_,{item:o,onClose:()=>l(null),onOpenInPage:u=>{l(null),Qr.navigate(Kt.DELIVERABLES,{openDeliverable:u})}})]})}const $M=C.lazy(()=>Mx(()=>import("./index-CiAGgfZx.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),qp=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],wx={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function kx({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=At("team"),[o,l]=C.useState(null),[c,d]=C.useState(null),[u,f]=C.useState("overview"),g=r&&i?i:u,[v,b]=C.useState(""),[m,O]=C.useState(""),[p,x]=C.useState(!1),[y,_]=C.useState(!1),[k,w]=C.useState(""),[S,Q]=C.useState(""),N=C.useRef(null),L=C.useRef(null),$=C.useRef(null),j=C.useRef(null),[I,V]=C.useState(!1),[Z,z]=C.useState(!1),[J,T]=C.useState(""),[A,B]=C.useState(""),[q,H]=C.useState(!1),[te,ue]=C.useState([]),ke=C.useRef(null),U=C.useCallback(async()=>{try{const ge=(await K.teams.list()).teams.find(nt=>nt.id===s);ge&&l(ge);const He=await K.teams.status(s);ue(He.agents)}catch{}},[s]),D=C.useCallback(async()=>{try{const me=await K.teams.getFile(s,"ANNOUNCEMENT.md");b(me.content)}catch{b("")}try{const me=await K.teams.getFile(s,"NORMS.md");O(me.content)}catch{O("")}},[s]);C.useEffect(()=>{f("overview"),U(),D()},[s,U,D]),C.useEffect(()=>{p&&L.current&&L.current.focus()},[p]),C.useEffect(()=>{y&&j.current&&j.current.focus()},[y]);const se=async(me,ge)=>{V(!0);try{await K.teams.updateFile(s,me,ge),me==="ANNOUNCEMENT.md"?(b(ge),x(!1)):(O(ge),_(!1))}catch{}V(!1)},F=async()=>{J.trim()&&(await K.teams.update(s,{name:J.trim()}),z(!1),U())},G=async()=>{await K.teams.update(s,{description:A}),H(!1),U()};if(!o)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const ee=o.members.find(me=>me.agentRole==="manager"),we=te.filter(me=>me.status!=="offline").length,Ae=g==="announcements"&&p||g==="norms"&&y;if(r)return h.jsx("div",{className:`flex-1 bg-surface-primary ${Ae?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:h.jsxs("div",{className:`${Ae?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const ge=te.find(Ct=>Ct.id===me.id),He=wx[ge?.status??"offline"]??"bg-gray-500",nt=me.type==="agent";return h.jsxs("div",{onClick:()=>nt&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${nt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:me.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ge?.status??"offline"}),me.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),nt&&n&&h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),g==="announcements"&&h.jsx(ic,{content:v,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:L,contentRef:N,saving:I,onSave:()=>se("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),g==="norms"&&h.jsx(ic,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:I,onSave:()=>se("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),g==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:ke,value:J,onChange:me=>T(me.target.value),onKeyDown:me=>me.key==="Enter"&&F(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),h.jsx("button",{onClick:F,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:me=>B(me.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:G,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(Cx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const xe=u==="announcements"&&p||u==="norms"&&y;return h.jsxs("div",{className:`flex-1 bg-surface-primary ${xe?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:o.name}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[we," online"]})]}),h.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),h.jsxs("button",{onClick:async()=>{if(o)try{const{files:me}=await K.teams.getFilesMap(o.id),ge=o.members.filter(nt=>nt.type==="agent"),He={type:"team",name:Ex(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:ge.map(nt=>({name:nt.name,roleName:nt.role,role:nt.agentRole??"worker",count:1,skills:[]}))}};await Rf.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:He,files:me}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(me){d({title:"Hub",message:`Failed to publish: ${me}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[h.jsx("span",{children:"↑"})," Hub"]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),h.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:qp.map(me=>h.jsxs("button",{onClick:()=>f(me.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===me.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[me.icon," ",a(me.labelKey)]},me.key))})]}),h.jsxs("div",{className:`${xe?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const ge=te.find(Ct=>Ct.id===me.id),He=wx[ge?.status??"offline"]??"bg-gray-500",nt=me.type==="agent";return h.jsxs("div",{onClick:()=>nt&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${nt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:me.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ge?.status??"offline"}),me.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),nt&&n&&h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&h.jsx(ic,{content:v,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:L,contentRef:N,saving:I,onSave:()=>se("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&h.jsx(ic,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:I,onSave:()=>se("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:ke,value:J,onChange:me=>T(me.target.value),onKeyDown:me=>me.key==="Enter"&&F(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),h.jsx("button",{onClick:F,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:me=>B(me.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:G,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(Cx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),c&&h.jsx(_o,{alertOnly:!0,variant:c.variant??"primary",title:c.title,message:c.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function ic({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:c,emptyText:d}){return r?h.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[h.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:c}),o&&h.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):h.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx($M,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Cx({teamId:s,teamName:e,onDeleted:t}){const[r,i]=C.useState(!1),[n,a]=C.useState(!1),[o,l]=C.useState(!1),[c,d]=C.useState(!1);return h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[h.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{disabled:c,onClick:async()=>{d(!0);try{await K.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:c?"Deleting...":"Confirm Delete"}),h.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):h.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function nc(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}class bi{currentConvKey="";loadingSession=null;msgBuffers=new Map;sessionMsgCache=new Map;activeSession=new Map;actBuffers=new Map;sessionTabs=new Map;phase=new Map;sendCount=new Map;streamingSessions=new Map;sessionCacheOrder=[];static MAX_MESSAGES=500;static MAX_CONVERSATIONS=20;static MAX_SESSION_CACHE=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){return this.phase.get(e)??"idle"}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e){this.phase.set(e,"idle"),this.activeSession.delete(e)}updateMessages(e,t,r){const i=this.activeSession.get(e),n=!r||i===r||i===void 0,a=n?this.msgBuffers.get(e)??[]:this.sessionMsgCache.get(r)??[];let o=t(a);o.length>bi.MAX_MESSAGES&&(o=o.slice(-500));let l=!1;return n&&(this.msgBuffers.set(e,o),this.evictIfNeeded(e),l=this.currentConvKey===e),r&&r!==bi.NEW_CHAT_ID&&(this.sessionMsgCache.set(r,o),this.touchSessionCache(r)),{displayChanged:l,newMessages:l?o:void 0}}applyLoadResult(e,t,r){const i=this.sessionMsgCache.get(t),n=this.isCacheFresher(t,r);n||(this.sessionMsgCache.set(t,r),this.touchSessionCache(t));const a=this.getPhase(e),o=this.activeSession.get(e);if(this.currentConvKey===e&&(this.loadingSession===t||o===t)&&a!=="streaming"){const c=this.mergeDbWithCache(r,n?i:void 0);return this.msgBuffers.set(e,c),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:c}}return{displayChanged:!1}}mergeDbWithCache(e,t){if(!t||t.length===0)return[...e];const r=new Set,i=[];for(const n of e)r.add(n.id),i.push(n);for(const n of t){if(r.has(n.id))continue;const a=n.rawCreatedAt?Date.parse(n.rawCreatedAt):NaN;let o=i.length;for(;o>0&&i[o-1].rawCreatedAt&&Number.isFinite(a);){const l=Date.parse(i[o-1].rawCreatedAt);if(!Number.isFinite(l)||l<=a)break;o--}i.splice(o,0,n),r.add(n.id)}return i}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.activeSession.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.activeSession.get(e)}setActiveSession(e,t){this.activeSession.set(e,t)}saveToCache(e,t){if(!t||t===bi.NEW_CHAT_ID)return;const r=this.msgBuffers.get(e);r&&r.length>0&&(this.sessionMsgCache.set(t,r),this.touchSessionCache(t))}restoreFromCache(e,t){const r=this.sessionMsgCache.get(t);if(r&&r.length>0)return this.msgBuffers.set(e,r),r;this.msgBuffers.delete(e)}isCacheFresher(e,t){const r=this.sessionMsgCache.get(e);if(!r||r.length===0)return!1;if(r.length>t.length)return!0;const i=r.reduce((l,c)=>l+c.text.length,0),n=t.reduce((l,c)=>l+c.text.length,0);if(i>n)return!0;const a=r.reduce((l,c)=>l+(c.segments?.length??0),0),o=t.reduce((l,c)=>l+(c.segments?.length??0),0);return a>o}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;r.add(t),this.streamingSessions.set(e,r)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);r&&(r.delete(t),r.size===0&&this.streamingSessions.delete(e))}else this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}getMessages(e){return this.msgBuffers.get(e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.msgBuffers.delete(e)}evictIfNeeded(e){if(this.msgBuffers.size<=bi.MAX_CONVERSATIONS)return;const t=[...this.msgBuffers.keys()],r=t.filter(i=>i!==e&&i!==this.currentConvKey).slice(0,t.length-bi.MAX_CONVERSATIONS);for(const i of r)this.msgBuffers.delete(i),this.actBuffers.delete(i),this.sessionTabs.delete(i),this.activeSession.delete(i)}touchSessionCache(e){const t=this.sessionCacheOrder.indexOf(e);for(t!==-1&&this.sessionCacheOrder.splice(t,1),this.sessionCacheOrder.push(e);this.sessionCacheOrder.length>bi.MAX_SESSION_CACHE;){const r=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(r)){this.sessionCacheOrder.push(r);break}this.sessionMsgCache.delete(r)}}}const Tt=bi.NEW_CHAT_ID;function jM(s){const e=C.useRef(new bi),[t,r]=C.useState(s??[]),[i,n]=C.useState(!1),[a,o]=C.useState([]),l=C.useRef(null);C.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const c=C.useCallback((p,x,y)=>{const _=e.current.updateMessages(p,x,y);_.displayChanged&&_.newMessages&&r(_.newMessages)},[]),d=C.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const k=e.current.getMessages(p);k&&e.current.currentConvKey===p&&r([...k])}))},[]),u=C.useCallback((p,x,y)=>{const _=e.current.appendActivity(p,x,y);_.displayChanged&&_.newActivities&&o(_.newActivities)},[]),f=C.useCallback(p=>e.current.getPhase(p),[]),g=C.useCallback(p=>e.current.beginLoad(p),[]),v=C.useCallback(p=>e.current.beginStream(p),[]),b=C.useCallback(p=>e.current.endStream(p),[]),m=C.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=C.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const _=await y(),k=e.current.applyLoadResult(x,p,_.messages);return k.displayChanged&&k.newMessages&&r(k.newMessages),{count:_.messages.length,hasMore:_.hasMore,oldestCursor:_.oldestCursor}}catch{return e.current.currentConvKey===x&&e.current.getPhase(x)!=="streaming"&&(r([]),e.current.completeLoad(x)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get msgBuffers(){return e.current.msgBuffers},get sessionMsgCache(){return e.current.sessionMsgCache},get activeSessionBuffer(){return e.current.activeSession},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(p){e.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(p){e.current.loadingSession=p}}},updateConvMsgs:c,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:g,beginStream:v,endStream:b,resetConv:m,loadAndDisplay:O,incrementSending:p=>e.current.incrementSend(p),decrementSending:p=>e.current.decrementSend(p),resetSending:p=>e.current.resetSend(p),isSendingFor:p=>e.current.isSending(p),setStreamSession:(p,x)=>e.current.addStreamSession(p,x),clearStreamSession:(p,x)=>e.current.removeStreamSession(p,x),getStreamSession:p=>e.current.getStreamSessions(p),saveSessionToCache:(p,x)=>e.current.saveToCache(p,x),restoreSessionFromCache:(p,x)=>{const y=e.current.restoreFromCache(p,x);return r(y??[]),y},isSessionCacheFresherThanDb:(p,x)=>e.current.isCacheFresher(p,x)}}function EM({value:s,onSelect:e,disabled:t}){const{t:r}=At("team"),[i,n]=C.useState(!1),[a,o]=C.useState(!0),[l,c]=C.useState(""),[d,u]=C.useState(!1),[f,g]=C.useState([]),[v,b]=C.useState(null),m=C.useRef(null),O=C.useCallback(async()=>{u(!0);try{const w=await fetch("/api/settings/llm",{credentials:"include"});if(!w.ok)throw new Error(`HTTP ${w.status}`);const S=await w.json(),Q=S.providers?.markus;if(Q?.configured&&Q.enabled!==!1&&(!Q.models||Q.models.length===0))try{const j=await fetch("/api/models/live/markus",{credentials:"include"});if(j.ok){const I=await j.json();I.models?.length&&(Q.models=I.models)}}catch{}const N=[];for(const[j,I]of Object.entries(S.providers??{})){if(!I.configured||I.enabled===!1)continue;const V=(I.models??[]).map(Z=>({id:Z.id,name:Z.name}));V.length!==0&&N.push({provider:j,displayName:I.displayName??j,models:V})}N.sort((j,I)=>j.displayName.localeCompare(I.displayName)),g(N);const L=j=>!j?.provider||!j.model?!1:!!N.find(V=>V.provider===j.provider)?.models.some(V=>V.id===j.model);let $=null;if(S.routingDefaultModel?.provider&&S.routingDefaultModel?.model)$={provider:S.routingDefaultModel.provider,model:S.routingDefaultModel.model};else if(S.defaultProvider){const j=S.providers?.[S.defaultProvider];j?.model&&($={provider:S.defaultProvider,model:j.model})}if($&&!L($)){const j=N.find(V=>V.provider==="markus"),I=j?.models[0]?{provider:"markus",model:j.models[0].id}:N[0]?.models[0]?{provider:N[0].provider,model:N[0].models[0].id}:null;I?($=I,K.settings.updateRouting({defaultProvider:I.provider,routingDefaultModel:I}).catch(()=>{})):$=null}b($)}catch{g([])}finally{u(!1)}},[]);C.useEffect(()=>{O()},[O]),C.useEffect(()=>{i&&(o(!0),c(""),O())},[i,O]),C.useEffect(()=>{if(!i)return;const w=S=>{m.current?.contains(S.target)||n(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[i]);const p=C.useMemo(()=>{const w=l.trim().toLowerCase();return f.map(S=>({...S,models:w?S.models.filter(Q=>Q.id.toLowerCase().includes(w)||(Q.name?.toLowerCase().includes(w)??!1)||S.displayName.toLowerCase().includes(w)||S.provider.toLowerCase().includes(w)):S.models})).filter(S=>S.models.length>0)},[f,l]),x=C.useCallback(w=>!w?.provider||!w.model?!1:f.length===0?!0:!!f.find(Q=>Q.provider===w.provider)?.models.some(Q=>Q.id===w.model),[f]);C.useEffect(()=>{if(!s||f.length===0||x(s))return;const w=v&&x(v)?v:(()=>{const S=f.find(Q=>Q.provider==="markus");return S?.models[0]?{provider:"markus",model:S.models[0].id}:f[0]?.models[0]?{provider:f[0].provider,model:f[0].models[0].id}:null})();w&&e(w,!1)},[s,f,v,x,e]);const y=s&&x(s)?s:v,k=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||r("chatModel.title",{defaultValue:"Model"});return h.jsxs("div",{ref:m,className:"relative shrink-0",children:[h.jsxs("button",{type:"button",disabled:t,onClick:()=>n(w=>!w),className:"max-w-[180px] px-1.5 py-1 text-[12px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-md hover:bg-surface-elevated transition-colors flex items-center gap-1",title:y?`${y.provider}: ${y.model}`:r("chatModel.title",{defaultValue:"Model"}),children:[h.jsx("span",{className:"truncate",children:k}),h.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),i&&h.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[h.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[h.jsx("input",{autoFocus:!0,value:l,onChange:w=>c(w.target.value),placeholder:r("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-base border border-border-default/50 outline-none focus:border-brand-500/50"}),h.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[h.jsx("span",{children:r("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),h.jsx("button",{type:"button",role:"switch","aria-checked":a,onClick:()=>o(w=>!w),className:`relative w-9 h-5 rounded-full transition-colors ${a?"bg-brand-600":"bg-fg-tertiary/30"}`,children:h.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${a?"translate-x-4":""}`})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[d&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}),!d&&p.length===0&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!d&&p.map(w=>h.jsxs("div",{className:"mb-1",children:[h.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:w.displayName}),w.models.slice(0,80).map(S=>{const Q=y?.provider===w.provider&&y?.model===S.id;return h.jsxs("button",{type:"button",onClick:()=>{e({provider:w.provider,model:S.id},a),a&&b({provider:w.provider,model:S.id}),n(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[h.jsx("span",{className:"truncate flex-1",children:S.id}),Q&&h.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:h.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${w.provider}:${S.id}`)})]},w.provider))]})]})]})}async function RM(s,e,t){s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,e),t&&await K.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const Px="markus_team_sidebars_c";function AM(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}const MM=["chat","overview","files","tools","memory","deliverables"],LM=["chat","overview","announcements","norms","settings"];function NM(s,e){if(s==="chat")return e("page.chatTitle");if(Xp.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=qp.find(i=>i.key===s);return r?e(r.labelKey):s}function DM(s){if(s==="chat")return"💬";const e=Xp.find(r=>r.key===s);if(e)return e.icon;const t=qp.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}const $f=new Set;function IM(){return window.location.hash}function BM(s){return $f.add(s),()=>{$f.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>$f.forEach(s=>s()));function tL({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=At(["team","common"]),a=C.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Ef(Kt.TEAM),[l,c]=C.useState(r?.agents??[]),[d,u]=C.useState(r?.humans??[]),[f,g]=C.useState(!r),v=jf(),b=C.useSyncExternalStore(BM,IM),m=v&&(b.startsWith(`#${Kt.TEAM}/`)||b.startsWith("#chat/")),O=v&&b.match(/^#team\/t\/(.+)$/),p=v?O?"team":m?"chat":"roster":"roster",x=O?O[1]:null,y=C.useRef(Kt.TEAM),_=C.useCallback(()=>{y.current=window.location.hash.slice(1)||Kt.TEAM,window.location.hash=`${Kt.TEAM}/d`},[]),k=C.useCallback(P=>{window.location.hash=`${Kt.TEAM}/t/${P}`},[]);C.useEffect(()=>{if(!v)return;const P=()=>{fi(Q.current)&&S("chat")};return window.addEventListener("popstate",P),()=>window.removeEventListener("popstate",P)},[v]);const[w,S]=C.useState("chat"),Q=C.useRef("chat");Q.current=w;const N=Dm({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[L,$]=C.useState(()=>{try{return localStorage.getItem(Px)==="1"}catch{return!1}}),j=C.useCallback(P=>{$(P);try{localStorage.setItem(Px,P?"1":"0")}catch{}},[]),I=nh(),V=I?.leftCollapsed??!1,Z=I?.rightPanel??null,z=I?.rightPanelTabs??[],J=I?.activeRightPanelTabId??null,T=I?.rightPanelFullscreen??!1,A=Z?"2xl:pr-8":"2xl:pr-[280px]",B=I?.setHostAvailable,q=I?.collapseRightPanelOnly??I?.toggleRightPanel,H=I?.openRightPanel,te=400,ue=320,ke=6,[U,D]=C.useState(typeof window<"u"?window.innerWidth:1440),[se,F]=C.useState("auto"),G=C.useRef(V);C.useEffect(()=>{G.current!==V&&(G.current=V,$(V))},[V]);const ee=I?.keyboardPane??"content",we=C.useRef(!1),Ae=C.useRef(ee);C.useEffect(()=>{if(t||v||!o)return;const P=Ae.current;Ae.current=ee,(ee==="l1"||ee==="l2")&&P!==ee&&L&&($(!1),I?.setLeftCollapsed(!1))},[ee,t,v,o,L,I]),C.useEffect(()=>{if(t||v||!o)return;const P=R=>{const E=I?.keyboardPane??"content";if(E==="l0"||E==="l1"||E==="l2"||R.metaKey||R.ctrlKey||R.altKey)return;if(R.target instanceof HTMLElement){const Y=R.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||R.target.isContentEditable||R.target.closest(".xterm"))return}const X=R.key.length===1?R.key.toLowerCase():R.key;X!=="h"&&X!=="ArrowLeft"||(R.preventDefault(),L&&(j(!1),I?.setLeftCollapsed(!1)),I?.setKeyboardPane(we.current?"l2":"l1"))};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[t,v,o,I,L,j]),C.useEffect(()=>{if(B)return B(o&&!v),()=>B(!1)},[o,v,B]),C.useEffect(()=>t||v||!o?void 0:yt.on("ui:right_panel",R=>{const E=R.payload;if(E.action==="collapse"){q?.();return}if(E.action!=="open"||!E.panel||!H)return;const X=E.panel;if(X.kind==="url"&&X.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"url",url:X.url,title:X.title||X.url,browserId:Y});return}if(X.kind==="file"&&X.path){H({kind:"file",path:X.path,title:X.title});return}if(X.kind==="terminal"){const Y=X.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"terminal",terminalId:Y,title:X.title||"Terminal",cwd:X.cwd});return}X.kind==="deliverable"&&X.deliverableId&&K.deliverables.get(X.deliverableId).then(Y=>{Y.deliverable&&H({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,q,H]);const xe=C.useCallback(P=>{const R=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Mi(E=>[...E,{id:R,...P}]),requestAnimationFrame(()=>cr.current?.focus())},[]),me=C.useCallback(P=>{if(P)try{const R=JSON.parse(P);if(!Array.isArray(R)||R.length===0)return;const E=R.filter(Y=>!!Y&&typeof Y.content=="string"&&Y.content.trim().length>0);if(E.length===0)return;const X=E.map(Y=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:Y.label?.trim()||"Context",content:Y.content}));Mi(Y=>[...Y,...X]),requestAnimationFrame(()=>{const Y=cr.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))})}catch{}},[]),[ge,He]=C.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),nt=Dm({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Ct=C.useRef(null),[pt,Xt]=C.useState(!1),[wt,Et]=C.useState(!1),Pt=C.useCallback(()=>{pt?Et(P=>!P):He(P=>{const R=!P;try{localStorage.setItem("markus_team_panel_visible",String(R))}catch{}return R})},[pt]);C.useEffect(()=>{if(v)return;const P=Ct.current;if(!P)return;const R=new ResizeObserver(([E])=>{if(!E)return;const X=E.contentRect.width;if(D(X),!t){const Y=X-N.width-nt.width;Xt(Y<400)}});return R.observe(P),()=>R.disconnect()},[v,t,N.width,nt.width]);const he=ge&&!pt&&!wt,Xe=L?0:N.width+ke+(he?nt.width+ke:0),Oe=Math.max(0,U-Xe-ke-8),Ke=Math.min(te,Math.floor(Oe*.4)),Ne=Math.max(0,Oe-Ke),bt=Math.min(Math.round(Oe/2),Ne),ir=Math.max(0,Math.min(se==="auto"?bt:se,Ne)),ts=C.useRef(!1);C.useEffect(()=>{const P=(I?.rightPanel??null)!==null;P&&!ts.current&&($(!0),F("auto")),ts.current=P},[I?.rightPanel]);const Ka=C.useRef(ir);Ka.current=ir;const Ja=C.useRef(Ne);Ja.current=Ne;const el=C.useCallback(P=>{P.preventDefault();const R=P.clientX,E=Ka.current,X=oe=>{const de=E+(R-oe.clientX),Se=Ja.current,ae=Math.min(ue,Se);F(Math.max(ae,Math.min(Se,de)))},Y=()=>{document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",X),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);C.useEffect(()=>{if(!wt)return;const P=R=>{R.target.closest("[data-l2-floating]")||Et(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[wt]);const[rn,si]=C.useState(null),[Qo,tl]=C.useState(),[ji,nr]=C.useState(),[Ei,Dn]=C.useState(!1),[$o,nn]=C.useState(""),[wh,Lr]=C.useState(!1),[Ri,on]=C.useState(""),or=C.useRef(null),sl=C.useRef(null),vr=C.useCallback((P,R)=>{tl(P),nr(R),v?(S("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):S(P??"overview")},[v]),jo=[{id:"chat"},{id:"profile"}],ri=C.useCallback(P=>{P==="profile"?vr():fi(Q.current)?history.back():S("chat")},[vr]),Nr=jx(jo,w,ri),us=C.useCallback((P,R)=>{gt("direct"),Yt(P),v&&_(),vr(R?.tab,R?.highlightMailboxId),si(null)},[v,_,vr]),Eo=C.useCallback((P,R)=>{const E=l.find(X=>X.name.toLowerCase()===P.toLowerCase());if(E){const X=R.target.getBoundingClientRect();si({agentId:E.id,top:X.bottom,left:X.left})}},[l]),rl=C.useMemo(()=>l.map(P=>P.name),[l]),[ie,gt]=C.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[be,Yt]=C.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[mt,ks]=C.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Ut,gs]=C.useState(""),il=500,Ai=C.useRef(new Set),Ro=P=>{if(Ai.current.add(P),Ai.current.size>il){const R=Math.floor(il*.2),E=Ai.current.values();for(let X=0;X<R;X++){const Y=E.next().value;Y&&Ai.current.delete(Y)}}},nl=C.useMemo(()=>{if(r?.channelMessages){const P=r.activeChannel??"custom:general";return r.channelMessages.filter(R=>R.channel===P).map(R=>Sn(R))}},[]),{manager:ol,messages:zt,setMessages:Cs,sending:Ms,setSending:Os,activities:kh,setActivities:yr,msgBuffers:ss,sessionMsgCache:ar,activeSessionBuffer:ii,actBuffers:Sr,sessionTabsBuffer:Ws,currentConvKeyRef:at,updateConvMsgs:ft,updateConvMsgsRaf:ni,appendConvActivity:an,beginLoad:al,beginStream:ln,endStream:Ps,resetConv:W,loadAndDisplay:le,incrementSending:pe,decrementSending:je,resetSending:Ge,isSendingFor:tt,setStreamSession:Ot,clearStreamSession:St,getStreamSession:Ye,saveSessionToCache:ns,restoreSessionFromCache:Ls}=jM(nl),[Mt,xs]=C.useState(""),[Ht,Ts]=C.useState(null),[_r,Mi]=C.useState([]),[Wt,wr]=C.useState([]),lr=C.useRef(null),[Ch,ll]=C.useState(!!r?.streamLastMessage),cn=C.useRef(null),dS=400;C.useEffect(()=>(Ms?(cn.current&&(clearTimeout(cn.current),cn.current=null),ll(!0)):Ch&&(cn.current=setTimeout(()=>{ll(!1),cn.current=null},dS)),()=>{cn.current&&clearTimeout(cn.current)}),[Ms]);const zp=Ms||Ch||(()=>{for(let P=zt.length-1;P>=Math.max(0,zt.length-8);P--){const R=zt[P];if(R.isStreaming&&!R.isStopped)return!0}return!1})(),Ph=C.useRef({fullText:"",timers:[]});C.useEffect(()=>{if(!t||!r?.streamLastMessage||zt.length===0)return;const P=zt[zt.length-1];if(!P||P.sender!=="agent")return;const R=P.text;Ph.current.fullText=R;const E=Ph.current.timers;function X(){let oe=0;Cs(Se=>Se.map((ae,ce)=>ce===Se.length-1?{...ae,text:""}:ae)),ll(!0);const de=setInterval(()=>{if(oe+=1+Math.floor(Math.random()*2),oe>=R.length){clearInterval(de),Cs(ce=>ce.map((We,Ze)=>Ze===ce.length-1?{...We,text:R}:We));const Se=setTimeout(()=>ll(!1),800);E.push(Se);const ae=setTimeout(X,6e3);E.push(ae)}else Cs(Se=>Se.map((ae,ce)=>ce===Se.length-1?{...ae,text:R.slice(0,oe)}:ae))},30);E.push(de)}const Y=setTimeout(X,1500);return E.push(Y),()=>{E.forEach(oe=>clearTimeout(oe)),Ph.current.timers=[]}},[]);const Li=C.useRef(0),[Zp,Dr]=C.useState(!1),[Th,Vp]=C.useState(!1),[cl,oi]=C.useState(!1),[Us,Qh]=C.useState([]),[Fp,Yp]=C.useState(null),$h=C.useRef(null),cr=C.useRef(null),[hl,In]=C.useState(null),Ni=C.useRef(null),jh=C.useRef(!1),Ao=C.useCallback(()=>{const P=cr.current;if(!P)return;const R=jh.current,E=R?36:52,X=R?160:120;P.style.height="auto";const Y=Math.max(E,Math.min(P.scrollHeight,X));P.style.height=`${Y}px`,P.style.overflowY=Y>=X?"auto":"hidden"},[]);C.useEffect(()=>{const P=requestAnimationFrame(()=>Ao());return()=>cancelAnimationFrame(P)},[Mt,Us.length,Ao]);const Eh=P=>{try{const R=localStorage.getItem(`markus_closed_tabs_${P}`);return R?new Set(JSON.parse(R)):new Set}catch{return new Set}},uS=(P,R)=>{const E=Eh(P);E.add(R);try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...E]))}catch{}},fS=(P,R)=>{const E=Eh(P);if(E.delete(R))try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...E]))}catch{}},pS=P=>{try{return localStorage.getItem(`markus_active_session_${P}`)}catch{return null}},dl=(P,R)=>{if(P)try{R&&R!==Tt?localStorage.setItem(`markus_active_session_${P}`,R):localStorage.removeItem(`markus_active_session_${P}`)}catch{}},[Rh,hn]=C.useState([]),[lt,Ir]=C.useState(null),[dn,un]=C.useState(!1),[Up,Ah]=C.useState([]),[Mo,Mh]=C.useState(null),[mS,Hp]=C.useState(null),[ul,Lh]=C.useState([]),[Bn,Nh]=C.useState(null),[gS,Gp]=C.useState(null),[Kp,Dh]=C.useState([]),[Lo,OS]=C.useState([]),Xs=P=>{OS(R=>{const E=typeof P=="function"?P(R):P,X=new Set;return E.filter(Y=>X.has(Y.id)?!1:(X.add(Y.id),!0))})},fl=C.useRef(null),Ih=C.useRef(null),kr=C.useRef(null),[Qs,No]=C.useState(r?.groupChats??[]),Bh=C.useRef(Qs);Bh.current=Qs;const Jp=C.useRef(null),[Do,bs]=C.useState(!1),[fn,Io]=C.useState(!1),[em,Wn]=C.useState(""),[Wh,Di]=C.useState([]),[tm,sm]=C.useState(!1),Xh=C.useRef(void 0),[Cr,rm]=C.useState(r?.teams??[]),[xS,bS]=C.useState([]),[pl,im]=C.useState([]),[vS,yS]=C.useState(null),[WM,XM]=C.useState(!1),[qM,zM]=C.useState(""),[nm,Bo]=C.useState(!1),[om,SS]=C.useState(""),[Wo,Xn]=C.useState(0),[am,ml]=C.useState(!1),[lm,_S]=C.useState(""),[qh,Xo]=C.useState(0),[zh,wS]=C.useState([]),cm=C.useRef(!1),Zh=C.useCallback(()=>{cm.current||(cm.current=!0,(async()=>{try{const{skills:P}=await K.skills.list();wS(P.map(R=>({name:R.name,description:R.description??R.name})))}catch{}})())},[]);C.useEffect(()=>{Zh()},[Zh]);const pn=lm?zh.filter(P=>P.name.toLowerCase().includes(lm.toLowerCase())):zh,[kS,CS]=C.useState([]),hm=C.useRef(!1),PS=C.useCallback(()=>{hm.current||(hm.current=!0,(async()=>{const P=[];try{const[R,E,X,Y,oe]=await Promise.all([K.projects.list().catch(()=>({projects:[]})),K.requirements.list().catch(()=>({requirements:[]})),K.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),K.deliverables.search({limit:100}).catch(()=>({results:[]})),K.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const de of R.projects)P.push({id:de.id,name:de.name,entityType:"project",role:de.status});for(const de of E.requirements)P.push({id:de.id,name:de.title,entityType:"requirement",role:de.priority});for(const de of X.tasks)P.push({id:de.id,name:de.title,entityType:"task",role:de.status});for(const de of Y.results)P.push({id:de.id,name:de.title,entityType:"deliverable",role:de.type});for(const de of oe.teams)try{const Se=await K.workflows.list(de.id);for(const ae of Se.workflows)P.push({id:ae.name,name:ae.displayName||ae.name,entityType:"workflow",role:`v${ae.version}`})}catch{}}catch{}CS(P)})())},[]),rs=ie==="channel"?Qs.find(P=>P.channelKey===mt)?.teamId:void 0,TS=C.useRef(null),qn=C.useRef(null),$s=C.useRef(null),dm=C.useRef(void 0),gl=C.useRef(!1),Br=C.useRef(!0),um=C.useRef(void 0);C.useEffect(()=>{if(!dn)return;const P=R=>{Ih.current&&!Ih.current.contains(R.target)&&fl.current&&!fl.current.contains(R.target)&&un(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[dn]);const Ol=(P,R)=>{if(!R||P===R)return`notes:${P}`;const[E,X]=[P,R].sort();return`dm:${E}:${X}`};C.useEffect(()=>{localStorage.setItem("markus_chat_mode",ie)},[ie]),C.useEffect(()=>{localStorage.setItem("markus_chat_agent",be)},[be]),C.useEffect(()=>{localStorage.setItem("markus_chat_channel",mt)},[mt]);const{counts:Vh,sessionAgentMap:qo,markRead:zo,setActiveKey:QS,clearActiveKey:$S}=__({enabled:!t}),xl=C.useMemo(()=>{const P={};for(const[R,E]of Object.entries(Vh))R.startsWith("channel:")&&(P[R.slice(8)]=E);return P},[Vh]),Fh=w_(qo,Vh);C.useEffect(()=>{let P=0;for(const R of Fh.values())P+=R;for(const R of Object.values(xl))P+=R;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:P}}))},[Fh,xl]);const bl=Fh,jS=C.useCallback(async P=>{for(const[R,E]of Object.entries(qo))E===P&&zo(`session:${R}`)},[qo,zo]);C.useEffect(()=>{if(t||!((!v||p==="chat")&&w==="chat"))return;if(ie==="direct"&&be&&jS(be),ie==="channel"&&mt)zo(`channel:${mt}`);else if(ie==="direct"&&lt)zo(`session:${lt}`);else if(ie==="dm"&&Ut){const E=`dm:${[e?.id,Ut].sort().join(":")}`;zo(`channel:${E}`)}const R=[];if(ie==="direct"&&lt){R.push(`session:${lt}`);for(const[E,X]of Object.entries(qo))X===be&&R.push(`session:${E}`)}else ie==="channel"&&mt?R.push(`channel:${mt}`):ie==="dm"&&Ut&&e?.id&&R.push(`channel:dm:${[e.id,Ut].sort().join(":")}`);for(const E of R)QS(E);return()=>{for(const E of R)$S(E)}},[t,ie,mt,lt,Ut,be,p,w,qo]);const hr=C.useCallback(()=>K.agents.list().then(P=>c(P.agents)).catch(()=>{}),[]),Hs=C.useCallback(()=>K.teams.list().then(P=>rm(P.teams)).catch(()=>{}),[]),zn=C.useCallback(()=>K.groupChats.list().then(P=>No(P.chats)).catch(()=>{}),[]),ES=C.useMemo(()=>hd(hr,3e3),[hr]),vl=C.useMemo(()=>hd(Hs,5e3),[Hs]),Yh=C.useMemo(()=>hd(zn,3e3),[zn]),Zo=C.useCallback(()=>{K.users.list(e?.orgId).then(P=>u(P.users)).catch(()=>{})},[e?.orgId]);C.useEffect(()=>{t||(Promise.all([hr(),Hs()]).finally(()=>g(!1)),Zo(),K.tasks.list().then(P=>im(P.tasks)).catch(()=>{}),K.externalAgents.list().then(P=>bS(P.agents)).catch(()=>{}),zn())},[t,Zo]),C.useEffect(()=>{if(!(!t||!r)&&(c(r.agents??[]),u(r.humans??[]),rm(r.teams??[]),No(r.groupChats??[]),r.channelMessages)){const P=r.activeChannel??"custom:general";Cs(r.channelMessages.filter(R=>R.channel===P).map(R=>Sn(R)))}},[t,r]),C.useEffect(()=>{if(t||!o)return;hr(),Hs();const P=setInterval(hr,3e4),R=setInterval(Hs,6e4),E=yt.on("agent:update",()=>{ES(),vl()}),X=yt.on("team:update",()=>{vl(),Yh()}),Y=yt.on("agent:removed",vl),oe=yt.on("chat:group_created",()=>{zn(),Hs(),hr()}),de=yt.on("chat:group_updated",Yh),Se=yt.on("chat:group_deleted",()=>{Yh(),vl()}),ae=yt.on("task:update",We=>{const Ze=We?.payload;Ze?.taskId&&im(Ie=>Ie.map(Te=>Te.id===Ze.taskId?{...Te,status:Ze.status??Te.status}:Te))}),ce=()=>{hr(),Hs(),Zo()};return window.addEventListener("markus:data-changed",ce),()=>{clearInterval(P),clearInterval(R),E(),X(),Y(),oe(),de(),Se(),ae(),window.removeEventListener("markus:data-changed",ce)}},[t,o,Zo]),C.useEffect(()=>{if(t)return;const P=ce=>{const We=ce.detail;if(N_(We.page)===Kt.TEAM){if(We.params?.agentId){if(We.params.profileTab)us(We.params.agentId,{tab:We.params.profileTab});else if(gt("direct"),Yt(We.params.agentId),S("chat"),v&&_(),We.params.sessionId){const Ze=We.params.sessionId;setTimeout(async()=>{try{const{sessions:Ie}=await K.sessions.listByAgent(We.params.agentId,20),Te=Ie.find(dt=>dt.id===Ze);Te&&Cl(Te)}catch{}},300)}}if(We.params?.selectAgent&&(gt("direct"),Yt(We.params.selectAgent),S("chat"),v&&_()),We.params?.openDeliverable){const Ze=We.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:Ze}):H&&K.deliverables.get(Ze).then(Ie=>{Ie.deliverable&&H({kind:"deliverable",deliverable:Ie.deliverable})}).catch(()=>{})}if(We.params?.prefillMessage){const Ze=We.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),We.params?.autoSend==="true"?setTimeout(()=>dm.current?.(Ze),300):(xs(Ze),setTimeout(()=>{const Ie=cr.current;Ie&&(Ie.focus(),Ie.setSelectionRange(Ie.value.length,Ie.value.length))},100))}if(We.params?.chatChips){const Ze=We.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),S("chat"),me(Ze)}if(We.params?.dm&&(gt("dm"),gs(We.params.dm),S("chat"),v&&_()),We.params?.channel&&(gt("channel"),ks(We.params.channel),S("chat"),v&&_()),We.params?.selectTeam){const Ze=We.params.selectTeam;if(v)k(Ze);else{const Ie=Bh.current.find(Te=>Te.type==="team"&&Te.teamId===Ze);gt("channel"),ks(Ie?.channelKey??`group:${Ze}`),S("chat"),bs(!1),He(!0)}}We.params?.openHire}},R=localStorage.getItem("markus_nav_agentId");if(R){localStorage.removeItem("markus_nav_agentId");const ce=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),gt("direct"),Yt(R),ce?us(R,{tab:ce}):(S("chat"),v&&_())}const E=localStorage.getItem("markus_nav_dm");E&&(localStorage.removeItem("markus_nav_dm"),gt("dm"),gs(E),S("chat"),v&&_());const X=localStorage.getItem("markus_nav_channel");X&&(localStorage.removeItem("markus_nav_channel"),gt("channel"),ks(X),S("chat"),v&&_());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),xs(Y),setTimeout(()=>{const ce=cr.current;ce&&(ce.focus(),ce.setSelectionRange(ce.value.length,ce.value.length))},150));const oe=localStorage.getItem("markus_nav_chatChips");oe&&(localStorage.removeItem("markus_nav_chatChips"),S("chat"),me(oe));const de=localStorage.getItem("markus_nav_openDeliverable");de&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:de}):H&&K.deliverables.get(de).then(ce=>{ce.deliverable&&H({kind:"deliverable",deliverable:ce.deliverable})}).catch(()=>{}));const Se=localStorage.getItem("markus_nav_selectAgent");Se&&(localStorage.removeItem("markus_nav_selectAgent"),gt("direct"),Yt(Se),S("chat"),v&&_());const ae=localStorage.getItem("markus_nav_selectTeam");if(ae)if(localStorage.removeItem("markus_nav_selectTeam"),v)k(ae);else{const ce=Bh.current.find(We=>We.type==="team"&&We.teamId===ae);gt("channel"),ks(ce?.channelKey??`group:${ae}`),S("chat"),bs(!1),He(!0)}return window.addEventListener("markus:navigate",P),()=>window.removeEventListener("markus:navigate",P)},[t]),C.useEffect(()=>{const P=Jp.current;if(!P)return;const R=Qs.find(E=>E.type==="team"&&E.teamId===P);Jp.current=null,gt("channel"),ks(R?.channelKey??`group:${P}`),S("chat"),bs(!1),He(!0)},[Qs,Cr]),C.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||be&&l.some(E=>E.id===be))return;const P=localStorage.getItem("markus_nav_after_remove");if(P&&(localStorage.removeItem("markus_nav_after_remove"),P.startsWith("channel:"))){gt("channel"),ks(P.slice(8)),S("chat");return}const R=l.find(E=>!E.teamId&&E.role?.toLowerCase()==="secretary")??l.find(E=>E.role?.toLowerCase()==="secretary")??l.find(E=>E.name?.toLowerCase().includes("secretary"));R?(gt("direct"),Yt(R.id),S("chat")):l.length>0&&(gt("direct"),Yt(l[0].id),S("chat"))},[l,be]);const Zn=C.useRef(!1),Pr=C.useRef(!1),yl=C.useRef(!1),Sl=C.useRef(0),Vn=C.useRef(0),[RS,ai]=C.useState(!1),Ii=C.useRef(0),[fm,mn]=C.useState(0),li=C.useCallback(()=>{Pr.current=!1,yl.current=!1,Br.current=!0},[]),Uh=C.useCallback(()=>{Pr.current=!0,Br.current=!1,Vn.current+=1,Zn.current=!1,ai(!0)},[]),gn=C.useCallback(P=>{const R=qn.current;if(!R)return;const E=R.scrollHeight-R.scrollTop-R.clientHeight,X=E<160,Y=E<48,oe=Sl.current,de=R.scrollTop<oe-2;if(Sl.current=R.scrollTop,de&&E>20){yl.current=!0,Uh();return}if(yl.current){Y?(li(),ai(!1),Ii.current=0,mn(0)):Uh();return}if(X&&!Pr.current){li(),ai(!1),Ii.current=0,mn(0);return}P?.fromProgrammatic||Zn.current||!Pr.current&&Br.current||Pr.current&&(Br.current=!1,ai(!0))},[Uh,li]);C.useEffect(()=>{const P=qn.current;if(!P)return;const R=()=>{yl.current=!0},E=()=>{gn({fromProgrammatic:Zn.current})};P.addEventListener("wheel",R,{passive:!0}),P.addEventListener("touchmove",R,{passive:!0}),P.addEventListener("scroll",E,{passive:!0});const X=typeof ResizeObserver<"u"?new ResizeObserver(()=>gn()):null;return X?.observe(P),Sl.current=P.scrollTop,gn(),()=>{P.removeEventListener("wheel",R),P.removeEventListener("touchmove",R),P.removeEventListener("scroll",E),X?.disconnect()}},[p,gn]);const Hh=C.useMemo(()=>new Set(Kp),[Kp]),os=C.useMemo(()=>{const P=ie==="channel"?zt:zt.filter(R=>!R.isActivityLog);return Hh.size===0?P:P.filter(R=>!(R.isNotification&&Hh.has(R.id)))},[zt,ie,Hh]);C.useEffect(()=>{jh.current=w==="chat"&&os.length>0,Ao()},[w,os.length,Ao]);const ci=ew({count:os.length,getScrollElement:()=>qn.current,getItemKey:P=>os[P]?.id??P,estimateSize:P=>{const R=os[P];return R?R.segments&&R.segments.length>0?300:R.text.length>500?200:120:120},overscan:8});ci.shouldAdjustScrollPositionOnItemSizeChange=(P,R,E)=>Im()?!1:P.start<(E.scrollOffset??0);const hi=C.useCallback((P="instant")=>{if(!Br.current||Pr.current)return;const R=++Vn.current;Zn.current=!0;const E=()=>R===Vn.current&&Br.current&&!Pr.current,X=()=>{if(R!==Vn.current)return;if(Zn.current=!1,!E()){gn();return}const Y=qn.current;Y&&(Sl.current=Y.scrollTop,Y.scrollHeight-Y.scrollTop-Y.clientHeight<160&&!Pr.current&&(li(),ai(!1),Ii.current=0,mn(0))),requestAnimationFrame(()=>{R===Vn.current&&gn({fromProgrammatic:!0})})};if(os.length>0)ci.scrollToIndex(os.length-1,{align:"end",behavior:P}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!E()){R===Vn.current&&(Zn.current=!1);return}ci.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(X)})});else{const Y=qn.current;Y&&Y.scrollTo({top:Y.scrollHeight,behavior:P}),requestAnimationFrame(X)}},[os.length,ci,gn,li]),pm=C.useRef(o);C.useEffect(()=>{pm.current=o},[o]),C.useLayoutEffect(()=>{if(gl.current){gl.current=!1;const P=wl.current;P>0&&(wl.current=0,ci.scrollToIndex(P,{align:"start",behavior:"instant"}));return}pm.current&&(!Br.current||Pr.current||Im()||hi())},[zt,hi,ci]);const mm=C.useRef(w);C.useEffect(()=>{const P=mm.current!=="chat";if(mm.current=w,w==="chat"&&P&&Br.current&&!Pr.current){const R=[],E=requestAnimationFrame(()=>hi("instant"));for(const X of[60,160,320])R.push(setTimeout(()=>hi("instant"),X));return()=>{cancelAnimationFrame(E);for(const X of R)clearTimeout(X)}}},[w,Ms,hi]);const gm=C.useRef(A);C.useEffect(()=>{if(gm.current===A||(gm.current=A,w!=="chat")||os.length===0||Ms||cl||!Br.current||Pr.current)return;const P=[],R=requestAnimationFrame(()=>hi("instant"));for(const E of[60,160,320])P.push(setTimeout(()=>hi("instant"),E));return()=>{cancelAnimationFrame(R);for(const E of P)clearTimeout(E)}},[A,w,os.length,Ms,cl,hi]);const Om=C.useCallback(async(P,R)=>{const E=R??`ch:${P}`;at.current===E&&oi(!0);try{const X=await K.channels.getMessages(P,50),Y=X.messages.map(oe=>Sn(oe,e?.id));ss.set(E,Y),at.current===E&&(Cs(Y),Dr(X.hasMore),kr.current=X.messages[0]?new Date(X.messages[0].createdAt).toISOString():null)}catch{at.current===E&&(Cs([]),Dr(!1))}finally{at.current===E&&oi(!1)}},[]),Gh=C.useCallback(async(P,R)=>{const E=at.current===R&&(ss.get(R)?.length??0)===0;E&&oi(!0);try{const{count:X,hasMore:Y,oldestCursor:oe}=await le(P,R,async()=>{const de=await K.sessions.getMessages(P,50);return{messages:k_(de.messages.map(dd).filter(ae=>ae.sender!=="agent"||ae.text||ae.segments&&ae.segments.length>0||ae.isStreaming)),hasMore:de.hasMore,oldestCursor:de.messages[0]?new Date(de.messages[0].createdAt).toISOString():null}});return Dr(Y),kr.current=oe,X}finally{E&&at.current===R&&oi(!1)}},[le,ss]),xm=C.useRef(new Map),On=C.useCallback(async(P,R,E)=>{if(!P||!R||R===Tt)return;let X=null;try{if($s.current&&!$s.current.signal.aborted&&Ye(E)?.has(R)){ln(E),at.current===E&&Os(!0);return}const Y=`${P}:${R}`,oe=xm.current.get(Y)??0;if(Date.now()-oe<1500)return;const de=await K.sessions.streamStatus(P,R),ae=[...ss.get(E)??[]].reverse().find(ve=>ve.sender==="agent"),ce=de.status==="streaming",We=!!de.active&&(de.status==="done"||de.status==="error")&&!!ae?.isStreaming;if(!ce&&!We)return;xm.current.set(Y,Date.now()),Ni.current?.abort(),X=new AbortController,Ni.current=X,ln(E),Os(!0),Ot(E,R);let Ze=ae?.id;if(!ae||ae.isError)Ze=`reattach_${Date.now()}`,ft(E,ve=>[...ve,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],R);else{const ve=(ae.segments??[]).filter(ze=>ze.type==="tool").map(ze=>ze.status==="stopped"||ze.status==="running"?{...ze,status:"running"}:ze);ft(E,ze=>ze.map(Qe=>Qe.id===ae.id?{...Qe,text:"",isStreaming:!0,isStopped:!1,segments:ve,committedSegments:void 0}:Qe),R)}let Ie=!1;const Te=ve=>{at.current===E&&(Li.current=Date.now(),ni(E,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(fe=>fe.id===Ze):-1,Me=De>=0?De:Qe.map((fe,ye)=>({m:fe,j:ye})).reverse().find(fe=>fe.m.sender==="agent")?.j??-1;if(Me<0)return ze;const qe=Qe[Me].segments??[],it=qe[qe.length-1],Rt=it?.type==="text"?it.thinking??"":"";let Gt="",Ns="",ne=ve;for(;ne.length>0;)if(Ie){const fe=ne.indexOf("</think>");fe>=0?(Gt+=ne.slice(0,fe),ne=ne.slice(fe+8),Ie=!1):(Gt+=ne,ne="")}else{const fe=ne.indexOf("<think>");fe>=0?(Ns+=ne.slice(0,fe),ne=ne.slice(fe+7),Ie=!0):(Ns+=ne,ne="")}const Ue=Rt+Gt||void 0,Ce=it?.type==="text"?[...qe.slice(0,-1),{type:"text",content:it.content+Ns,thinking:Ue,createdAt:it.createdAt}]:[...qe,{type:"text",content:Ns,thinking:Ue,createdAt:new Date().toISOString()}];return Qe[Me]={...Qe[Me],text:(Qe[Me].text??"")+Ns,segments:Ce,isStreaming:!0},Qe},R))},dt=ve=>{if(at.current===E&&(Li.current=Date.now(),ve.phase!=="heartbeat")){if((ve.phase==="start"||ve.phase==="end")&&an(E,{...ve,phase:ve.phase,ts:Date.now()},R),ve.phase==="start"){const ze=`${ve.tool}_${Date.now()}`,Qe=new Date().toISOString(),De=Me=>{const qe=[...Me];for(let it=qe.length-1;it>=0;it--){const Rt=qe[it];if(Rt.type==="tool"&&Rt.tool===ve.tool&&(Rt.status==="running"||Rt.status==="stopped"))return qe[it]={...Rt,status:"running",args:ve.arguments??Rt.args},qe}return qe.push({type:"tool",key:ze,tool:ve.tool,status:"running",args:ve.arguments,createdAt:Qe}),qe};ft(E,Me=>{const qe=[...Me],it=Ze?qe.findIndex(ne=>ne.id===Ze):-1;if(it<0)return Me;const Rt=De(qe[it].segments??[]),Gt=qe[it].committedSegments,Ns=Gt&&De(Gt);return qe[it]={...qe[it],segments:Rt,committedSegments:Ns,isStreaming:!0},qe},R)}else if(ve.phase==="end"){const ze=new Date().toISOString(),Qe=De=>{const Me=[...De];for(let qe=Me.length-1;qe>=0;qe--){const it=Me[qe];if(it.type==="tool"&&it.tool===ve.tool&&(it.status==="running"||it.status==="stopped")){Me[qe]={...it,status:ve.success===!1?"error":"done",args:ve.arguments??it.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,liveOutput:void 0,createdAt:ze};break}}return Me};ft(E,De=>{const Me=[...De],qe=Ze?Me.findIndex(Ns=>Ns.id===Ze):-1;if(qe<0)return De;const it=Qe(Me[qe].segments??[]),Rt=Me[qe].committedSegments,Gt=Rt&&Qe(Rt);return Me[qe]={...Me[qe],segments:it,committedSegments:Gt,isStreaming:!0},Me},R)}else if(ve.phase==="subagent_progress"&&ve.subagentEvent){const ze=Qe=>{const De=[...Qe];for(let Me=De.length-1;Me>=0;Me--){const qe=De[Me];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){De[Me]={...qe,status:"running",subagentLogs:Bm(qe.subagentLogs,ve.subagentEvent)};break}}return De};ni(E,Qe=>{const De=[...Qe],Me=Ze?De.findIndex(Gt=>Gt.id===Ze):-1;if(Me<0)return Qe;const qe=ze(De[Me].segments??[]),it=De[Me].committedSegments,Rt=it&&ze(it);return De[Me]={...De[Me],segments:qe,committedSegments:Rt,isStreaming:!0},De},R)}}},Be=ve=>{at.current===E&&(Li.current=Date.now(),ft(E,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(qe=>qe.id===Ze):-1;if(De<0)return ze;const Me=[...Qe[De].committedSegments??[]];if(ve.type==="thinking_commit")Me.push({type:"text",content:"",thinking:ve.content,createdAt:ve.createdAt});else if(ve.type==="text_commit")Me.push({type:"text",content:ve.content,createdAt:ve.createdAt});else return ze;return Qe[De]={...Qe[De],committedSegments:Me,isStreaming:!0},Qe},R))},st=ve=>{if(at.current!==E)return;Li.current=Date.now();const ze=(ve.segments??[]).map((Qe,De)=>Qe.type==="tool"?{type:"tool",key:`${Qe.tool}_${De}`,tool:Qe.tool??"tool",status:Qe.status==="error"?"error":Qe.status==="running"||Qe.status==="stopped"?"running":"done",args:Qe.arguments,result:Qe.result,error:Qe.error,durationMs:Qe.durationMs,createdAt:Qe.createdAt,...Qe.subagentLogs?.length?{subagentLogs:Qe.subagentLogs}:{}}:{type:"text",content:Qe.content??"",thinking:Qe.thinking,createdAt:Qe.createdAt});ft(E,Qe=>{const De=[...Qe],Me=Ze?De.findIndex(qe=>qe.id===Ze):-1;return Me<0?Qe:(De[Me]={...De[Me],text:ve.content||De[Me].text,segments:ze,committedSegments:ze,isStreaming:!0,isStopped:!1},De)},R);for(const Qe of ze)Qe.type==="tool"&&an(E,{tool:Qe.tool,phase:Qe.status==="running"||Qe.status==="stopped"?"start":"end",success:Qe.status!=="error",arguments:Qe.args,result:Qe.result,error:Qe.error,durationMs:Qe.durationMs,ts:Date.now()},R)},rt=await K.sessions.reattachStream(P,R,{onChunk:Te,onActivity:dt,onCommit:Be,onSnapshot:st},X.signal,0);if(!rt.attached){Ps(E),at.current===E&&(ft(E,ve=>{const ze=[...ve],Qe=Ze?ze.findIndex(qe=>qe.id===Ze):-1,De=Qe>=0?Qe:ze.map((qe,it)=>({m:qe,j:it})).reverse().find(qe=>qe.m.sender==="agent"&&qe.m.isStreaming)?.j??-1;if(De<0)return ve;const Me=ze[De];return Me.isStreaming?(ze[De]={...Me,isStreaming:!1,isStopped:Me.isError?Me.isStopped:!0},ze):ve},R),Os(!1));return}at.current===E&&(ft(E,ve=>{const ze=[...ve],Qe=Ze?ze.findIndex(it=>it.id===Ze):-1,De=Qe>=0?Qe:ze.map((it,Rt)=>({m:it,j:Rt})).reverse().find(it=>it.m.sender==="agent")?.j??-1;if(De<0)return ve;const Me=ze[De],qe=rt.segments?.length?Wm(rt.segments,Me.segments):void 0;return ze[De]={...Me,text:rt.content||Me.text,isStreaming:!1,isStopped:!1,...qe?{segments:qe,committedSegments:qe}:{}},ze},R),Os(!1)),Ps(E),Ni.current===X&&(Ni.current=null)}catch(Y){if(Ni.current===X&&(Ni.current=null),Ps(E),at.current===E&&Os(!1),Y instanceof Error&&Y.name==="AbortError")return}},[an,ln,Ps,Ye,ss,Ot,ft,ni]);C.useEffect(()=>{if(!o||t||ie!=="direct"||!be)return;const P=lt;!P||P===Tt||On(be,P,at.current)},[o,t,ie,be,lt,On]);const _l=C.useCallback(async P=>{if(!P)return hn([]),[];try{const{sessions:R}=await K.sessions.listByAgent(P,10);return hn(R),R}catch{return hn([]),[]}},[]),wl=C.useRef(0),AS=C.useCallback(async()=>{if(!(Th||!Zp||!kr.current)){Vp(!0);try{const P=at.current;if(ie==="channel"||ie==="dm"){const R=ie==="dm"?Ol(e?.id??"",Ut):mt,E=await K.channels.getMessages(R,50,kr.current),X=E.messages.map(Y=>Sn(Y,e?.id));wl.current=X.length,gl.current=!0,Cs(Y=>{let oe=[...X,...Y];return oe.length>500&&(oe=oe.slice(-500)),ss.set(P,oe),oe}),Dr(E.hasMore),E.messages[0]&&(kr.current=new Date(E.messages[0].createdAt).toISOString())}else if(lt){const R=await K.sessions.getMessages(lt,50,kr.current),E=R.messages.map(dd);wl.current=E.length,gl.current=!0,Cs(X=>{let Y=[...E,...X];return Y.length>500&&(Y=Y.slice(-500)),ss.set(P,Y),Y}),Dr(R.hasMore),R.messages[0]&&(kr.current=new Date(R.messages[0].createdAt).toISOString())}}catch{}finally{Vp(!1)}}},[Th,Zp,ie,mt,lt,e?.id,Ut]);um.current=AS;const Kh=C.useRef(!1),MS=C.useCallback(P=>{Kh.current||(Kh.current=!0,requestAnimationFrame(()=>{Kh.current=!1,P.target.scrollTop<100&&um.current?.()}))},[]);C.useEffect(()=>{if(t)return;const P=nc(ie,be,mt,Ut),R=at.current;at.current=P,R&&R!==P&&(Ws.set(R,Lo),lt&&ii.set(R,lt)),R!==P&&(li(),ai(!1),Ii.current=0,mn(0));const E=ss.get(P),X=Ws.get(P),Y=ii.get(P),oe=Ye(P),de=Y??lt,Se=tt(P)&&(ie!=="direct"||!oe||!de||oe.has(de)),ae=de??P,ce=Sr.get(ae)??[];if(yr(Se?ce:[]),Os(Se),ie==="direct"&&be&&_l(be),X&&X.length>0&&Xs(X),un(!1),E!==void 0&&E.length>0)if(Se||ol.completeLoad(P),oi(!1),Cs(E),Dr(!1),Y!==void 0&&Ir(Y),(!X||X.length===0)&&Xs([]),ie==="channel"||ie==="dm"){const Ze=ie==="dm"?Ol(e?.id??"",Ut):mt;Om(Ze,P)}else ie==="direct"&&be&&Y&&Y!==Tt&&(Se?On(be,Y,P):Gh(Y,P).then(()=>{at.current===P&&be&&On(be,Y,P)}));else if(al(P),oi(!0),Cs([]),Dr(!1),kr.current=null,ss.delete(P),ie==="channel"||ie==="dm"){const Ze=ie==="dm"?Ol(e?.id??"",Ut):mt;Om(Ze,P),(!X||X.length===0)&&Xs([])}else ie==="direct"&&be?_l(be).then(Ze=>{if(at.current===P)if(Ze.length>0){const Ie=Ze.find(De=>De.isMain),Te=Eh(be),dt=Ie?[Ie,...Ze.filter(De=>!De.isMain&&!Te.has(De.id)).slice(0,4)]:Ze.filter(De=>!Te.has(De.id)).slice(0,5);let Be=X&&X.length>0?X:dt;const st=pS(be),rt=Y!==void 0?Y:st??Ie?.id??Be[0].id;if(rt&&rt!==Tt&&!Be.some(De=>De.id===rt)){const De=Ze.find(Me=>Me.id===rt);De&&(Be=[...Be,De])}const ve=rt&&Be.some(De=>De.id===rt)?rt:Be[0].id;Ir(ve),ii.set(P,ve),dl(be,ve),Xs(Be);const Qe=Ze.find(De=>De.id===ve)?.metadata?.modelOverride;In(Qe?.provider&&Qe?.model?{provider:Qe.provider,model:Qe.model}:null),Gh(ve,P).then(()=>{at.current===P&&be&&On(be,ve,P)})}else Ir(null),In(null),oi(!1),(!X||X.length===0)&&Xs([])}).catch(()=>{at.current===P&&oi(!1)}):oi(!1)},[t,ie,be,mt,Ut,n.language,i]),C.useEffect(()=>t?void 0:yt.on("chat:message",R=>{const E=R.payload,X=E.channel??"";if(!X)return;const Y=E.senderType??"agent",oe=E.text??E.message??"",de=E.senderId??E.agentId??"",Se=E.senderName??E.agentId??i("page.fallbackAgent"),ae=E.metadata,ce=E.messageId??E.id??"";if(ce&&Ai.current.has(ce))return;const We=Y==="human"&&de===(e?.id??""),Ze={id:ce||`ws_${Date.now()}_${de}`,sender:We?"user":"agent",text:oe,time:new Date().toLocaleTimeString(),agentName:We?void 0:Se,agentId:We?void 0:de,replyToId:E.replyToId??void 0,replyToSender:E.replyToSender??void 0,replyToText:E.replyToText??void 0};if(ae&&Y==="agent"){const Te=[];if(ae.thinking?.length&&Te.push({type:"text",content:"",thinking:ae.thinking.join(`
72
+ `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Qr.navigate(Kt.TEAM,{agentId:s,prefillMessage:T})},L=async Z=>{if(y?.file===Z){_(null);return}try{const z=await K.agents.roleDiff(s,Z);z.agentContent!=null&&z.templateContent!=null&&_({file:Z,agent:z.agentContent,template:z.templateContent})}catch{}};if(i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},j=Z=>{const z=$[Z];return z?e(`agent:profilePage.filesTab.fileLabels.${z}`):Z},I=p?.hasTemplate&&!p.isUpToDate,V=a?Q.some(Z=>Z.file===a):!1;return h.jsxs("div",{className:"space-y-4",children:[I&&h.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[h.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),h.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:Q.length,templateId:p.templateId})," ",Q.map(Z=>Z.file).join(", ")]})]}),h.jsx("button",{onClick:()=>N(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),h.jsxs(as,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",h.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[h.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(Z=>{const z=Q.some(J=>J.file===Z.name);return h.jsxs("button",{onClick:()=>w(Z.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===Z.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[Z.name,z&&h.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.name)})}),a&&h.jsxs("div",{children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("div",{className:"text-xs text-fg-secondary",children:j(a)}),h.jsxs("div",{className:"flex gap-2 items-center",children:[V&&h.jsxs(h.Fragment,{children:[h.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),h.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&h.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[h.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),g(!0),setTimeout(()=>g(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),h.jsx("button",{onClick:()=>{K.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&h.jsx(pM,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),h.jsx(gM,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{c(Z),O(!0)},dirty:m,onSave:S}),a==="ROLE.md"&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&h.jsx(ih,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function gM({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=C.useState(!1),o=C.useRef(null);return C.useEffect(()=>{n&&o.current?.focus()},[n]),C.useEffect(()=>{a(!1)},[s]),n||r?h.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):h.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[h.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx(uM,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const OM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_"]}];function xM(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of OM){const l=e(`agent:toolCategories.${a}`),c=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));c.length>0&&(t.set(l,c),c.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),c=e("agent:toolCategories.mcp",{server:l});t.has(c)||t.set(c,[]),t.get(c).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function bM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function vM({tools:s}){const{t:e}=At(["agent","common"]),t=xM(s,e);return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>h.jsx(as,{title:`${r.category} (${r.tools.length})`,children:h.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=y_(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,c=bM(i.description||"");return h.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[h.jsx(S_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&h.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&h.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),c&&h.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:c,children:c})]})]},i.name)})})},r.category)),s.length===0&&h.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function yM({agent:s}){const{t:e}=At(["agent","common"]),t=s.proficiency??{},[r,i]=C.useState(null),[n,a]=C.useState(null),[o,l]=C.useState(!1),c=s.availableSkills??[],d=new Map;for(const m of c){const O=m.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(m)}const u=async m=>{if(r===m){i(null),a(null);return}i(m),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(m)}`);if(O.ok){const p=await O.json();a(p.skill)}else a(null)}catch{a(null)}l(!1)},f={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},g=m=>{const O=t[m.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:O.uses,successes:O.successes}),O.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(O.lastUsed).toLocaleDateString()})]}),y=r===m.name;return h.jsxs("div",{children:[h.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(m.name),children:[h.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:m.name}),m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),m.builtIn&&!m.alwaysOn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!m.builtIn&&h.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:m.description}),x]}),p!==null&&h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:h.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&h.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(_=>h.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:_},_))]}),n.description&&h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&h.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(_=>h.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",_]},_))}),(n.toolDetails??n.tools??[]).length>0&&h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),h.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(_=>h.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[h.jsx("div",{className:"text-xs font-medium text-brand-500",children:_.name}),_.description&&h.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:_.description})]},_.name))})]})]}):h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},m.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],b=[...d.entries()].sort((m,O)=>{const p=v.indexOf(m[0]),x=v.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:c.length})})}),b.map(([m,O])=>h.jsx(as,{title:h.jsxs("span",{className:"capitalize",children:[m," ",h.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:h.jsx("div",{className:"space-y-2",children:O.map(p=>g(p))})},m)),c.length===0&&h.jsx(ih,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function ux({tools:s,agent:e}){const{t}=At(["agent","common"]),[r,i]=C.useState("tools");return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>h.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?h.jsx(vM,{tools:s}):h.jsx(yM,{agent:e})]})}function fx({agentId:s}){const{t:e}=At(["agent","common"]),[t,r]=C.useState(null),[i,n]=C.useState(!0),[a,o]=C.useState("longterm"),[l,c]=C.useState(""),[d,u]=C.useState(""),[f,g]=C.useState(!1),[v,b]=C.useState(null),[m,O]=C.useState(null),[p,x]=C.useState([]),[y,_]=C.useState(!1),k=C.useCallback(()=>{n(!0),K.agents.getMemory(s).then($=>{r($),c($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);C.useEffect(()=>{k()},[k]);const w=async()=>{g(!0),await K.agents.updateDailyMemory(s,l).catch(()=>{}),g(!1),k()},S=async()=>{g(!0),await K.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),g(!1),k()},Q=l!==(t?.recentDailyLogs??""),N=d!==(t?.longTermMemory??"");if(i)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"flex gap-2",children:L.map($=>h.jsx("button",{onClick:()=>o($.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===$.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:$.label},$.key))}),a==="entries"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?h.jsx(ih,{text:e("agent:profilePage.memoryTab.noEntries")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,j)=>{const I=v===j;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>b(I?null:j),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.type==="fact"?"bg-blue-500/15 text-blue-600":$.type==="task"?"bg-green-500/15 text-green-600":$.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:$.type}),h.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${I?"":"line-clamp-2"}`,children:$.content}),h.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&h.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${$.importance>=7?"bg-red-500/15 text-red-500":$.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",$.importance]}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:I?"▲":"▼"})]})]}),I&&h.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[h.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),h.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[h.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&h.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),h.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},j)})})}),a==="sessions"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?h.jsx(ih,{text:e("agent:profilePage.memoryTab.noSessions")}):h.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const j=m===$.id,I=async()=>{if(j){O(null),x([]);return}O($.id),_(!0);try{const V=await K.agents.getMemorySession(s,$.id);x(V.messages)}catch{x([])}_(!1)};return h.jsxs("div",{children:[h.jsxs("button",{onClick:I,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[h.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),h.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),h.jsx("span",{className:"text-fg-tertiary text-[10px]",children:j?"▲":"▼"})]}),j&&h.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?h.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const V=new Map;for(const Z of p)Z.role==="tool"&&Z.toolCallId&&V.set(Z.toolCallId,Z.content);return h.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(Z=>Z.role!=="tool").map((Z,z)=>h.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.role==="system")&&h.jsxs("div",{children:[h.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(Oa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&h.jsxs("div",{className:"space-y-1",children:[Z.content&&h.jsxs("div",{children:[h.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),h.jsx("div",{className:"text-xs text-fg-secondary",children:h.jsx(Oa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&h.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(J=>{let T;try{T=JSON.parse(J.arguments)}catch{}const A={tool:J.name,status:"done",args:T,result:V.get(J.id)};return h.jsx(g_,{entry:{type:"tool",info:A}},J.id)})})]})]},z))})})()})]},$.id)})})}),a==="daily"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:Q?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>c(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:w,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:l,onChange:$=>c($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&h.jsx(as,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:N?h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),h.jsx("button",{onClick:S,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:h.jsx("textarea",{value:d,onChange:$=>u($.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function px({agentId:s,initialData:e}){const{t}=At(["agent","common"]),[r,i]=C.useState(e??null),[n,a]=C.useState(!e),[o,l]=C.useState([]),[c,d]=C.useState(null),[u,f]=C.useState(!1),[g,v]=C.useState(null),b=C.useCallback(()=>Promise.all([K.agents.getHeartbeat(s).then(i).catch(()=>{}),K.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);C.useEffect(()=>{a(!0),b().finally(()=>a(!1))},[b]),C.useEffect(()=>yt.on("agent:update",_=>{_.payload?.agentId===s&&b()}),[s,b]);const m=async()=>{f(!0),v(null);try{const y=await K.agents.triggerHeartbeat(s);v(y.message),setTimeout(()=>v(null),4e3),setTimeout(b,2e3)}catch(y){v(String(y).replace("Error: ",""))}f(!1)},O=async y=>{try{await K.agents.cancelWakeup(s,y),b()}catch{}};if(n)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return h.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=y=>y?y<1e3?`${y}ms`:y<6e4?`${(y/1e3).toFixed(1)}s`:`${(y/6e4).toFixed(1)}m`:null,x=y=>{if(!y)return null;const _=Date.now()-new Date(y).getTime();if(_<0){const k=Math.abs(_);return k<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(k/1e3)}):k<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(k/6e4)}):t("agent:profilePage.relative.inHours",{hours:(k/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return h.jsxs("div",{className:"space-y-4",children:[h.jsxs(as,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:b,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),h.jsx("button",{onClick:m,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[h.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[h.jsx(fs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),h.jsx(_M,{agentId:s,intervalMs:r.intervalMs,onChanged:b}),h.jsx(fs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?x(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),h.jsx(fs,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?x(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),h.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),g&&h.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:g})]}),r.wakeups&&r.wakeups.length>0&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[x(y.wakeAt)??new Date(y.wakeAt).toLocaleString(),y.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${y.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),h.jsx("button",{onClick:()=>O(y.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},y.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(y=>h.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[h.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${y.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${x(y.timeoutAt)??new Date(y.timeoutAt).toLocaleString()}`]})]})]},y.id))})}),r.lastSummary&&h.jsx(as,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:h.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:h.jsx(Oa,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?h.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:h.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const _=c===y.id;return h.jsxs("div",{children:[h.jsxs("button",{onClick:()=>d(_?null:y.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[h.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),h.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),h.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),h.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:h.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&h.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:h.jsx(Xa,{agentId:s,activityId:y.id})})]},y.id)})})}):r.lastHeartbeat?null:h.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:h.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[h.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),h.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),h.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&h.jsx("button",{onClick:m,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function SM({taskId:s,isLive:e}){const{t}=At("agent"),[r,i]=C.useState([]),[n,a]=C.useState(""),[o,l]=C.useState(!0),[c,d]=C.useState("compact");if(C.useEffect(()=>{l(!0),a(""),K.tasks.getLogs(s).then(g=>{i(g.logs),l(!1)}).catch(()=>l(!1))},[s]),C.useEffect(()=>{if(!e)return;const g=yt.on("task:log",b=>{const m=b.payload;if(m.taskId!==s)return;const O={id:m.id,taskId:m.taskId,agentId:m.agentId,seq:m.seq,type:m.logType,content:m.content,metadata:m.metadata,createdAt:m.createdAt};i(p=>O.id&&p.some(x=>x.id===O.id)?p:[...p,O]),O.type==="text"&&a("")}),v=yt.on("task:log:delta",b=>{const m=b.payload;m.taskId===s&&a(O=>O+m.text)});return()=>{g(),v()}},[s,e]),o)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(g=>v_(g)),f=new Set(u.filter(g=>g.executionRound!=null).map(g=>g.executionRound)).size>1;return h.jsx("div",{className:"px-3 py-2",children:c==="compact"?h.jsx(Rx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):h.jsx(Ax,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function Xa({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=At("agent"),[i,n]=C.useState([]),[a,o]=C.useState(!0),[l,c]=C.useState("compact");if(C.useEffect(()=>{o(!0),K.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),C.useEffect(()=>t?yt.on("agent:activity_log",f=>{const g=f.payload;if(g.agentId!==s||g.activityId!==e)return;const v={seq:g.seq,type:g.type,content:g.content,metadata:g.metadata,createdAt:g.createdAt};n(b=>b.some(m=>m.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return h.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>b_(u,e,s)).filter(u=>u!==null);return h.jsx("div",{className:"px-3 py-2",children:l==="compact"?h.jsx(Rx,{entries:d,isActive:t,onExpand:()=>c("full")}):h.jsx(Ax,{entries:d,isActive:t,onCollapse:()=>c("compact")})})}function as({title:s,action:e,children:t}){return h.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[h.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),h.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function fs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return h.jsxs("div",{className:"flex items-baseline gap-1.5",children:[h.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const mx=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],gx=5,Ox=1440;function _M({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=At(["agent","common"]),[i,n]=C.useState(!1),[a,o]=C.useState(null),[l,c]=C.useState(!1),[d,u]=C.useState(String(Math.round(e/6e4))),f=p=>p%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),g=async p=>{n(!0),o(null);try{await K.agents.updateConfig(s,{heartbeatIntervalMs:p}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=p=>{if(p.target.value==="custom"){c(!0);return}c(!1),g(Number(p.target.value))},b=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<gx||p>Ox){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}g(p*60*1e3)},m=mx.includes(e),O=l||!m?"custom":String(e);return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),h.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!m&&h.jsx("option",{value:String(e),children:f(e)}),mx.map(p=>h.jsx("option",{value:String(p),children:f(p)},p)),h.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!m)&&h.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[h.jsx("input",{type:"number",min:gx,max:Ox,value:d,onChange:p=>u(p.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),h.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&h.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function ih({text:s}){return h.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function xx(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const bx={0:"0",1:"1",2:"2",3:"3",4:"4"},vx={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},wM={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"},kM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},rc={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},CM=["all","interaction","task","notification","system"],PM={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"]},TM={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"},QM={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 bu(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function yx(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Qf(d,e),g=Qf(u,e),v=QM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:g}),badge:{label:g,color:v}}}const c=r.match(/^Task:\s*(.+)/);return c?{title:c[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=bu(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=bu(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a[2],text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a[2]});return{title:a[1],subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=bu(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function Sx({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r,onAgentStateChange:i}){const{t:n}=At(["agent","common","team"]),[a,o]=C.useState(null),[l,c]=C.useState(null),[d,u]=C.useState(!0),[f,g]=C.useState("all"),[v,b]=C.useState("all"),[m,O]=C.useState(e??null),[p,x]=C.useState(e??null),[y,_]=C.useState(!1),[k,w]=C.useState(!0),[S,Q]=C.useState(null),N=50,L=3,$=C.useCallback(async(T=!0)=>{T&&u(!0);try{const A=f==="all"?void 0:f,B=v==="all"?void 0:v,[q,H]=await Promise.all([K.agents.getMindState(s),K.agents.getMailbox(s,{limit:N,category:A,status:B})]);o(q),c(H),w((H.history?.length??0)>=N)}catch{}u(!1)},[s,f,v]),j=C.useCallback(async()=>{if(!l)return;const T=f==="all"?void 0:f,A=v==="all"?void 0:v;try{const B=await K.agents.getMailbox(s,{limit:N,offset:l.history.length,category:T,status:A});c(q=>q?{...q,history:[...q.history,...B.history]}:B),w((B.history?.length??0)>=N)}catch{}},[s,l,f,v]);C.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const I=C.useRef(!1);if(C.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){I.current=!1;const A=document.getElementById(`mbx-${p}`);if(A){setTimeout(()=>A.scrollIntoView({behavior:"smooth",block:"center"}),100);const B=setTimeout(()=>x(null),3e3);return()=>clearTimeout(B)}}else k&&!I.current&&(I.current=!0,(async()=>{let A=l?.history??[],B=k;for(;B;)try{const q=await K.agents.getMailbox(s,{limit:N,offset:A.length}),H=[...A,...q.history];A=H,B=(q.history?.length??0)>=N;const te=q.history.some(ue=>ue.id===p);if(c(ue=>ue?{...ue,history:H}:q),w(B),te||!B)break}catch{break}I.current=!1})())},[p,d,l,k,s]),C.useEffect(()=>{let T=null;const A=q=>{q.payload?.agentId===s&&(T&&clearTimeout(T),T=setTimeout(()=>{T=null,$(!1)},500))},B=[yt.on("agent:mailbox",A),yt.on("agent:decision",A),yt.on("agent:attention",A),yt.on("agent:focus",A),yt.on("agent:update",A),yt.on("agent:triage",A)];return()=>{T&&clearTimeout(T),B.forEach(q=>q())}},[s,$]),d&&!a)return h.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:n("agent:profilePage.mind.loading")});const V=a?.mailboxDepth??a?.queuedItems?.length??0,Z=(()=>{const T=a?.attentionState??"idle";return T==="deciding"||T==="idle"&&V>0?"deciding":T!=="idle"&&!a?.currentFocus?"idle":T})(),z=Z==="idle"&&l?.history?.some(T=>T.status==="processing"),J=(a?.attentionState??"idle")==="idle"&&V>0;return h.jsxs("div",{className:"space-y-4",children:[h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[h.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${kM[Z]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${Z}`)}),a?.currentFocus?(()=>{const T=yx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return h.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[h.jsxs("span",{children:[rc[a.currentFocus.type]??"●"," ",h.jsx("span",{className:"text-fg-primary font-medium",children:T.title}),T.subtitle&&h.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:T.subtitle}),h.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&h.jsxs("button",{onClick:()=>Q(a.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]})})():J?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.queuedButIdle",{count:V,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):Z==="deciding"?h.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:V})}):h.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&t==="offline"&&h.jsxs("button",{onClick:()=>{K.agents.start(s).then(()=>{i?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-green-500/15 text-green-500 hover:bg-green-500/25 transition-colors",children:["▶ ",n("agent:profilePage.mind.continueBtn")]}),r&&(t==="working"||t==="idle")&&h.jsxs("button",{onClick:()=>{K.agents.stop(s).then(()=>{i?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors",children:["■ ",n("team:contextMenu.stop")]}),h.jsx("button",{onClick:()=>{$()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:n("agent:profilePage.mind.refresh")})]})]}),z&&h.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[h.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),h.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const T=a.queuedItems,A=T.length>L,B=A&&!y?T.slice(0,L):T,q=T.reduce((H,te)=>(H[te.sourceType]=(H[te.sourceType]??0)+1,H),{});return h.jsxs("div",{className:"mb-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:T.length})}),h.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(q).map(([H,te])=>h.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[rc[H]??"●"," ",te]},H))})]}),h.jsxs("div",{className:"space-y-1",children:[B.map((H,te)=>h.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[h.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:te+1}),h.jsx("span",{className:"text-sm",children:rc[H.sourceType]??"●"}),h.jsx("span",{className:`text-[10px] ${vx[H.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${bx[H.priority]??H.priority}`,{defaultValue:`P${H.priority}`})}),h.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:H.summary}),h.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(H.queuedAt).toLocaleTimeString()})]},H.id)),A&&h.jsx("button",{onClick:()=>_(!y),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:y?n("agent:profilePage.mind.collapseQueue"):n("agent:profilePage.mind.expandQueue",{count:T.length-L})})]})]})})()]}),(a?.notebook?.length??0)>0&&h.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:h.jsxs("details",{open:!0,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"📓"}),h.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),h.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),h.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(T=>{const A=Date.now()-T.updatedAt,B=A<6e4?`${Math.round(A/1e3)}s ago`:A<36e5?`${Math.round(A/6e4)}min ago`:`${(A/36e5).toFixed(1)}h ago`,q=T.managed==="system"?"text-blue-400":T.managed==="cpp"?"text-purple-400":"text-emerald-400";return h.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-medium text-fg-primary",children:T.key}),h.jsxs("span",{className:`text-[10px] ${q}`,children:["[",T.managed,"]"]}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:B})]}),h.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:T.text.length>500?T.text.slice(0,500)+"…":T.text})]},T.key)})})]})}),a?.deliberationActivity&&h.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),h.jsx(Xa,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return h.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:h.jsxs("details",{open:!A,children:[h.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[h.jsx("span",{className:"text-sm",children:"🧠"}),h.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),h.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),h.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),h.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:n("agent:profilePage.mind.deferred",{count:a.lastTriage.deferredItemIds.length})}),a.lastTriage.droppedItemIds.length>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:n("agent:profilePage.mind.dropped",{count:a.lastTriage.droppedItemIds.length})}),(a.lastTriage.inlineCompletedIds?.length??0)>0&&h.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:n("agent:profilePage.mind.inlineCompleted",{count:a.lastTriage.inlineCompletedIds.length})})]})]})})})(),h.jsxs("section",{children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[h.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),h.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:CM.map(T=>{const A=l?.sourceTypeCounts,B=T==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?(PM[T]??[]).reduce((q,H)=>q+(A[H]??0),0):void 0;return h.jsxs("button",{onClick:()=>g(T),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===T?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[n(`agent:profilePage.mind.categoryFilters.${T}`),B!=null&&B>0&&h.jsx("span",{className:"ml-1 opacity-60",children:B})]},T)})})]}),h.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(T=>{const A=l?.statusCounts,B=T.key==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?.[T.key];return h.jsxs("button",{onClick:()=>b(T.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===T.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[T.dot&&h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T.dot}`}),n(`agent:profilePage.mind.statusFilters.${T.key}`),B!=null&&B>0&&h.jsx("span",{className:"ml-1 opacity-60",children:B})]},T.key)})}),(!l?.history||l.history.length===0)&&!d&&h.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),h.jsx("div",{className:"space-y-1",children:l?.history?.map(T=>{const A=m===T.id,B=rc[T.sourceType]??"●",q=yx(T,n),H=T.metadata?.senderName,te=T.metadata?.senderRole,ue=p===T.id;return h.jsxs("div",{id:`mbx-${T.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${ue?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[h.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>O(A?null:T.id),children:[h.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),h.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${TM[T.status]??"bg-gray-400"}`}),h.jsx("span",{className:"text-sm",children:B}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:q.title}),q.badge&&h.jsx("span",{className:`text-[10px] font-medium shrink-0 ${q.badge.color}`,children:q.badge.label}),h.jsx("span",{className:`text-[10px] shrink-0 ${vx[T.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${bx[T.priority]??T.priority}`,{defaultValue:""})})]}),q.subtitle&&h.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:q.subtitle}),h.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[h.jsx("span",{children:new Date(T.queuedAt).toLocaleString()}),T.completedAt&&h.jsxs("span",{children:["→ ",new Date(T.completedAt).toLocaleTimeString()]}),T.activity&&h.jsxs(h.Fragment,{children:[T.activity.totalTokens>0&&h.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:Kn(T.activity.totalTokens)})}),T.activity.totalTools>0&&h.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:T.activity.totalTools})})]})]})]}),h.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:T.sourceType}),r&&T.status==="processing"&&h.jsxs("button",{onClick:ke=>{ke.stopPropagation(),Q(T.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",n("agent:profilePage.mind.cancelCurrentBtn")]})]}),A&&h.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[H&&h.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",h.jsx("span",{className:"text-fg-secondary",children:H}),te&&h.jsxs("span",{className:"text-fg-tertiary",children:[" (",te,")"]})]}),T.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(T.sourceType)&&h.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:T.payload.content}),T.decisions&&T.decisions.length>0&&h.jsxs("div",{children:[h.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),h.jsx("div",{className:"space-y-1",children:T.decisions.map(ke=>h.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[h.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${wM[ke.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:ke.decisionType}),h.jsx("span",{className:"text-fg-secondary flex-1",children:ke.reasoning}),h.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(ke.createdAt).toLocaleTimeString()})]},ke.id))})]}),T.activity?h.jsxs("div",{children:[h.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:T.activity.label}),h.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${T.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:T.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),T.activity.type==="task"&&T.payload?.taskId?h.jsx(SM,{taskId:T.payload.taskId,isLive:!T.activity.endedAt}):h.jsx(Xa,{agentId:s,activityId:T.activity.id,isLive:!T.activity.endedAt})]}):T.status==="processing"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):T.status==="completed"?h.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},T.id)})}),k&&(l?.history?.length??0)>0&&h.jsx("div",{className:"text-center mt-3",children:h.jsx("button",{onClick:j,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),S&&h.jsx(_o,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{Q(null),K.agents.cancelProcessing(s).then(()=>{let T=0;const A=()=>{T+=1,$(),T<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>Q(null)})]})}function _x({agentId:s}){const{t:e}=At(["agent","common"]),t=nh(),[r,i]=C.useState([]),[n,a]=C.useState(!0),[o,l]=C.useState(null),c=C.useCallback(u=>{t?.openRightPanel?t.openRightPanel({kind:"deliverable",deliverable:u}):l(u)},[t]),d=C.useCallback(async()=>{a(!0);try{const{results:u}=await K.deliverables.search({agentId:s,limit:200});i(u)}catch{i([])}a(!1)},[s]);return C.useEffect(()=>{d()},[d]),C.useEffect(()=>{const u=yt.on("deliverable:created",()=>d()),f=yt.on("deliverable:updated",()=>d()),g=yt.on("deliverable:removed",()=>d());return()=>{u(),f(),g()}},[d]),n?h.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(u=>h.jsxs("div",{className:"animate-pulse space-y-2",children:[h.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),h.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},u))}):r.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[h.jsx("span",{className:"text-3xl mb-3",children:"📦"}),h.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),h.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(u=>{const f=O_[u.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},g=Nm[u.status]??Nm.active;return h.jsxs("button",{onClick:()=>c(u),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[h.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${f.color}`,children:f.icon}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:u.title}),h.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${g.color}`,children:u.status})]}),u.summary&&h.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:u.summary}),h.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[h.jsx("span",{children:new Date(u.createdAt).toLocaleDateString()}),u.tags.length>0&&h.jsx("span",{children:u.tags.slice(0,3).join(", ")})]})]}),h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},u.id)})]}),o&&h.jsx(x_,{item:o,onClose:()=>l(null),onOpenInPage:u=>{l(null),Qr.navigate(Kt.DELIVERABLES,{openDeliverable:u})}})]})}const $M=C.lazy(()=>Mx(()=>import("./index-B1VN5yM1.js").then(s=>s.aE),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),qp=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],wx={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function kx({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=At("team"),[o,l]=C.useState(null),[c,d]=C.useState(null),[u,f]=C.useState("overview"),g=r&&i?i:u,[v,b]=C.useState(""),[m,O]=C.useState(""),[p,x]=C.useState(!1),[y,_]=C.useState(!1),[k,w]=C.useState(""),[S,Q]=C.useState(""),N=C.useRef(null),L=C.useRef(null),$=C.useRef(null),j=C.useRef(null),[I,V]=C.useState(!1),[Z,z]=C.useState(!1),[J,T]=C.useState(""),[A,B]=C.useState(""),[q,H]=C.useState(!1),[te,ue]=C.useState([]),ke=C.useRef(null),U=C.useCallback(async()=>{try{const ge=(await K.teams.list()).teams.find(nt=>nt.id===s);ge&&l(ge);const He=await K.teams.status(s);ue(He.agents)}catch{}},[s]),D=C.useCallback(async()=>{try{const me=await K.teams.getFile(s,"ANNOUNCEMENT.md");b(me.content)}catch{b("")}try{const me=await K.teams.getFile(s,"NORMS.md");O(me.content)}catch{O("")}},[s]);C.useEffect(()=>{f("overview"),U(),D()},[s,U,D]),C.useEffect(()=>{p&&L.current&&L.current.focus()},[p]),C.useEffect(()=>{y&&j.current&&j.current.focus()},[y]);const se=async(me,ge)=>{V(!0);try{await K.teams.updateFile(s,me,ge),me==="ANNOUNCEMENT.md"?(b(ge),x(!1)):(O(ge),_(!1))}catch{}V(!1)},F=async()=>{J.trim()&&(await K.teams.update(s,{name:J.trim()}),z(!1),U())},G=async()=>{await K.teams.update(s,{description:A}),H(!1),U()};if(!o)return h.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const ee=o.members.find(me=>me.agentRole==="manager"),we=te.filter(me=>me.status!=="offline").length,Ae=g==="announcements"&&p||g==="norms"&&y;if(r)return h.jsx("div",{className:`flex-1 bg-surface-primary ${Ae?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:h.jsxs("div",{className:`${Ae?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const ge=te.find(Ct=>Ct.id===me.id),He=wx[ge?.status??"offline"]??"bg-gray-500",nt=me.type==="agent";return h.jsxs("div",{onClick:()=>nt&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${nt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:me.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ge?.status??"offline"}),me.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),nt&&n&&h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),g==="announcements"&&h.jsx(ic,{content:v,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:L,contentRef:N,saving:I,onSave:()=>se("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),g==="norms"&&h.jsx(ic,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:I,onSave:()=>se("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),g==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:ke,value:J,onChange:me=>T(me.target.value),onKeyDown:me=>me.key==="Enter"&&F(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),h.jsx("button",{onClick:F,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:me=>B(me.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:G,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(Cx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const xe=u==="announcements"&&p||u==="norms"&&y;return h.jsxs("div",{className:`flex-1 bg-surface-primary ${xe?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[h.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:h.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),h.jsx("circle",{cx:"9",cy:"7",r:"4"}),h.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),h.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h.jsx("h2",{className:"text-base font-semibold",children:o.name}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),h.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[we," online"]})]}),h.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),h.jsxs("button",{onClick:async()=>{if(o)try{const{files:me}=await K.teams.getFilesMap(o.id),ge=o.members.filter(nt=>nt.type==="agent"),He={type:"team",name:Ex(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:ge.map(nt=>({name:nt.name,roleName:nt.role,role:nt.agentRole??"worker",count:1,skills:[]}))}};await Rf.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:He,files:me}),d({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(me){d({title:"Hub",message:`Failed to publish: ${me}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[h.jsx("span",{children:"↑"})," Hub"]}),t&&h.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),h.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:qp.map(me=>h.jsxs("button",{onClick:()=>f(me.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${u===me.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[me.icon," ",a(me.labelKey)]},me.key))})]}),h.jsxs("div",{className:`${xe?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),h.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),h.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const ge=te.find(Ct=>Ct.id===me.id),He=wx[ge?.status??"offline"]??"bg-gray-500",nt=me.type==="agent";return h.jsxs("div",{onClick:()=>nt&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${nt&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[h.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium",children:me.name}),h.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),h.jsx("span",{className:"text-xs text-fg-tertiary",children:ge?.status??"offline"}),me.agentRole==="manager"&&h.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),h.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),nt&&n&&h.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&h.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&h.jsx(ic,{content:v,draft:k,setDraft:w,editing:p,setEditing:x,textareaRef:L,contentRef:N,saving:I,onSave:()=>se("ANNOUNCEMENT.md",k),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&h.jsx(ic,{content:m,draft:S,setDraft:Q,editing:y,setEditing:_,textareaRef:j,contentRef:$,saving:I,onSave:()=>se("NORMS.md",S),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&h.jsxs("div",{className:"space-y-5",children:[h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?h.jsxs("div",{className:"flex gap-2 items-center",children:[h.jsx("input",{ref:ke,value:J,onChange:me=>T(me.target.value),onKeyDown:me=>me.key==="Enter"&&F(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),h.jsx("button",{onClick:F,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm",children:o.name}),h.jsx("button",{onClick:()=>{T(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?h.jsxs("div",{className:"space-y-2",children:[h.jsx("textarea",{value:A,onChange:me=>B(me.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:G,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),h.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),h.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),h.jsx(Cx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),c&&h.jsx(_o,{alertOnly:!0,variant:c.variant??"primary",title:c.title,message:c.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function ic({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:c,emptyText:d}){return r?h.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[h.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:c}),o&&h.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):h.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?h.jsx(C.Suspense,{fallback:h.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:h.jsx($M,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):h.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Cx({teamId:s,teamName:e,onDeleted:t}){const[r,i]=C.useState(!1),[n,a]=C.useState(!1),[o,l]=C.useState(!1),[c,d]=C.useState(!1);return h.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[h.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),h.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{disabled:c,onClick:async()=>{d(!0);try{await K.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:c?"Deleting...":"Confirm Delete"}),h.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):h.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function nc(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}class bi{currentConvKey="";loadingSession=null;msgBuffers=new Map;sessionMsgCache=new Map;activeSession=new Map;actBuffers=new Map;sessionTabs=new Map;phase=new Map;sendCount=new Map;streamingSessions=new Map;sessionCacheOrder=[];static MAX_MESSAGES=500;static MAX_CONVERSATIONS=20;static MAX_SESSION_CACHE=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){return this.phase.get(e)??"idle"}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e){this.phase.set(e,"idle"),this.activeSession.delete(e)}updateMessages(e,t,r){const i=this.activeSession.get(e),n=!r||i===r||i===void 0,a=n?this.msgBuffers.get(e)??[]:this.sessionMsgCache.get(r)??[];let o=t(a);o.length>bi.MAX_MESSAGES&&(o=o.slice(-500));let l=!1;return n&&(this.msgBuffers.set(e,o),this.evictIfNeeded(e),l=this.currentConvKey===e),r&&r!==bi.NEW_CHAT_ID&&(this.sessionMsgCache.set(r,o),this.touchSessionCache(r)),{displayChanged:l,newMessages:l?o:void 0}}applyLoadResult(e,t,r){const i=this.sessionMsgCache.get(t),n=this.isCacheFresher(t,r);n||(this.sessionMsgCache.set(t,r),this.touchSessionCache(t));const a=this.getPhase(e),o=this.activeSession.get(e);if(this.currentConvKey===e&&(this.loadingSession===t||o===t)&&a!=="streaming"){const c=this.mergeDbWithCache(r,n?i:void 0);return this.msgBuffers.set(e,c),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:c}}return{displayChanged:!1}}mergeDbWithCache(e,t){if(!t||t.length===0)return[...e];const r=new Set,i=[];for(const n of e)r.add(n.id),i.push(n);for(const n of t){if(r.has(n.id))continue;const a=n.rawCreatedAt?Date.parse(n.rawCreatedAt):NaN;let o=i.length;for(;o>0&&i[o-1].rawCreatedAt&&Number.isFinite(a);){const l=Date.parse(i[o-1].rawCreatedAt);if(!Number.isFinite(l)||l<=a)break;o--}i.splice(o,0,n),r.add(n.id)}return i}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.activeSession.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.activeSession.get(e)}setActiveSession(e,t){this.activeSession.set(e,t)}saveToCache(e,t){if(!t||t===bi.NEW_CHAT_ID)return;const r=this.msgBuffers.get(e);r&&r.length>0&&(this.sessionMsgCache.set(t,r),this.touchSessionCache(t))}restoreFromCache(e,t){const r=this.sessionMsgCache.get(t);if(r&&r.length>0)return this.msgBuffers.set(e,r),r;this.msgBuffers.delete(e)}isCacheFresher(e,t){const r=this.sessionMsgCache.get(e);if(!r||r.length===0)return!1;if(r.length>t.length)return!0;const i=r.reduce((l,c)=>l+c.text.length,0),n=t.reduce((l,c)=>l+c.text.length,0);if(i>n)return!0;const a=r.reduce((l,c)=>l+(c.segments?.length??0),0),o=t.reduce((l,c)=>l+(c.segments?.length??0),0);return a>o}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;r.add(t),this.streamingSessions.set(e,r)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);r&&(r.delete(t),r.size===0&&this.streamingSessions.delete(e))}else this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}getMessages(e){return this.msgBuffers.get(e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.msgBuffers.delete(e)}evictIfNeeded(e){if(this.msgBuffers.size<=bi.MAX_CONVERSATIONS)return;const t=[...this.msgBuffers.keys()],r=t.filter(i=>i!==e&&i!==this.currentConvKey).slice(0,t.length-bi.MAX_CONVERSATIONS);for(const i of r)this.msgBuffers.delete(i),this.actBuffers.delete(i),this.sessionTabs.delete(i),this.activeSession.delete(i)}touchSessionCache(e){const t=this.sessionCacheOrder.indexOf(e);for(t!==-1&&this.sessionCacheOrder.splice(t,1),this.sessionCacheOrder.push(e);this.sessionCacheOrder.length>bi.MAX_SESSION_CACHE;){const r=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(r)){this.sessionCacheOrder.push(r);break}this.sessionMsgCache.delete(r)}}}const Tt=bi.NEW_CHAT_ID;function jM(s){const e=C.useRef(new bi),[t,r]=C.useState(s??[]),[i,n]=C.useState(!1),[a,o]=C.useState([]),l=C.useRef(null);C.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const c=C.useCallback((p,x,y)=>{const _=e.current.updateMessages(p,x,y);_.displayChanged&&_.newMessages&&r(_.newMessages)},[]),d=C.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const k=e.current.getMessages(p);k&&e.current.currentConvKey===p&&r([...k])}))},[]),u=C.useCallback((p,x,y)=>{const _=e.current.appendActivity(p,x,y);_.displayChanged&&_.newActivities&&o(_.newActivities)},[]),f=C.useCallback(p=>e.current.getPhase(p),[]),g=C.useCallback(p=>e.current.beginLoad(p),[]),v=C.useCallback(p=>e.current.beginStream(p),[]),b=C.useCallback(p=>e.current.endStream(p),[]),m=C.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=C.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const _=await y(),k=e.current.applyLoadResult(x,p,_.messages);return k.displayChanged&&k.newMessages&&r(k.newMessages),{count:_.messages.length,hasMore:_.hasMore,oldestCursor:_.oldestCursor}}catch{return e.current.currentConvKey===x&&e.current.getPhase(x)!=="streaming"&&(r([]),e.current.completeLoad(x)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get msgBuffers(){return e.current.msgBuffers},get sessionMsgCache(){return e.current.sessionMsgCache},get activeSessionBuffer(){return e.current.activeSession},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(p){e.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(p){e.current.loadingSession=p}}},updateConvMsgs:c,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:g,beginStream:v,endStream:b,resetConv:m,loadAndDisplay:O,incrementSending:p=>e.current.incrementSend(p),decrementSending:p=>e.current.decrementSend(p),resetSending:p=>e.current.resetSend(p),isSendingFor:p=>e.current.isSending(p),setStreamSession:(p,x)=>e.current.addStreamSession(p,x),clearStreamSession:(p,x)=>e.current.removeStreamSession(p,x),getStreamSession:p=>e.current.getStreamSessions(p),saveSessionToCache:(p,x)=>e.current.saveToCache(p,x),restoreSessionFromCache:(p,x)=>{const y=e.current.restoreFromCache(p,x);return r(y??[]),y},isSessionCacheFresherThanDb:(p,x)=>e.current.isCacheFresher(p,x)}}function EM({value:s,onSelect:e,disabled:t}){const{t:r}=At("team"),[i,n]=C.useState(!1),[a,o]=C.useState(!0),[l,c]=C.useState(""),[d,u]=C.useState(!1),[f,g]=C.useState([]),[v,b]=C.useState(null),m=C.useRef(null),O=C.useCallback(async()=>{u(!0);try{const w=await fetch("/api/settings/llm",{credentials:"include"});if(!w.ok)throw new Error(`HTTP ${w.status}`);const S=await w.json(),Q=S.providers?.markus;if(Q?.configured&&Q.enabled!==!1&&(!Q.models||Q.models.length===0))try{const j=await fetch("/api/models/live/markus",{credentials:"include"});if(j.ok){const I=await j.json();I.models?.length&&(Q.models=I.models)}}catch{}const N=[];for(const[j,I]of Object.entries(S.providers??{})){if(!I.configured||I.enabled===!1)continue;const V=(I.models??[]).map(Z=>({id:Z.id,name:Z.name}));V.length!==0&&N.push({provider:j,displayName:I.displayName??j,models:V})}N.sort((j,I)=>j.displayName.localeCompare(I.displayName)),g(N);const L=j=>!j?.provider||!j.model?!1:!!N.find(V=>V.provider===j.provider)?.models.some(V=>V.id===j.model);let $=null;if(S.routingDefaultModel?.provider&&S.routingDefaultModel?.model)$={provider:S.routingDefaultModel.provider,model:S.routingDefaultModel.model};else if(S.defaultProvider){const j=S.providers?.[S.defaultProvider];j?.model&&($={provider:S.defaultProvider,model:j.model})}if($&&!L($)){const j=N.find(V=>V.provider==="markus"),I=j?.models[0]?{provider:"markus",model:j.models[0].id}:N[0]?.models[0]?{provider:N[0].provider,model:N[0].models[0].id}:null;I?($=I,K.settings.updateRouting({defaultProvider:I.provider,routingDefaultModel:I}).catch(()=>{})):$=null}b($)}catch{g([])}finally{u(!1)}},[]);C.useEffect(()=>{O()},[O]),C.useEffect(()=>{i&&(o(!0),c(""),O())},[i,O]),C.useEffect(()=>{if(!i)return;const w=S=>{m.current?.contains(S.target)||n(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[i]);const p=C.useMemo(()=>{const w=l.trim().toLowerCase();return f.map(S=>({...S,models:w?S.models.filter(Q=>Q.id.toLowerCase().includes(w)||(Q.name?.toLowerCase().includes(w)??!1)||S.displayName.toLowerCase().includes(w)||S.provider.toLowerCase().includes(w)):S.models})).filter(S=>S.models.length>0)},[f,l]),x=C.useCallback(w=>!w?.provider||!w.model?!1:f.length===0?!0:!!f.find(Q=>Q.provider===w.provider)?.models.some(Q=>Q.id===w.model),[f]);C.useEffect(()=>{if(!s||f.length===0||x(s))return;const w=v&&x(v)?v:(()=>{const S=f.find(Q=>Q.provider==="markus");return S?.models[0]?{provider:"markus",model:S.models[0].id}:f[0]?.models[0]?{provider:f[0].provider,model:f[0].models[0].id}:null})();w&&e(w,!1)},[s,f,v,x,e]);const y=s&&x(s)?s:v,k=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||r("chatModel.title",{defaultValue:"Model"});return h.jsxs("div",{ref:m,className:"relative shrink-0",children:[h.jsxs("button",{type:"button",disabled:t,onClick:()=>n(w=>!w),className:"max-w-[180px] px-1.5 py-1 text-[12px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-md hover:bg-surface-elevated transition-colors flex items-center gap-1",title:y?`${y.provider}: ${y.model}`:r("chatModel.title",{defaultValue:"Model"}),children:[h.jsx("span",{className:"truncate",children:k}),h.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:h.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),i&&h.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[h.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[h.jsx("input",{autoFocus:!0,value:l,onChange:w=>c(w.target.value),placeholder:r("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-base border border-border-default/50 outline-none focus:border-brand-500/50"}),h.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[h.jsx("span",{children:r("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),h.jsx("button",{type:"button",role:"switch","aria-checked":a,onClick:()=>o(w=>!w),className:`relative w-9 h-5 rounded-full transition-colors ${a?"bg-brand-600":"bg-fg-tertiary/30"}`,children:h.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${a?"translate-x-4":""}`})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[d&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}),!d&&p.length===0&&h.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!d&&p.map(w=>h.jsxs("div",{className:"mb-1",children:[h.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:w.displayName}),w.models.slice(0,80).map(S=>{const Q=y?.provider===w.provider&&y?.model===S.id;return h.jsxs("button",{type:"button",onClick:()=>{e({provider:w.provider,model:S.id},a),a&&b({provider:w.provider,model:S.id}),n(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[h.jsx("span",{className:"truncate flex-1",children:S.id}),Q&&h.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:h.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${w.provider}:${S.id}`)})]},w.provider))]})]})]})}async function RM(s,e,t){s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,e),t&&await K.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const Px="markus_team_sidebars_c";function AM(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}const MM=["chat","overview","files","tools","memory","deliverables"],LM=["chat","overview","announcements","norms","settings"];function NM(s,e){if(s==="chat")return e("page.chatTitle");if(Xp.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=qp.find(i=>i.key===s);return r?e(r.labelKey):s}function DM(s){if(s==="chat")return"💬";const e=Xp.find(r=>r.key===s);if(e)return e.icon;const t=qp.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}const $f=new Set;function IM(){return window.location.hash}function BM(s){return $f.add(s),()=>{$f.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>$f.forEach(s=>s()));function tL({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=At(["team","common"]),a=C.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Ef(Kt.TEAM),[l,c]=C.useState(r?.agents??[]),[d,u]=C.useState(r?.humans??[]),[f,g]=C.useState(!r),v=jf(),b=C.useSyncExternalStore(BM,IM),m=v&&(b.startsWith(`#${Kt.TEAM}/`)||b.startsWith("#chat/")),O=v&&b.match(/^#team\/t\/(.+)$/),p=v?O?"team":m?"chat":"roster":"roster",x=O?O[1]:null,y=C.useRef(Kt.TEAM),_=C.useCallback(()=>{y.current=window.location.hash.slice(1)||Kt.TEAM,window.location.hash=`${Kt.TEAM}/d`},[]),k=C.useCallback(P=>{window.location.hash=`${Kt.TEAM}/t/${P}`},[]);C.useEffect(()=>{if(!v)return;const P=()=>{fi(Q.current)&&S("chat")};return window.addEventListener("popstate",P),()=>window.removeEventListener("popstate",P)},[v]);const[w,S]=C.useState("chat"),Q=C.useRef("chat");Q.current=w;const N=Dm({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[L,$]=C.useState(()=>{try{return localStorage.getItem(Px)==="1"}catch{return!1}}),j=C.useCallback(P=>{$(P);try{localStorage.setItem(Px,P?"1":"0")}catch{}},[]),I=nh(),V=I?.leftCollapsed??!1,Z=I?.rightPanel??null,z=I?.rightPanelTabs??[],J=I?.activeRightPanelTabId??null,T=I?.rightPanelFullscreen??!1,A=Z?"2xl:pr-8":"2xl:pr-[280px]",B=I?.setHostAvailable,q=I?.collapseRightPanelOnly??I?.toggleRightPanel,H=I?.openRightPanel,te=400,ue=320,ke=6,[U,D]=C.useState(typeof window<"u"?window.innerWidth:1440),[se,F]=C.useState("auto"),G=C.useRef(V);C.useEffect(()=>{G.current!==V&&(G.current=V,$(V))},[V]);const ee=I?.keyboardPane??"content",we=C.useRef(!1),Ae=C.useRef(ee);C.useEffect(()=>{if(t||v||!o)return;const P=Ae.current;Ae.current=ee,(ee==="l1"||ee==="l2")&&P!==ee&&L&&($(!1),I?.setLeftCollapsed(!1))},[ee,t,v,o,L,I]),C.useEffect(()=>{if(t||v||!o)return;const P=R=>{const E=I?.keyboardPane??"content";if(E==="l0"||E==="l1"||E==="l2"||R.metaKey||R.ctrlKey||R.altKey)return;if(R.target instanceof HTMLElement){const Y=R.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||R.target.isContentEditable||R.target.closest(".xterm"))return}const X=R.key.length===1?R.key.toLowerCase():R.key;X!=="h"&&X!=="ArrowLeft"||(R.preventDefault(),L&&(j(!1),I?.setLeftCollapsed(!1)),I?.setKeyboardPane(we.current?"l2":"l1"))};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[t,v,o,I,L,j]),C.useEffect(()=>{if(B)return B(o&&!v),()=>B(!1)},[o,v,B]),C.useEffect(()=>t||v||!o?void 0:yt.on("ui:right_panel",R=>{const E=R.payload;if(E.action==="collapse"){q?.();return}if(E.action!=="open"||!E.panel||!H)return;const X=E.panel;if(X.kind==="url"&&X.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"url",url:X.url,title:X.title||X.url,browserId:Y});return}if(X.kind==="file"&&X.path){H({kind:"file",path:X.path,title:X.title});return}if(X.kind==="terminal"){const Y=X.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"terminal",terminalId:Y,title:X.title||"Terminal",cwd:X.cwd});return}X.kind==="deliverable"&&X.deliverableId&&K.deliverables.get(X.deliverableId).then(Y=>{Y.deliverable&&H({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,q,H]);const xe=C.useCallback(P=>{const R=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Mi(E=>[...E,{id:R,...P}]),requestAnimationFrame(()=>cr.current?.focus())},[]),me=C.useCallback(P=>{if(P)try{const R=JSON.parse(P);if(!Array.isArray(R)||R.length===0)return;const E=R.filter(Y=>!!Y&&typeof Y.content=="string"&&Y.content.trim().length>0);if(E.length===0)return;const X=E.map(Y=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:Y.label?.trim()||"Context",content:Y.content}));Mi(Y=>[...Y,...X]),requestAnimationFrame(()=>{const Y=cr.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))})}catch{}},[]),[ge,He]=C.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),nt=Dm({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Ct=C.useRef(null),[pt,Xt]=C.useState(!1),[wt,Et]=C.useState(!1),Pt=C.useCallback(()=>{pt?Et(P=>!P):He(P=>{const R=!P;try{localStorage.setItem("markus_team_panel_visible",String(R))}catch{}return R})},[pt]);C.useEffect(()=>{if(v)return;const P=Ct.current;if(!P)return;const R=new ResizeObserver(([E])=>{if(!E)return;const X=E.contentRect.width;if(D(X),!t){const Y=X-N.width-nt.width;Xt(Y<400)}});return R.observe(P),()=>R.disconnect()},[v,t,N.width,nt.width]);const he=ge&&!pt&&!wt,Xe=L?0:N.width+ke+(he?nt.width+ke:0),Oe=Math.max(0,U-Xe-ke-8),Ke=Math.min(te,Math.floor(Oe*.4)),Ne=Math.max(0,Oe-Ke),bt=Math.min(Math.round(Oe/2),Ne),ir=Math.max(0,Math.min(se==="auto"?bt:se,Ne)),ts=C.useRef(!1);C.useEffect(()=>{const P=(I?.rightPanel??null)!==null;P&&!ts.current&&($(!0),F("auto")),ts.current=P},[I?.rightPanel]);const Ka=C.useRef(ir);Ka.current=ir;const Ja=C.useRef(Ne);Ja.current=Ne;const el=C.useCallback(P=>{P.preventDefault();const R=P.clientX,E=Ka.current,X=oe=>{const de=E+(R-oe.clientX),Se=Ja.current,ae=Math.min(ue,Se);F(Math.max(ae,Math.min(Se,de)))},Y=()=>{document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",X),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);C.useEffect(()=>{if(!wt)return;const P=R=>{R.target.closest("[data-l2-floating]")||Et(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[wt]);const[rn,si]=C.useState(null),[Qo,tl]=C.useState(),[ji,nr]=C.useState(),[Ei,Dn]=C.useState(!1),[$o,nn]=C.useState(""),[wh,Lr]=C.useState(!1),[Ri,on]=C.useState(""),or=C.useRef(null),sl=C.useRef(null),vr=C.useCallback((P,R)=>{tl(P),nr(R),v?(S("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):S(P??"overview")},[v]),jo=[{id:"chat"},{id:"profile"}],ri=C.useCallback(P=>{P==="profile"?vr():fi(Q.current)?history.back():S("chat")},[vr]),Nr=jx(jo,w,ri),us=C.useCallback((P,R)=>{gt("direct"),Yt(P),v&&_(),vr(R?.tab,R?.highlightMailboxId),si(null)},[v,_,vr]),Eo=C.useCallback((P,R)=>{const E=l.find(X=>X.name.toLowerCase()===P.toLowerCase());if(E){const X=R.target.getBoundingClientRect();si({agentId:E.id,top:X.bottom,left:X.left})}},[l]),rl=C.useMemo(()=>l.map(P=>P.name),[l]),[ie,gt]=C.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[be,Yt]=C.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[mt,ks]=C.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Ut,gs]=C.useState(""),il=500,Ai=C.useRef(new Set),Ro=P=>{if(Ai.current.add(P),Ai.current.size>il){const R=Math.floor(il*.2),E=Ai.current.values();for(let X=0;X<R;X++){const Y=E.next().value;Y&&Ai.current.delete(Y)}}},nl=C.useMemo(()=>{if(r?.channelMessages){const P=r.activeChannel??"custom:general";return r.channelMessages.filter(R=>R.channel===P).map(R=>Sn(R))}},[]),{manager:ol,messages:zt,setMessages:Cs,sending:Ms,setSending:Os,activities:kh,setActivities:yr,msgBuffers:ss,sessionMsgCache:ar,activeSessionBuffer:ii,actBuffers:Sr,sessionTabsBuffer:Ws,currentConvKeyRef:at,updateConvMsgs:ft,updateConvMsgsRaf:ni,appendConvActivity:an,beginLoad:al,beginStream:ln,endStream:Ps,resetConv:W,loadAndDisplay:le,incrementSending:pe,decrementSending:je,resetSending:Ge,isSendingFor:tt,setStreamSession:Ot,clearStreamSession:St,getStreamSession:Ye,saveSessionToCache:ns,restoreSessionFromCache:Ls}=jM(nl),[Mt,xs]=C.useState(""),[Ht,Ts]=C.useState(null),[_r,Mi]=C.useState([]),[Wt,wr]=C.useState([]),lr=C.useRef(null),[Ch,ll]=C.useState(!!r?.streamLastMessage),cn=C.useRef(null),dS=400;C.useEffect(()=>(Ms?(cn.current&&(clearTimeout(cn.current),cn.current=null),ll(!0)):Ch&&(cn.current=setTimeout(()=>{ll(!1),cn.current=null},dS)),()=>{cn.current&&clearTimeout(cn.current)}),[Ms]);const zp=Ms||Ch||(()=>{for(let P=zt.length-1;P>=Math.max(0,zt.length-8);P--){const R=zt[P];if(R.isStreaming&&!R.isStopped)return!0}return!1})(),Ph=C.useRef({fullText:"",timers:[]});C.useEffect(()=>{if(!t||!r?.streamLastMessage||zt.length===0)return;const P=zt[zt.length-1];if(!P||P.sender!=="agent")return;const R=P.text;Ph.current.fullText=R;const E=Ph.current.timers;function X(){let oe=0;Cs(Se=>Se.map((ae,ce)=>ce===Se.length-1?{...ae,text:""}:ae)),ll(!0);const de=setInterval(()=>{if(oe+=1+Math.floor(Math.random()*2),oe>=R.length){clearInterval(de),Cs(ce=>ce.map((We,Ze)=>Ze===ce.length-1?{...We,text:R}:We));const Se=setTimeout(()=>ll(!1),800);E.push(Se);const ae=setTimeout(X,6e3);E.push(ae)}else Cs(Se=>Se.map((ae,ce)=>ce===Se.length-1?{...ae,text:R.slice(0,oe)}:ae))},30);E.push(de)}const Y=setTimeout(X,1500);return E.push(Y),()=>{E.forEach(oe=>clearTimeout(oe)),Ph.current.timers=[]}},[]);const Li=C.useRef(0),[Zp,Dr]=C.useState(!1),[Th,Vp]=C.useState(!1),[cl,oi]=C.useState(!1),[Us,Qh]=C.useState([]),[Fp,Yp]=C.useState(null),$h=C.useRef(null),cr=C.useRef(null),[hl,In]=C.useState(null),Ni=C.useRef(null),jh=C.useRef(!1),Ao=C.useCallback(()=>{const P=cr.current;if(!P)return;const R=jh.current,E=R?36:52,X=R?160:120;P.style.height="auto";const Y=Math.max(E,Math.min(P.scrollHeight,X));P.style.height=`${Y}px`,P.style.overflowY=Y>=X?"auto":"hidden"},[]);C.useEffect(()=>{const P=requestAnimationFrame(()=>Ao());return()=>cancelAnimationFrame(P)},[Mt,Us.length,Ao]);const Eh=P=>{try{const R=localStorage.getItem(`markus_closed_tabs_${P}`);return R?new Set(JSON.parse(R)):new Set}catch{return new Set}},uS=(P,R)=>{const E=Eh(P);E.add(R);try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...E]))}catch{}},fS=(P,R)=>{const E=Eh(P);if(E.delete(R))try{localStorage.setItem(`markus_closed_tabs_${P}`,JSON.stringify([...E]))}catch{}},pS=P=>{try{return localStorage.getItem(`markus_active_session_${P}`)}catch{return null}},dl=(P,R)=>{if(P)try{R&&R!==Tt?localStorage.setItem(`markus_active_session_${P}`,R):localStorage.removeItem(`markus_active_session_${P}`)}catch{}},[Rh,hn]=C.useState([]),[lt,Ir]=C.useState(null),[dn,un]=C.useState(!1),[Up,Ah]=C.useState([]),[Mo,Mh]=C.useState(null),[mS,Hp]=C.useState(null),[ul,Lh]=C.useState([]),[Bn,Nh]=C.useState(null),[gS,Gp]=C.useState(null),[Kp,Dh]=C.useState([]),[Lo,OS]=C.useState([]),Xs=P=>{OS(R=>{const E=typeof P=="function"?P(R):P,X=new Set;return E.filter(Y=>X.has(Y.id)?!1:(X.add(Y.id),!0))})},fl=C.useRef(null),Ih=C.useRef(null),kr=C.useRef(null),[Qs,No]=C.useState(r?.groupChats??[]),Bh=C.useRef(Qs);Bh.current=Qs;const Jp=C.useRef(null),[Do,bs]=C.useState(!1),[fn,Io]=C.useState(!1),[em,Wn]=C.useState(""),[Wh,Di]=C.useState([]),[tm,sm]=C.useState(!1),Xh=C.useRef(void 0),[Cr,rm]=C.useState(r?.teams??[]),[xS,bS]=C.useState([]),[pl,im]=C.useState([]),[vS,yS]=C.useState(null),[WM,XM]=C.useState(!1),[qM,zM]=C.useState(""),[nm,Bo]=C.useState(!1),[om,SS]=C.useState(""),[Wo,Xn]=C.useState(0),[am,ml]=C.useState(!1),[lm,_S]=C.useState(""),[qh,Xo]=C.useState(0),[zh,wS]=C.useState([]),cm=C.useRef(!1),Zh=C.useCallback(()=>{cm.current||(cm.current=!0,(async()=>{try{const{skills:P}=await K.skills.list();wS(P.map(R=>({name:R.name,description:R.description??R.name})))}catch{}})())},[]);C.useEffect(()=>{Zh()},[Zh]);const pn=lm?zh.filter(P=>P.name.toLowerCase().includes(lm.toLowerCase())):zh,[kS,CS]=C.useState([]),hm=C.useRef(!1),PS=C.useCallback(()=>{hm.current||(hm.current=!0,(async()=>{const P=[];try{const[R,E,X,Y,oe]=await Promise.all([K.projects.list().catch(()=>({projects:[]})),K.requirements.list().catch(()=>({requirements:[]})),K.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),K.deliverables.search({limit:100}).catch(()=>({results:[]})),K.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const de of R.projects)P.push({id:de.id,name:de.name,entityType:"project",role:de.status});for(const de of E.requirements)P.push({id:de.id,name:de.title,entityType:"requirement",role:de.priority});for(const de of X.tasks)P.push({id:de.id,name:de.title,entityType:"task",role:de.status});for(const de of Y.results)P.push({id:de.id,name:de.title,entityType:"deliverable",role:de.type});for(const de of oe.teams)try{const Se=await K.workflows.list(de.id);for(const ae of Se.workflows)P.push({id:ae.name,name:ae.displayName||ae.name,entityType:"workflow",role:`v${ae.version}`})}catch{}}catch{}CS(P)})())},[]),rs=ie==="channel"?Qs.find(P=>P.channelKey===mt)?.teamId:void 0,TS=C.useRef(null),qn=C.useRef(null),$s=C.useRef(null),dm=C.useRef(void 0),gl=C.useRef(!1),Br=C.useRef(!0),um=C.useRef(void 0);C.useEffect(()=>{if(!dn)return;const P=R=>{Ih.current&&!Ih.current.contains(R.target)&&fl.current&&!fl.current.contains(R.target)&&un(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[dn]);const Ol=(P,R)=>{if(!R||P===R)return`notes:${P}`;const[E,X]=[P,R].sort();return`dm:${E}:${X}`};C.useEffect(()=>{localStorage.setItem("markus_chat_mode",ie)},[ie]),C.useEffect(()=>{localStorage.setItem("markus_chat_agent",be)},[be]),C.useEffect(()=>{localStorage.setItem("markus_chat_channel",mt)},[mt]);const{counts:Vh,sessionAgentMap:qo,markRead:zo,setActiveKey:QS,clearActiveKey:$S}=__({enabled:!t}),xl=C.useMemo(()=>{const P={};for(const[R,E]of Object.entries(Vh))R.startsWith("channel:")&&(P[R.slice(8)]=E);return P},[Vh]),Fh=w_(qo,Vh);C.useEffect(()=>{let P=0;for(const R of Fh.values())P+=R;for(const R of Object.values(xl))P+=R;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:P}}))},[Fh,xl]);const bl=Fh,jS=C.useCallback(async P=>{for(const[R,E]of Object.entries(qo))E===P&&zo(`session:${R}`)},[qo,zo]);C.useEffect(()=>{if(t||!((!v||p==="chat")&&w==="chat"))return;if(ie==="direct"&&be&&jS(be),ie==="channel"&&mt)zo(`channel:${mt}`);else if(ie==="direct"&&lt)zo(`session:${lt}`);else if(ie==="dm"&&Ut){const E=`dm:${[e?.id,Ut].sort().join(":")}`;zo(`channel:${E}`)}const R=[];if(ie==="direct"&&lt){R.push(`session:${lt}`);for(const[E,X]of Object.entries(qo))X===be&&R.push(`session:${E}`)}else ie==="channel"&&mt?R.push(`channel:${mt}`):ie==="dm"&&Ut&&e?.id&&R.push(`channel:dm:${[e.id,Ut].sort().join(":")}`);for(const E of R)QS(E);return()=>{for(const E of R)$S(E)}},[t,ie,mt,lt,Ut,be,p,w,qo]);const hr=C.useCallback(()=>K.agents.list().then(P=>c(P.agents)).catch(()=>{}),[]),Hs=C.useCallback(()=>K.teams.list().then(P=>rm(P.teams)).catch(()=>{}),[]),zn=C.useCallback(()=>K.groupChats.list().then(P=>No(P.chats)).catch(()=>{}),[]),ES=C.useMemo(()=>hd(hr,3e3),[hr]),vl=C.useMemo(()=>hd(Hs,5e3),[Hs]),Yh=C.useMemo(()=>hd(zn,3e3),[zn]),Zo=C.useCallback(()=>{K.users.list(e?.orgId).then(P=>u(P.users)).catch(()=>{})},[e?.orgId]);C.useEffect(()=>{t||(Promise.all([hr(),Hs()]).finally(()=>g(!1)),Zo(),K.tasks.list().then(P=>im(P.tasks)).catch(()=>{}),K.externalAgents.list().then(P=>bS(P.agents)).catch(()=>{}),zn())},[t,Zo]),C.useEffect(()=>{if(!(!t||!r)&&(c(r.agents??[]),u(r.humans??[]),rm(r.teams??[]),No(r.groupChats??[]),r.channelMessages)){const P=r.activeChannel??"custom:general";Cs(r.channelMessages.filter(R=>R.channel===P).map(R=>Sn(R)))}},[t,r]),C.useEffect(()=>{if(t||!o)return;hr(),Hs();const P=setInterval(hr,3e4),R=setInterval(Hs,6e4),E=yt.on("agent:update",()=>{ES(),vl()}),X=yt.on("team:update",()=>{vl(),Yh()}),Y=yt.on("agent:removed",vl),oe=yt.on("chat:group_created",()=>{zn(),Hs(),hr()}),de=yt.on("chat:group_updated",Yh),Se=yt.on("chat:group_deleted",()=>{Yh(),vl()}),ae=yt.on("task:update",We=>{const Ze=We?.payload;Ze?.taskId&&im(Ie=>Ie.map(Te=>Te.id===Ze.taskId?{...Te,status:Ze.status??Te.status}:Te))}),ce=()=>{hr(),Hs(),Zo()};return window.addEventListener("markus:data-changed",ce),()=>{clearInterval(P),clearInterval(R),E(),X(),Y(),oe(),de(),Se(),ae(),window.removeEventListener("markus:data-changed",ce)}},[t,o,Zo]),C.useEffect(()=>{if(t)return;const P=ce=>{const We=ce.detail;if(N_(We.page)===Kt.TEAM){if(We.params?.agentId){if(We.params.profileTab)us(We.params.agentId,{tab:We.params.profileTab});else if(gt("direct"),Yt(We.params.agentId),S("chat"),v&&_(),We.params.sessionId){const Ze=We.params.sessionId;setTimeout(async()=>{try{const{sessions:Ie}=await K.sessions.listByAgent(We.params.agentId,20),Te=Ie.find(dt=>dt.id===Ze);Te&&Cl(Te)}catch{}},300)}}if(We.params?.selectAgent&&(gt("direct"),Yt(We.params.selectAgent),S("chat"),v&&_()),We.params?.openDeliverable){const Ze=We.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:Ze}):H&&K.deliverables.get(Ze).then(Ie=>{Ie.deliverable&&H({kind:"deliverable",deliverable:Ie.deliverable})}).catch(()=>{})}if(We.params?.prefillMessage){const Ze=We.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),We.params?.autoSend==="true"?setTimeout(()=>dm.current?.(Ze),300):(xs(Ze),setTimeout(()=>{const Ie=cr.current;Ie&&(Ie.focus(),Ie.setSelectionRange(Ie.value.length,Ie.value.length))},100))}if(We.params?.chatChips){const Ze=We.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),S("chat"),me(Ze)}if(We.params?.dm&&(gt("dm"),gs(We.params.dm),S("chat"),v&&_()),We.params?.channel&&(gt("channel"),ks(We.params.channel),S("chat"),v&&_()),We.params?.selectTeam){const Ze=We.params.selectTeam;if(v)k(Ze);else{const Ie=Bh.current.find(Te=>Te.type==="team"&&Te.teamId===Ze);gt("channel"),ks(Ie?.channelKey??`group:${Ze}`),S("chat"),bs(!1),He(!0)}}We.params?.openHire}},R=localStorage.getItem("markus_nav_agentId");if(R){localStorage.removeItem("markus_nav_agentId");const ce=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),gt("direct"),Yt(R),ce?us(R,{tab:ce}):(S("chat"),v&&_())}const E=localStorage.getItem("markus_nav_dm");E&&(localStorage.removeItem("markus_nav_dm"),gt("dm"),gs(E),S("chat"),v&&_());const X=localStorage.getItem("markus_nav_channel");X&&(localStorage.removeItem("markus_nav_channel"),gt("channel"),ks(X),S("chat"),v&&_());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),S("chat"),xs(Y),setTimeout(()=>{const ce=cr.current;ce&&(ce.focus(),ce.setSelectionRange(ce.value.length,ce.value.length))},150));const oe=localStorage.getItem("markus_nav_chatChips");oe&&(localStorage.removeItem("markus_nav_chatChips"),S("chat"),me(oe));const de=localStorage.getItem("markus_nav_openDeliverable");de&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:de}):H&&K.deliverables.get(de).then(ce=>{ce.deliverable&&H({kind:"deliverable",deliverable:ce.deliverable})}).catch(()=>{}));const Se=localStorage.getItem("markus_nav_selectAgent");Se&&(localStorage.removeItem("markus_nav_selectAgent"),gt("direct"),Yt(Se),S("chat"),v&&_());const ae=localStorage.getItem("markus_nav_selectTeam");if(ae)if(localStorage.removeItem("markus_nav_selectTeam"),v)k(ae);else{const ce=Bh.current.find(We=>We.type==="team"&&We.teamId===ae);gt("channel"),ks(ce?.channelKey??`group:${ae}`),S("chat"),bs(!1),He(!0)}return window.addEventListener("markus:navigate",P),()=>window.removeEventListener("markus:navigate",P)},[t]),C.useEffect(()=>{const P=Jp.current;if(!P)return;const R=Qs.find(E=>E.type==="team"&&E.teamId===P);Jp.current=null,gt("channel"),ks(R?.channelKey??`group:${P}`),S("chat"),bs(!1),He(!0)},[Qs,Cr]),C.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||be&&l.some(E=>E.id===be))return;const P=localStorage.getItem("markus_nav_after_remove");if(P&&(localStorage.removeItem("markus_nav_after_remove"),P.startsWith("channel:"))){gt("channel"),ks(P.slice(8)),S("chat");return}const R=l.find(E=>!E.teamId&&E.role?.toLowerCase()==="secretary")??l.find(E=>E.role?.toLowerCase()==="secretary")??l.find(E=>E.name?.toLowerCase().includes("secretary"));R?(gt("direct"),Yt(R.id),S("chat")):l.length>0&&(gt("direct"),Yt(l[0].id),S("chat"))},[l,be]);const Zn=C.useRef(!1),Pr=C.useRef(!1),yl=C.useRef(!1),Sl=C.useRef(0),Vn=C.useRef(0),[RS,ai]=C.useState(!1),Ii=C.useRef(0),[fm,mn]=C.useState(0),li=C.useCallback(()=>{Pr.current=!1,yl.current=!1,Br.current=!0},[]),Uh=C.useCallback(()=>{Pr.current=!0,Br.current=!1,Vn.current+=1,Zn.current=!1,ai(!0)},[]),gn=C.useCallback(P=>{const R=qn.current;if(!R)return;const E=R.scrollHeight-R.scrollTop-R.clientHeight,X=E<160,Y=E<48,oe=Sl.current,de=R.scrollTop<oe-2;if(Sl.current=R.scrollTop,de&&E>20){yl.current=!0,Uh();return}if(yl.current){Y?(li(),ai(!1),Ii.current=0,mn(0)):Uh();return}if(X&&!Pr.current){li(),ai(!1),Ii.current=0,mn(0);return}P?.fromProgrammatic||Zn.current||!Pr.current&&Br.current||Pr.current&&(Br.current=!1,ai(!0))},[Uh,li]);C.useEffect(()=>{const P=qn.current;if(!P)return;const R=()=>{yl.current=!0},E=()=>{gn({fromProgrammatic:Zn.current})};P.addEventListener("wheel",R,{passive:!0}),P.addEventListener("touchmove",R,{passive:!0}),P.addEventListener("scroll",E,{passive:!0});const X=typeof ResizeObserver<"u"?new ResizeObserver(()=>gn()):null;return X?.observe(P),Sl.current=P.scrollTop,gn(),()=>{P.removeEventListener("wheel",R),P.removeEventListener("touchmove",R),P.removeEventListener("scroll",E),X?.disconnect()}},[p,gn]);const Hh=C.useMemo(()=>new Set(Kp),[Kp]),os=C.useMemo(()=>{const P=ie==="channel"?zt:zt.filter(R=>!R.isActivityLog);return Hh.size===0?P:P.filter(R=>!(R.isNotification&&Hh.has(R.id)))},[zt,ie,Hh]);C.useEffect(()=>{jh.current=w==="chat"&&os.length>0,Ao()},[w,os.length,Ao]);const ci=ew({count:os.length,getScrollElement:()=>qn.current,getItemKey:P=>os[P]?.id??P,estimateSize:P=>{const R=os[P];return R?R.segments&&R.segments.length>0?300:R.text.length>500?200:120:120},overscan:8});ci.shouldAdjustScrollPositionOnItemSizeChange=(P,R,E)=>Im()?!1:P.start<(E.scrollOffset??0);const hi=C.useCallback((P="instant")=>{if(!Br.current||Pr.current)return;const R=++Vn.current;Zn.current=!0;const E=()=>R===Vn.current&&Br.current&&!Pr.current,X=()=>{if(R!==Vn.current)return;if(Zn.current=!1,!E()){gn();return}const Y=qn.current;Y&&(Sl.current=Y.scrollTop,Y.scrollHeight-Y.scrollTop-Y.clientHeight<160&&!Pr.current&&(li(),ai(!1),Ii.current=0,mn(0))),requestAnimationFrame(()=>{R===Vn.current&&gn({fromProgrammatic:!0})})};if(os.length>0)ci.scrollToIndex(os.length-1,{align:"end",behavior:P}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!E()){R===Vn.current&&(Zn.current=!1);return}ci.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(X)})});else{const Y=qn.current;Y&&Y.scrollTo({top:Y.scrollHeight,behavior:P}),requestAnimationFrame(X)}},[os.length,ci,gn,li]),pm=C.useRef(o);C.useEffect(()=>{pm.current=o},[o]),C.useLayoutEffect(()=>{if(gl.current){gl.current=!1;const P=wl.current;P>0&&(wl.current=0,ci.scrollToIndex(P,{align:"start",behavior:"instant"}));return}pm.current&&(!Br.current||Pr.current||Im()||hi())},[zt,hi,ci]);const mm=C.useRef(w);C.useEffect(()=>{const P=mm.current!=="chat";if(mm.current=w,w==="chat"&&P&&Br.current&&!Pr.current){const R=[],E=requestAnimationFrame(()=>hi("instant"));for(const X of[60,160,320])R.push(setTimeout(()=>hi("instant"),X));return()=>{cancelAnimationFrame(E);for(const X of R)clearTimeout(X)}}},[w,Ms,hi]);const gm=C.useRef(A);C.useEffect(()=>{if(gm.current===A||(gm.current=A,w!=="chat")||os.length===0||Ms||cl||!Br.current||Pr.current)return;const P=[],R=requestAnimationFrame(()=>hi("instant"));for(const E of[60,160,320])P.push(setTimeout(()=>hi("instant"),E));return()=>{cancelAnimationFrame(R);for(const E of P)clearTimeout(E)}},[A,w,os.length,Ms,cl,hi]);const Om=C.useCallback(async(P,R)=>{const E=R??`ch:${P}`;at.current===E&&oi(!0);try{const X=await K.channels.getMessages(P,50),Y=X.messages.map(oe=>Sn(oe,e?.id));ss.set(E,Y),at.current===E&&(Cs(Y),Dr(X.hasMore),kr.current=X.messages[0]?new Date(X.messages[0].createdAt).toISOString():null)}catch{at.current===E&&(Cs([]),Dr(!1))}finally{at.current===E&&oi(!1)}},[]),Gh=C.useCallback(async(P,R)=>{const E=at.current===R&&(ss.get(R)?.length??0)===0;E&&oi(!0);try{const{count:X,hasMore:Y,oldestCursor:oe}=await le(P,R,async()=>{const de=await K.sessions.getMessages(P,50);return{messages:k_(de.messages.map(dd).filter(ae=>ae.sender!=="agent"||ae.text||ae.segments&&ae.segments.length>0||ae.isStreaming)),hasMore:de.hasMore,oldestCursor:de.messages[0]?new Date(de.messages[0].createdAt).toISOString():null}});return Dr(Y),kr.current=oe,X}finally{E&&at.current===R&&oi(!1)}},[le,ss]),xm=C.useRef(new Map),On=C.useCallback(async(P,R,E)=>{if(!P||!R||R===Tt)return;let X=null;try{if($s.current&&!$s.current.signal.aborted&&Ye(E)?.has(R)){ln(E),at.current===E&&Os(!0);return}const Y=`${P}:${R}`,oe=xm.current.get(Y)??0;if(Date.now()-oe<1500)return;const de=await K.sessions.streamStatus(P,R),ae=[...ss.get(E)??[]].reverse().find(ve=>ve.sender==="agent"),ce=de.status==="streaming",We=!!de.active&&(de.status==="done"||de.status==="error")&&!!ae?.isStreaming;if(!ce&&!We)return;xm.current.set(Y,Date.now()),Ni.current?.abort(),X=new AbortController,Ni.current=X,ln(E),Os(!0),Ot(E,R);let Ze=ae?.id;if(!ae||ae.isError)Ze=`reattach_${Date.now()}`,ft(E,ve=>[...ve,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],R);else{const ve=(ae.segments??[]).filter(ze=>ze.type==="tool").map(ze=>ze.status==="stopped"||ze.status==="running"?{...ze,status:"running"}:ze);ft(E,ze=>ze.map(Qe=>Qe.id===ae.id?{...Qe,text:"",isStreaming:!0,isStopped:!1,segments:ve,committedSegments:void 0}:Qe),R)}let Ie=!1;const Te=ve=>{at.current===E&&(Li.current=Date.now(),ni(E,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(fe=>fe.id===Ze):-1,Me=De>=0?De:Qe.map((fe,ye)=>({m:fe,j:ye})).reverse().find(fe=>fe.m.sender==="agent")?.j??-1;if(Me<0)return ze;const qe=Qe[Me].segments??[],it=qe[qe.length-1],Rt=it?.type==="text"?it.thinking??"":"";let Gt="",Ns="",ne=ve;for(;ne.length>0;)if(Ie){const fe=ne.indexOf("</think>");fe>=0?(Gt+=ne.slice(0,fe),ne=ne.slice(fe+8),Ie=!1):(Gt+=ne,ne="")}else{const fe=ne.indexOf("<think>");fe>=0?(Ns+=ne.slice(0,fe),ne=ne.slice(fe+7),Ie=!0):(Ns+=ne,ne="")}const Ue=Rt+Gt||void 0,Ce=it?.type==="text"?[...qe.slice(0,-1),{type:"text",content:it.content+Ns,thinking:Ue,createdAt:it.createdAt}]:[...qe,{type:"text",content:Ns,thinking:Ue,createdAt:new Date().toISOString()}];return Qe[Me]={...Qe[Me],text:(Qe[Me].text??"")+Ns,segments:Ce,isStreaming:!0},Qe},R))},dt=ve=>{if(at.current===E&&(Li.current=Date.now(),ve.phase!=="heartbeat")){if((ve.phase==="start"||ve.phase==="end")&&an(E,{...ve,phase:ve.phase,ts:Date.now()},R),ve.phase==="start"){const ze=`${ve.tool}_${Date.now()}`,Qe=new Date().toISOString(),De=Me=>{const qe=[...Me];for(let it=qe.length-1;it>=0;it--){const Rt=qe[it];if(Rt.type==="tool"&&Rt.tool===ve.tool&&(Rt.status==="running"||Rt.status==="stopped"))return qe[it]={...Rt,status:"running",args:ve.arguments??Rt.args},qe}return qe.push({type:"tool",key:ze,tool:ve.tool,status:"running",args:ve.arguments,createdAt:Qe}),qe};ft(E,Me=>{const qe=[...Me],it=Ze?qe.findIndex(ne=>ne.id===Ze):-1;if(it<0)return Me;const Rt=De(qe[it].segments??[]),Gt=qe[it].committedSegments,Ns=Gt&&De(Gt);return qe[it]={...qe[it],segments:Rt,committedSegments:Ns,isStreaming:!0},qe},R)}else if(ve.phase==="end"){const ze=new Date().toISOString(),Qe=De=>{const Me=[...De];for(let qe=Me.length-1;qe>=0;qe--){const it=Me[qe];if(it.type==="tool"&&it.tool===ve.tool&&(it.status==="running"||it.status==="stopped")){Me[qe]={...it,status:ve.success===!1?"error":"done",args:ve.arguments??it.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,liveOutput:void 0,createdAt:ze};break}}return Me};ft(E,De=>{const Me=[...De],qe=Ze?Me.findIndex(Ns=>Ns.id===Ze):-1;if(qe<0)return De;const it=Qe(Me[qe].segments??[]),Rt=Me[qe].committedSegments,Gt=Rt&&Qe(Rt);return Me[qe]={...Me[qe],segments:it,committedSegments:Gt,isStreaming:!0},Me},R)}else if(ve.phase==="subagent_progress"&&ve.subagentEvent){const ze=Qe=>{const De=[...Qe];for(let Me=De.length-1;Me>=0;Me--){const qe=De[Me];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){De[Me]={...qe,status:"running",subagentLogs:Bm(qe.subagentLogs,ve.subagentEvent)};break}}return De};ni(E,Qe=>{const De=[...Qe],Me=Ze?De.findIndex(Gt=>Gt.id===Ze):-1;if(Me<0)return Qe;const qe=ze(De[Me].segments??[]),it=De[Me].committedSegments,Rt=it&&ze(it);return De[Me]={...De[Me],segments:qe,committedSegments:Rt,isStreaming:!0},De},R)}}},Be=ve=>{at.current===E&&(Li.current=Date.now(),ft(E,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(qe=>qe.id===Ze):-1;if(De<0)return ze;const Me=[...Qe[De].committedSegments??[]];if(ve.type==="thinking_commit")Me.push({type:"text",content:"",thinking:ve.content,createdAt:ve.createdAt});else if(ve.type==="text_commit")Me.push({type:"text",content:ve.content,createdAt:ve.createdAt});else return ze;return Qe[De]={...Qe[De],committedSegments:Me,isStreaming:!0},Qe},R))},st=ve=>{if(at.current!==E)return;Li.current=Date.now();const ze=(ve.segments??[]).map((Qe,De)=>Qe.type==="tool"?{type:"tool",key:`${Qe.tool}_${De}`,tool:Qe.tool??"tool",status:Qe.status==="error"?"error":Qe.status==="running"||Qe.status==="stopped"?"running":"done",args:Qe.arguments,result:Qe.result,error:Qe.error,durationMs:Qe.durationMs,createdAt:Qe.createdAt,...Qe.subagentLogs?.length?{subagentLogs:Qe.subagentLogs}:{}}:{type:"text",content:Qe.content??"",thinking:Qe.thinking,createdAt:Qe.createdAt});ft(E,Qe=>{const De=[...Qe],Me=Ze?De.findIndex(qe=>qe.id===Ze):-1;return Me<0?Qe:(De[Me]={...De[Me],text:ve.content||De[Me].text,segments:ze,committedSegments:ze,isStreaming:!0,isStopped:!1},De)},R);for(const Qe of ze)Qe.type==="tool"&&an(E,{tool:Qe.tool,phase:Qe.status==="running"||Qe.status==="stopped"?"start":"end",success:Qe.status!=="error",arguments:Qe.args,result:Qe.result,error:Qe.error,durationMs:Qe.durationMs,ts:Date.now()},R)},rt=await K.sessions.reattachStream(P,R,{onChunk:Te,onActivity:dt,onCommit:Be,onSnapshot:st},X.signal,0);if(!rt.attached){Ps(E),at.current===E&&(ft(E,ve=>{const ze=[...ve],Qe=Ze?ze.findIndex(qe=>qe.id===Ze):-1,De=Qe>=0?Qe:ze.map((qe,it)=>({m:qe,j:it})).reverse().find(qe=>qe.m.sender==="agent"&&qe.m.isStreaming)?.j??-1;if(De<0)return ve;const Me=ze[De];return Me.isStreaming?(ze[De]={...Me,isStreaming:!1,isStopped:Me.isError?Me.isStopped:!0},ze):ve},R),Os(!1));return}at.current===E&&(ft(E,ve=>{const ze=[...ve],Qe=Ze?ze.findIndex(it=>it.id===Ze):-1,De=Qe>=0?Qe:ze.map((it,Rt)=>({m:it,j:Rt})).reverse().find(it=>it.m.sender==="agent")?.j??-1;if(De<0)return ve;const Me=ze[De],qe=rt.segments?.length?Wm(rt.segments,Me.segments):void 0;return ze[De]={...Me,text:rt.content||Me.text,isStreaming:!1,isStopped:!1,...qe?{segments:qe,committedSegments:qe}:{}},ze},R),Os(!1)),Ps(E),Ni.current===X&&(Ni.current=null)}catch(Y){if(Ni.current===X&&(Ni.current=null),Ps(E),at.current===E&&Os(!1),Y instanceof Error&&Y.name==="AbortError")return}},[an,ln,Ps,Ye,ss,Ot,ft,ni]);C.useEffect(()=>{if(!o||t||ie!=="direct"||!be)return;const P=lt;!P||P===Tt||On(be,P,at.current)},[o,t,ie,be,lt,On]);const _l=C.useCallback(async P=>{if(!P)return hn([]),[];try{const{sessions:R}=await K.sessions.listByAgent(P,10);return hn(R),R}catch{return hn([]),[]}},[]),wl=C.useRef(0),AS=C.useCallback(async()=>{if(!(Th||!Zp||!kr.current)){Vp(!0);try{const P=at.current;if(ie==="channel"||ie==="dm"){const R=ie==="dm"?Ol(e?.id??"",Ut):mt,E=await K.channels.getMessages(R,50,kr.current),X=E.messages.map(Y=>Sn(Y,e?.id));wl.current=X.length,gl.current=!0,Cs(Y=>{let oe=[...X,...Y];return oe.length>500&&(oe=oe.slice(-500)),ss.set(P,oe),oe}),Dr(E.hasMore),E.messages[0]&&(kr.current=new Date(E.messages[0].createdAt).toISOString())}else if(lt){const R=await K.sessions.getMessages(lt,50,kr.current),E=R.messages.map(dd);wl.current=E.length,gl.current=!0,Cs(X=>{let Y=[...E,...X];return Y.length>500&&(Y=Y.slice(-500)),ss.set(P,Y),Y}),Dr(R.hasMore),R.messages[0]&&(kr.current=new Date(R.messages[0].createdAt).toISOString())}}catch{}finally{Vp(!1)}}},[Th,Zp,ie,mt,lt,e?.id,Ut]);um.current=AS;const Kh=C.useRef(!1),MS=C.useCallback(P=>{Kh.current||(Kh.current=!0,requestAnimationFrame(()=>{Kh.current=!1,P.target.scrollTop<100&&um.current?.()}))},[]);C.useEffect(()=>{if(t)return;const P=nc(ie,be,mt,Ut),R=at.current;at.current=P,R&&R!==P&&(Ws.set(R,Lo),lt&&ii.set(R,lt)),R!==P&&(li(),ai(!1),Ii.current=0,mn(0));const E=ss.get(P),X=Ws.get(P),Y=ii.get(P),oe=Ye(P),de=Y??lt,Se=tt(P)&&(ie!=="direct"||!oe||!de||oe.has(de)),ae=de??P,ce=Sr.get(ae)??[];if(yr(Se?ce:[]),Os(Se),ie==="direct"&&be&&_l(be),X&&X.length>0&&Xs(X),un(!1),E!==void 0&&E.length>0)if(Se||ol.completeLoad(P),oi(!1),Cs(E),Dr(!1),Y!==void 0&&Ir(Y),(!X||X.length===0)&&Xs([]),ie==="channel"||ie==="dm"){const Ze=ie==="dm"?Ol(e?.id??"",Ut):mt;Om(Ze,P)}else ie==="direct"&&be&&Y&&Y!==Tt&&(Se?On(be,Y,P):Gh(Y,P).then(()=>{at.current===P&&be&&On(be,Y,P)}));else if(al(P),oi(!0),Cs([]),Dr(!1),kr.current=null,ss.delete(P),ie==="channel"||ie==="dm"){const Ze=ie==="dm"?Ol(e?.id??"",Ut):mt;Om(Ze,P),(!X||X.length===0)&&Xs([])}else ie==="direct"&&be?_l(be).then(Ze=>{if(at.current===P)if(Ze.length>0){const Ie=Ze.find(De=>De.isMain),Te=Eh(be),dt=Ie?[Ie,...Ze.filter(De=>!De.isMain&&!Te.has(De.id)).slice(0,4)]:Ze.filter(De=>!Te.has(De.id)).slice(0,5);let Be=X&&X.length>0?X:dt;const st=pS(be),rt=Y!==void 0?Y:st??Ie?.id??Be[0].id;if(rt&&rt!==Tt&&!Be.some(De=>De.id===rt)){const De=Ze.find(Me=>Me.id===rt);De&&(Be=[...Be,De])}const ve=rt&&Be.some(De=>De.id===rt)?rt:Be[0].id;Ir(ve),ii.set(P,ve),dl(be,ve),Xs(Be);const Qe=Ze.find(De=>De.id===ve)?.metadata?.modelOverride;In(Qe?.provider&&Qe?.model?{provider:Qe.provider,model:Qe.model}:null),Gh(ve,P).then(()=>{at.current===P&&be&&On(be,ve,P)})}else Ir(null),In(null),oi(!1),(!X||X.length===0)&&Xs([])}).catch(()=>{at.current===P&&oi(!1)}):oi(!1)},[t,ie,be,mt,Ut,n.language,i]),C.useEffect(()=>t?void 0:yt.on("chat:message",R=>{const E=R.payload,X=E.channel??"";if(!X)return;const Y=E.senderType??"agent",oe=E.text??E.message??"",de=E.senderId??E.agentId??"",Se=E.senderName??E.agentId??i("page.fallbackAgent"),ae=E.metadata,ce=E.messageId??E.id??"";if(ce&&Ai.current.has(ce))return;const We=Y==="human"&&de===(e?.id??""),Ze={id:ce||`ws_${Date.now()}_${de}`,sender:We?"user":"agent",text:oe,time:new Date().toLocaleTimeString(),agentName:We?void 0:Se,agentId:We?void 0:de,replyToId:E.replyToId??void 0,replyToSender:E.replyToSender??void 0,replyToText:E.replyToText??void 0};if(ae&&Y==="agent"){const Te=[];if(ae.thinking?.length&&Te.push({type:"text",content:"",thinking:ae.thinking.join(`
73
73
 
74
74
  `)}),ae.toolCalls?.length)for(let dt=0;dt<ae.toolCalls.length;dt++){const Be=ae.toolCalls[dt];Te.push({type:"tool",key:`${Be.tool}_${dt}`,tool:Be.tool,status:Be.status==="error"?"error":"done",args:Be.arguments,result:Be.result,durationMs:Be.durationMs})}Te.length>0&&(Te.push({type:"text",content:oe}),Ze.segments=Te)}let Ie;if(X.startsWith("notes:"))Ie=`dm:${X.slice(6)}`;else if(X.startsWith("dm:")){const Te=X.slice(3).split(":");Ie=`dm:${Te.find(Be=>Be!==(e?.id??""))??Te[0]??""}`}else Ie=`ch:${X}`;ft(Ie,Te=>[...Te,Ze]),Ie===at.current&&!Br.current&&(Ii.current+=1,mn(Ii.current),ai(!0)),Y==="agent"&&Ie===`ch:${mt}`&&wr(Te=>{const dt=Te.filter(Be=>Be.id!==de);return dt.length===0&&lr.current&&(clearTimeout(lr.current),lr.current=null),dt})}),[t,ft,e?.id,mt]),C.useEffect(()=>t?void 0:yt.on("chat:agent_no_response",R=>{const E=R.payload,X=E.channel??"",Y=E.agentId??"";X&&Y&&`ch:${mt}`==`ch:${X}`&&wr(oe=>{const de=oe.filter(Se=>Se.id!==Y);return de.length===0&&lr.current&&(clearTimeout(lr.current),lr.current=null),de})}),[t,mt]),C.useEffect(()=>t?void 0:yt.on("chat:proactive_message",R=>{const E=R.payload,X=E.targetUserId;if(X&&X!==e?.id)return;const Y=E.agentId??"",oe=E.agentName??i("page.fallbackAgent"),de=E.message??"",Se=E.sessionId??"",ae=E.messageId??"",ce=E.metadata??{};if(!Y||!de||de==="[cancelled]"||de==="[Stream cancelled]")return;const We=ce.role==="user",Ze=!We&&(!!ce.activityLog||de.startsWith("[ACTIVITY:")),{cleaned:Ie,priority:Te}=C_(de),dt=!We&&(!!ce.notifyUser||Ie!==de),Be=nc("direct",Y,"","");if(Se&&at.current===Be){const qe=lt;if(qe&&qe!==Tt&&qe!==Se)return}const st=!!ce.isMainSession&&!We,rt=Se||lt,ve=typeof ce.userText=="string"?ce.userText:"",ze=typeof ce.userMessageId=="string"?ce.userMessageId:"",Qe=typeof ce.createdAt=="string"&&ce.createdAt||(typeof R.timestamp=="string"?R.timestamp:void 0)||new Date().toISOString(),De=(()=>{try{return new Date(Qe).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Me={id:ae||`proactive_${Date.now()}`,sender:We?"user":"agent",text:Ie,time:De,rawCreatedAt:Qe,...We?{}:{agentName:oe,agentId:Y,...dt?{isNotification:!0,notifyPriority:ce.priority??Te}:{},...Ze?{isActivityLog:!0,activityType:ce.activityType,outcome:ce.outcome,mailboxItemId:ce.mailboxItemId,taskId:ce.taskId,requirementId:ce.requirementId}:{},...!Ze&&ce.taskId?{taskId:ce.taskId}:{},...!Ze&&ce.requirementId?{requirementId:ce.requirementId}:{}}};dt&&Me.id&&Dh(qe=>qe.includes(Me.id)?qe:[...qe,Me.id]),ft(Be,qe=>{if(qe.some(Rt=>Rt.id===Me.id))return qe;let it=qe;if(!We&&ve&&(it.some(Gt=>ze&&Gt.id===ze||Gt.sender==="user"&&Gt.text===ve)||(it=Xm(it,{id:ze||`feishu_user_${Me.id}`,sender:"user",text:ve,time:new Date().toLocaleTimeString(),rawCreatedAt:Me.rawCreatedAt}))),st)for(let Rt=it.length-1;Rt>=0;Rt--){const Gt=it[Rt];if(Gt.sender==="agent"&&Gt.agentId===Y&&Gt.isStopped){const Ns=[...it];return Ns[Rt]={...Me,id:Gt.id},Ns}}return Xm(it,Me)},rt||void 0)}),[t,ft,i,lt]),pl.find(P=>P.id===vS),C.useEffect(()=>{yS(null)},[be]);const LS=P=>I_(P),NS=()=>{const P=ie==="direct"?be:null;P&&K.agents.cancelProcessing(P).catch(()=>{}),$s.current?.abort(),$s.current=null,Ni.current?.abort(),Ni.current=null;const R=at.current;Ge(R),Sr.delete(lt??R),lt&&St(R,lt),Ps(R),Os(!1),yr([])},[xn,Jh]=C.useState(null),[bm,vm]=C.useState(!1),ym=C.useRef(null),bn=async(P,R)=>{const E=!P&&_r.length>0?_r.map(Ie=>Ie.content).join(`
75
75