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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/markus.mjs +1 -1
  2. package/dist/web-ui/assets/{CommentInput-BRkHjDZN.js → CommentInput-CidSogOF.js} +1 -1
  3. package/dist/web-ui/assets/{ContentRenderer-BHf4qoQ8.js → ContentRenderer-BsmttX9l.js} +2 -2
  4. package/dist/web-ui/assets/{DeliverableShareModal-BuGiP0iO.js → DeliverableShareModal-Ck-iPMFP.js} +3 -3
  5. package/dist/web-ui/assets/{Deliverables-CCRw1-G6.js → Deliverables-DhciZGmH.js} +1 -1
  6. package/dist/web-ui/assets/{Notifications-V3K-Jh5R.js → Notifications-kiOr1WLO.js} +1 -1
  7. package/dist/web-ui/assets/{Search-Yq4GtqtT.js → Search-R51lNgNR.js} +1 -1
  8. package/dist/web-ui/assets/{Settings-DSLj6wZd.js → Settings-CEpDPzDi.js} +1 -1
  9. package/dist/web-ui/assets/{Store-C8MuiBYk.js → Store-CdvKtaTQ.js} +1 -1
  10. package/dist/web-ui/assets/{Team-C9CW4uI_.js → Team-CxcNwa5O.js} +4 -4
  11. package/dist/web-ui/assets/{Work-gqXPqaqb.js → Work-C_8_ZUiW.js} +1 -1
  12. package/dist/web-ui/assets/{arc-4Un3epQ-.js → arc-QfptBfyf.js} +1 -1
  13. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-P9JLPAFD.js → architectureDiagram-3BPJPVTR-BwaTd39l.js} +1 -1
  14. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-DMVZw0je.js → blockDiagram-GPEHLZMM-F6uVkCU-.js} +1 -1
  15. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-CUm_kG8b.js → c4Diagram-AAUBKEIU-CLkZF07J.js} +1 -1
  16. package/dist/web-ui/assets/channel-G3UyRMO9.js +1 -0
  17. package/dist/web-ui/assets/{chunk-2J33WTMH-CO16L8Rv.js → chunk-2J33WTMH-xJTx1LaK.js} +1 -1
  18. package/dist/web-ui/assets/{chunk-4BX2VUAB-CX7Icsih.js → chunk-4BX2VUAB-CgzeJPH6.js} +1 -1
  19. package/dist/web-ui/assets/{chunk-55IACEB6-BXo53Ksk.js → chunk-55IACEB6-CSEwSjbc.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-727SXJPM-l-dLi7wm.js → chunk-727SXJPM-CCP8OjW9.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-AQP2D5EJ-CVn9n6_W.js → chunk-AQP2D5EJ-DYfEEGkD.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-FMBD7UC4-DUmAAOWu.js → chunk-FMBD7UC4-BqyWUvsM.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-ND2GUHAM-DMzyCujK.js → chunk-ND2GUHAM-BE4yiTgV.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-QZHKN3VN-BN56eR92.js → chunk-QZHKN3VN-DRj_Bv-t.js} +1 -1
  25. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D0EQckXG.js +1 -0
  26. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D0EQckXG.js +1 -0
  27. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-Cp0hhUPC.js → cose-bilkent-S5V4N54A-BX2qCzYu.js} +1 -1
  28. package/dist/web-ui/assets/{dagre-BM42HDAG-d7vcGaj6.js → dagre-BM42HDAG-pifgwsOY.js} +1 -1
  29. package/dist/web-ui/assets/{diagram-2AECGRRQ-j-e6bNLc.js → diagram-2AECGRRQ-CuEM3W8S.js} +1 -1
  30. package/dist/web-ui/assets/{diagram-5GNKFQAL-aBO68Kr1.js → diagram-5GNKFQAL-BlbUk4AS.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-KO2AKTUF-JjKTZ0q4.js → diagram-KO2AKTUF-ClaQFeIf.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-LMA3HP47-D8_a-FKC.js → diagram-LMA3HP47-XGsIGJ4b.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-OG6HWLK6-CWlPPlog.js → diagram-OG6HWLK6-BdNtMUBa.js} +1 -1
  34. package/dist/web-ui/assets/{docx-preview-D9tDSXmy.js → docx-preview-B4TYzKVe.js} +1 -1
  35. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BxU-hkOq.js → erDiagram-TEJ5UH35-DDYsF1UT.js} +1 -1
  36. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DiOr2xDD.js → flowDiagram-I6XJVG4X-Ca4Prfb_.js} +1 -1
  37. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-Bzzg-s51.js → ganttDiagram-6RSMTGT7-CpAWp7CX.js} +1 -1
  38. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-C4dRhtxr.js → gitGraphDiagram-PVQCEYII-NbgB-War.js} +1 -1
  39. package/dist/web-ui/assets/{index-C-JeUF8o.js → index-ByDm2R2Q.js} +4 -4
  40. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-D7J6SUW3.js → infoDiagram-5YYISTIA-raIYdtwN.js} +1 -1
  41. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-DLkxtd74.js → ishikawaDiagram-YF4QCWOH-DgldiO9i.js} +1 -1
  42. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-Du67A9Yw.js → journeyDiagram-JHISSGLW-C0Ggun7y.js} +1 -1
  43. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-NjM-JWNB.js → kanban-definition-UN3LZRKU-Dv28stos.js} +1 -1
  44. package/dist/web-ui/assets/{mermaid.core-DZ44f5S6.js → mermaid.core-CKl3afmE.js} +5 -5
  45. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-jzJVxMGu.js → mindmap-definition-RKZ34NQL-ClLrKr92.js} +1 -1
  46. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Bji1NMKi.js → pieDiagram-4H26LBE5-B17e_RsX.js} +1 -1
  47. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CVn-a7Se.js → quadrantDiagram-W4KKPZXB-UsM2h5vg.js} +1 -1
  48. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-C0NfgW04.js → requirementDiagram-4Y6WPE33-Bk8JUCl8.js} +1 -1
  49. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-YU6cIInr.js → sankeyDiagram-5OEKKPKP-DJTiJaZJ.js} +1 -1
  50. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-D2tlIr4X.js → sequenceDiagram-3UESZ5HK-CeSW5rTy.js} +1 -1
  51. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-YlXSGJww.js → stateDiagram-AJRCARHV-BZrwgveS.js} +1 -1
  52. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DhFW_GeR.js +1 -0
  53. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-vHgUjj7M.js → timeline-definition-PNZ67QCA-CC6erNUi.js} +1 -1
  54. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-D98-iHMN.js → vennDiagram-CIIHVFJN-Dq3XTEho.js} +1 -1
  55. package/dist/web-ui/assets/{wardley-L42UT6IY-BExY05R5.js → wardley-L42UT6IY-0QJodPho.js} +1 -1
  56. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-hUWvRAhb.js → wardleyDiagram-YWT4CUSO-D8GA1BsQ.js} +1 -1
  57. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-B0zLuKau.js → xychartDiagram-2RQKCTM6-D2jxDEwf.js} +1 -1
  58. package/dist/web-ui/index.html +1 -1
  59. package/package.json +1 -1
  60. package/dist/web-ui/assets/channel-CrGHeOxn.js +0 -1
  61. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-h8nFueDV.js +0 -1
  62. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-h8nFueDV.js +0 -1
  63. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-Dk-B40e3.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C-JeUF8o.js","assets/index-BfGY_nvu.css"])))=>i.map(i=>d[i]);
2
- import{r as k,k as Rx,u as Lt,B as p_,j as c,q as xa,a0 as m_,a as Af,b as Mf,P as Kt,c as ah,l as K,w as yt,M as g_,A as js,n as Qr,E as So,i as Ax,a1 as O_,a2 as x_,a3 as b_,a4 as Dm,a5 as $l,o as Im,h as Lf,d as Mx,a6 as Lx,a7 as Cc,a8 as v_,a9 as y_,aa as Bm,ab as S_,U as __,W as Nx,V as Dx,G as w_,ac as k_,ad as C_,_ as Ix,m as Wm,ae as _n,af as P_,ag as T_,ah as fd,ai as Xm,aj as Q_,ak as pd,al as $_,am as qm,an as zm,ao as j_,ap as Zm,C as Vm,aq as Fm,ar as E_,as as R_,at as A_,au as Ym,av as M_,aw as L_,ax as N_,ay as D_,az as I_,aA as B_,aB as W_,p as X_,aC as lc,aD as cc,aE as q_,aF as z_}from"./index-C-JeUF8o.js";import{r as Um,p as Z_}from"./CommentInput-BRkHjDZN.js";import{ContentRenderer as _u,resolveFormat as V_}from"./ContentRenderer-BHf4qoQ8.js";import{a as F_,c as Y_,O as U_,D as H_}from"./DeliverableShareModal-BuGiP0iO.js";function Yn(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let m;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(m=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-m)*100)/100,g=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-ByDm2R2Q.js","assets/index-BfGY_nvu.css"])))=>i.map(i=>d[i]);
2
+ import{r as k,k as Rx,u as Lt,B as p_,j as c,q as xa,a0 as m_,a as Af,b as Mf,P as Kt,c as ah,l as K,w as yt,M as g_,A as js,n as Qr,E as So,i as Ax,a1 as O_,a2 as x_,a3 as b_,a4 as Dm,a5 as $l,o as Im,h as Lf,d as Mx,a6 as Lx,a7 as Cc,a8 as v_,a9 as y_,aa as Bm,ab as S_,U as __,W as Nx,V as Dx,G as w_,ac as k_,ad as C_,_ as Ix,m as Wm,ae as _n,af as P_,ag as T_,ah as fd,ai as Xm,aj as Q_,ak as pd,al as $_,am as qm,an as zm,ao as j_,ap as Zm,C as Vm,aq as Fm,ar as E_,as as R_,at as A_,au as Ym,av as M_,aw as L_,ax as N_,ay as D_,az as I_,aA as B_,aB as W_,p as X_,aC as lc,aD as cc,aE as q_,aF as z_}from"./index-ByDm2R2Q.js";import{r as Um,p as Z_}from"./CommentInput-CidSogOF.js";import{ContentRenderer as _u,resolveFormat as V_}from"./ContentRenderer-BsmttX9l.js";import{a as F_,c as Y_,O as U_,D as H_}from"./DeliverableShareModal-Ck-iPMFP.js";function Yn(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let m;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(m=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-m)*100)/100,g=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*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function Hm(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const G_=(s,e)=>Math.abs(s-e)<1.01,K_=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},Gm=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},J_=s=>s,ew=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},tw=(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(Gm(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const h=l.borderBoxSize[0];if(h){i({width:h.inlineSize,height:h.blockSize});return}}i(Gm(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},Km={passive:!0},Jm=typeof window>"u"?!0:"onscrollend"in window,sw=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&Jm?()=>{}:K_(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,Km);const h=s.options.useScrollendEvent&&Jm;return h&&t.addEventListener("scrollend",l,Km),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},rw=(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"]},iw=(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 nw{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:J_,rangeExtractor:ew,onChange:()=>{},measureElement:rw,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},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const m of this.laneAssignments.keys())m>=t&&this.laneAssignments.delete(m);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(m=>{this.itemSizeCache.set(m.key,m.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 m=0;m<d;m++){const v=u[m];v&&(f[v.lane]=m)}for(let m=d;m<t;m++){const v=n(m),b=this.laneAssignments.get(m);let g,O;const p=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const w=f[g],T=w!==void 0?u[w]:void 0;O=T?T.end+this.options.gap:r+i}else{const w=this.options.lanes===1?u[m-1]:this.getFurthestMeasurement(u,m);O=w?w.end+this.options.gap:r+i,g=w?w.lane:m%this.options.lanes,this.options.lanes>1&&p&&this.laneAssignments.set(m,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(m),S=O+y;u[m]={index:m,start:O,size:y,end:S,key:v,lane:g},f[g]=m}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?ow({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 Hm(r[Bx(0,r.length-1,i=>Hm(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&&G_(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 Bx=(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 ow({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=Bx(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(d=>d>=t);){const d=s[a];h[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const eg=typeof document<"u"?k.useLayoutEffect:k.useEffect;function aw({useFlushSync:s=!0,...e}){const t=k.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Rx.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=k.useState(()=>new nw(r));return i.setOptions(r),eg(()=>i._didMount(),[]),eg(()=>i._willUpdate()),i}function lw(s){return aw({observeElementRect:tw,observeElementOffset:sw,scrollToFn:iw,...s})}const tg={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 cw({notification:s,agentName:e,acknowledging:t,onClose:r,onAcknowledge:i}){const{t:n}=Lt(["team","common"]);p_(!0);const a=s.priority||"normal",o=s.metadata??{},l=e||(typeof o.agentName=="string"?o.agentName:void 0);return Rx.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:h=>{h.target===h.currentTarget&&r()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[l&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:l}),a!=="normal"&&c.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${tg[a]??tg.normal}`,children:a})]})]}),c.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),c.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:c.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:c.jsx(xa,{content:s.body||""})})}),c.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[c.jsx("button",{onClick: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")}),c.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 ba({children:s,onClose:e,title:t,width:r="w-[440px]"}){return c.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:c.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[c.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function to({label:s,children:e}){return c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function hw({onClose:s,onCreate:e}){const{t}=Lt(["team","common"]),[r,i]=k.useState(""),[n,a]=k.useState("");return c.jsx(ba,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(to,{label:t("team:modals.createTeam.teamName"),children:c.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),c.jsx(to,{label:t("team:modals.createTeam.description"),children:c.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),c.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:c.jsx(m_,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:c.jsx("span",{className:"text-brand-400 font-medium"}),1:c.jsx("span",{className:"text-brand-400"})}})}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function dw({onClose:s,onAdd:e}){const{t}=Lt(["team","common"]),[r,i]=k.useState(""),[n,a]=k.useState("member"),[o,l]=k.useState(""),[h,d]=k.useState(""),[u,f]=k.useState(!1),[m,v]=k.useState(null),[b,g]=k.useState(!1),O=m?.inviteToken?`${window.location.origin}/#invite?token=${m.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),g(!0),setTimeout(()=>g(!1),2e3))};return m?c.jsxs(ba,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[c.jsxs("div",{className:"text-center py-4",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:m.userName})}),O?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),c.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),c.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),c.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${b?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(b?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):c.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),c.jsx("div",{className:"flex justify-end pt-3",children:c.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):c.jsx(ba,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[c.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),c.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",c.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),c.jsx(to,{label:t("team:modals.addHuman.name"),children:c.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),c.jsx(to,{label:t("team:modals.addHuman.role"),children:c.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[c.jsx("option",{value:"owner",children:t("common:role.owner")}),c.jsx("option",{value:"admin",children:t("common:role.admin")}),c.jsx("option",{value:"member",children:t("common:role.member")}),c.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),c.jsx(to,{label:t("team:modals.addHuman.emailRequired"),children:c.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),h&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick: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 uw({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=Lt(["team","common"]);return c.jsx(ba,{onClose:t,title:i("team:modals.addExisting.title"),children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?c.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):c.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>c.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[c.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),c.jsxs("div",{className:"flex-1",children:[c.jsx("div",{className:"font-medium text-sm",children:n.name}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&c.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),c.jsx("div",{className:"flex justify-end pt-2",children:c.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function fw({onClose:s,onConnected:e}){const{t}=Lt(["team","common"]),[r,i]=k.useState(""),[n,a]=k.useState(""),[o,l]=k.useState(!1),[h,d]=k.useState(null),[u,f]=k.useState(null),m=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const g=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!g.ok){const p=await g.json().catch(()=>({}));throw new Error(p.error??`HTTP ${g.status}`)}const O=await g.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(g){a(String(g))}l(!1)},v=(b,g)=>{navigator.clipboard.writeText(b),f(g),setTimeout(()=>f(null),2e3)};return c.jsx(ba,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:h?(()=>{const b=h.gatewayUrl??`${window.location.origin}/api/gateway`,g=h.token?t("team:modals.openClaw.bearerTokenLine",{token:h.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:h.externalAgentId,tokenSection:g});return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-center py-6",children:[c.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),c.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),c.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:c.jsx("strong",{children:r})})]}),c.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),c.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),c.jsx("div",{className:"flex justify-end pt-5",children:c.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),c.jsxs("div",{className:"space-y-4",children:[c.jsx(to,{label:t("team:modals.openClaw.agentName"),children:c.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:m,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 jl=new Map;function pw({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=Lt(["team","common"]),[a,o]=k.useState(""),[l,h]=k.useState(new Set),[d,u]=k.useState(""),[f,m]=k.useState(!1),v=k.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=k.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]),g=p=>{h(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;m(!0);const p=[...l],x={},y={};for(const S of p){const w=v.find(T=>T.id===S);w&&(x[S]=w.type,y[S]=w.name)}await i(a.trim(),p,x,y),m(!1)};return c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),c.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:c.jsx("input",{value:a,onChange: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})}),c.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:c.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"})}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&c.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(p=>c.jsxs("button",{onClick:()=>g(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:[c.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)&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx(js,{name:p.name,size:20,bgClass:p.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate text-[11px] font-medium block",children:p.name}),c.jsx("span",{className:"text-[9px] text-fg-tertiary",children:p.subtitle})]}),c.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))]}),c.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),c.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const mw=k.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:h,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:m,onSelectDm:v,onSelectTeam:b,selectedTeamId:g,onRefreshTeams:O,onRefreshAgents:p,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:S,onManageGroupMembers:w,unreadByAgent:T,unreadByChannel:_,width:P,onResizeStart:L,hidden:N,onCollapse:$,initialLoading:R,previewMode:D,focused:V,l2Available:Z}){const{t:z}=Lt(["team","common"]),J=Af(),Q=Mf(Kt.TEAM),A=ah(),B=e?.role==="owner"||e?.role==="admin",q=k.useMemo(()=>new Set(a.map(X=>X.markusAgentId).filter(Boolean)),[a]),[H,te]=k.useState([]),[de,we]=k.useState(new Set),[U,I]=k.useState(!1),[se,F]=k.useState(!1),[G,ee]=k.useState(null),[ke,Le]=k.useState(!1),[be,me]=k.useState(!1),[Oe,He]=k.useState(null),[ot,Pt]=k.useState(null),[pt,qt]=k.useState(null),[wt,Rt]=k.useState(!1),[Tt,he]=k.useState(""),[Xe,ge]=k.useState(null),[Je,Me]=k.useState(null),[bt,at]=k.useState(null),[ir,ts]=k.useState(!1),Ja=k.useRef(null),[el,tl]=k.useState(null),nn=k.useRef(null),si=k.useRef(null),[To,sl]=k.useState(null),ji=(X,le="success")=>{sl({message:X,type:le}),setTimeout(()=>sl(null),3e3)},[nr,Ei]=k.useState(null),[In,Qo]=k.useState(!1),on=k.useRef(!1);k.useEffect(()=>{if(D)return;K.governance.getSystemStatus().then(pe=>{on.current=!0,Ei(pe.globalPaused)}).catch(()=>{on.current=!0,Ei(!1)});const X=yt.on("system:pause-all",()=>{on.current&&Ei(!0)}),le=yt.on("system:resume-all",()=>{on.current&&Ei(!1)});return()=>{X(),le()}},[]),k.useEffect(()=>{if(!D)return;const X=setTimeout(()=>{const le=si.current,pe=nn.current;le&&pe&&pe.scrollTo({top:le.offsetTop-pe.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(X)},[D]);const Ch=k.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()=>{Qo(!0);try{nr?(await K.governance.resumeAll(),Ei(!1)):(await K.governance.pauseAll(),Ei(!0))}catch{}Qo(!1)}})},[nr]),[Lr,Ri]=k.useState(null),an=(X,le,pe,je,Ge)=>{Ri({title:X,message:le,onConfirm:pe,confirmLabel:je,checkboxes:Ge})},[or,rl]=k.useState(null),[vr,$o]=k.useState(null),ri=k.useRef(null),Nr=k.useRef(null),[us,jo]=k.useState(!1),[il,ne]=k.useState(null),[gt,xe]=k.useState(""),Yt=k.useCallback((X,le=176,pe=220)=>{const je=window.innerWidth,Ge=window.innerHeight,et=8;let Ot=X.clientX,St=X.clientY;return Ot+le>je-et&&(Ot=Math.max(et,je-le-et)),St+pe>Ge-et&&(St=Math.max(et,Ge-pe-et)),Ot=Math.max(et,Math.min(Ot,je-le-et)),St=Math.max(et,Math.min(St,Ge-pe-et)),{x:Ot,y:St}},[]),[mt,ks]=k.useState(jl),Ut=k.useMemo(()=>t.map(X=>X.id).sort().join(","),[t]);k.useEffect(()=>{if(!t.length||!Q)return;let X=!1;(async()=>{const St=[];await Promise.allSettled(t.map(async Ue=>{if(!jl.has(Ue.id))try{const{sessions:ns}=await K.sessions.listByAgent(Ue.id,1);if(!ns.length)return;const{messages:Ls}=await K.sessions.getMessages(ns[0].id,1);if(Ls.length){const At=Ls[0],Os=At.metadata?.segments;let Ht=At.content;if(Os&&Os.length>0){const _r=[...Os].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([Ue.id,Ts])}}catch{}})),!X&&St.length&&ks(Ue=>{const ns=new Map(Ue);for(const[Ls,At]of St)ns.set(Ls,At);return jl=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,Ue)=>{if(!St||!Ue||!pe.has(St))return;const ns=je(Ue);ns&&ks(Ls=>{const At=new Map(Ls);return At.set(St,ns),jl=At,At})},et=yt.on("chat:proactive_message",St=>{const Ue=St.payload;Ge(Ue.agentId??"",Ue.message??"")}),Ot=yt.on("chat:message",St=>{const Ue=St.payload,ns=Ue.senderId??Ue.agentId??"",Ls=Ue.text??Ue.message??"";Ge(ns,Ls)});return()=>{X=!0,et(),Ot()}},[Ut,Q]);const ms=k.useCallback(()=>{D||K.teams.list().then(X=>te(X.ungrouped)).catch(()=>{})},[D]);k.useEffect(()=>{ms()},[ms]),k.useEffect(()=>{if(!Q)return;const X=yt.on("team:update",ms),le=yt.on("agent:removed",ms);return()=>{X(),le()}},[ms,Q]),k.useEffect(()=>{if(!ot&&!pt&&!Xe&&!ir&&!bt)return;const X=()=>{Pt(null),qt(null),ge(null),at(null),ts(!1)},le=setTimeout(()=>document.addEventListener("click",X),0);return()=>{clearTimeout(le),document.removeEventListener("click",X)}},[ot,pt,Xe,ir,bt]);const nl=(X,le)=>{an(`${z("common:delete")} "${le}"?`,z("modals.deleteTeam.message"),async pe=>{const je=pe?.deleteMembers??!0,Ge=pe?.purgeFiles??!1;await K.teams.delete(X,je,{purgeFiles:Ge}),O(),ms(),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(X,le)=>{try{const je=await(le==="start"?K.teams.startAll:K.teams.stopAll)(X),Ge=je.success?.length??0,et=je.failed?.length??0;et>0?ji(z("batchAction.failed",{action:z(`batchAction.operation.${le}`),ok:Ge,fail:et}),"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")}},Eo=async(X,le,pe)=>{await K.teams.update(X,{managerId:le,managerType:pe}),O()},ol=async X=>{if(!gt.trim()){ne(null);return}await K.teams.update(X,{name:gt.trim()}),ne(null),O()},al=async(X,le)=>{le==="offline"?await K.agents.start(X):await K.agents.stop(X),p()},Zt=(X,le)=>{an(z("modals.removeFromTeam.title"),z("modals.removeFromTeam.message"),async()=>{await K.teams.removeMember(X,le),O(),ms()},z("common:remove"))},Cs=(X,le,pe,je)=>{an(`${z("common:remove")} "${le}"?`,z(pe==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ge=>{if(pe==="agent"&&je){const et=o.find(Ot=>Ot.type==="team"&&Ot.teamId===je);et?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+et.channelKey)}if(pe==="agent"){const et=Ge?.purgeFiles??!1;await K.agents.remove(X,{purgeFiles:et})}else await K.users.remove(X);p(),O(),x?.(),ms(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},z("common:remove"),pe==="agent"?[{id:"purgeFiles",label:z("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},Ms=X=>{if(X.isOrgSecretary||X.protected)return!0;if(X.teamId)return!1;const le=(X.role??"").toLowerCase().trim(),pe=(X.name??"").trim();return pe==="Secretary"||pe==="秘书"||le==="secretary"||le.startsWith("secretary")},gs=(X,le,pe)=>{const je=t.find(Ge=>Ge.id===le);je&&Ms(je)||(Nr.current={x:X.clientX,y:X.clientY},ri.current=setTimeout(()=>{rl({agentId:le,fromTeamId:pe}),jo(!0)},200))},Ph=X=>{if(!Nr.current||!ri.current)return;const le=Math.abs(X.clientX-Nr.current.x),pe=Math.abs(X.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 X=vr==="_ungrouped"?void 0:vr;try{if(or.fromTeamId&&or.fromTeamId!==X&&await K.teams.removeMember(or.fromTeamId,or.agentId),X&&X!==or.fromTeamId){const le=t.find(pe=>pe.id===or.agentId);await K.teams.addMember(X,or.agentId,"agent")}O(),p(),ms()}catch(le){ji(z("batchAction.moveFailed",{error:le instanceof Error?le.message:String(le)}),"error")}}rl(null),$o(null),jo(!1)},ss=k.useMemo(()=>new Map(r.map(X=>[X.id,X])),[r]),ar=k.useMemo(()=>{const X=new Map,le=[];for(const pe of t)if(pe.teamId&&ss.has(pe.teamId)){const je=X.get(pe.teamId)??[];je.push(pe),X.set(pe.teamId,je)}else le.push(pe);return{byTeam:X,ungrouped:le}},[t,ss]),ii=(X,le)=>{const pe=l==="direct"&&h===X.id,je=q.has(X.id),Ge=X.status==="offline",et=X.status==="idle"?"bg-green-500":X.status==="working"?"bg-blue-500 animate-pulse":X.status==="error"?"bg-red-500":"bg-gray-600",St=(void 0)?.managerId===X.id,Ue=X.role?.toLowerCase().replace(/[-_]/g," ").trim(),ns=X.name.toLowerCase().trim(),Ls=Ue&&Ue!==ns,At=mt.get(X.id)||X.currentActivity?.label?.slice(0,60)||"",Os=X.status==="idle"?z("common:status.online"):X.status==="working"?z("common:status.working"):X.status==="error"?z("common:status.error"):z("common:status.offline");return c.jsx("div",{className:`relative mb-0.5 ${us&&or?.agentId===X.id?"opacity-40":""}`,onPointerDown:Ht=>gs(Ht,X.id,le),onPointerMove:Ph,onPointerUp:yr,children:c.jsxs("button",{"data-l1-nav-id":`agent:${X.id}`,onClick:()=>{us||f(X.id)},onContextMenu:Ht=>{if(!B)return;Ht.preventDefault();const Ts=Yt(Ht);Rt(!1),he(""),qt({agentId:X.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:[c.jsx(js,{name:X.name,avatarUrl:X.avatarUrl,size:28,bgClass:Ge?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:X.name}),Ls&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",X.role,")"]}),St&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),je&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ge&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:z("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:At||" "})]}),c.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(T?.get(X.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:T.get(X.id)}),X.mailboxDepth!=null&&X.mailboxDepth>0&&c.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:X.mailboxDepth}),c.jsx("span",{title:Os,onClick:Ht=>{Ht.stopPropagation(),S(X.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${et}`}),J&&B&&c.jsx("span",{role:"button",tabIndex:0,onClick:Ht=>{if(Ht.stopPropagation(),pt?.agentId===X.id)qt(null);else{const Ts=Yt(Ht);Rt(!1),he(""),qt({agentId:X.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:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},X.id)},Sr=(X,le,pe,je)=>{const Ge=us&&vr===X&&or?.fromTeamId!==X,et=el===X,Ot=g===X,St=T?(ar.byTeam.get(X)??[]).reduce((Wt,wr)=>Wt+(T.get(wr.id)??0),0):0,Ue=o.find(Wt=>Wt.type==="team"&&Wt.teamId===X),ns=Ue&&_?_[Ue.channelKey]??0:0,Ls=St+ns,At=ar.byTeam.get(X)??[],Os=At.filter(Wt=>Wt.status==="offline").length,Ht=At.length,Ts=Ht>0&&Os===Ht,_r=Os>0&&!Ts,Mi=Ts?"bg-gray-500":_r?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":X,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ge?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${et?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{us&&$o(X)},onPointerLeave:()=>{us&&vr===X&&$o(null)},children:[c.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[c.jsxs("button",{"data-l1-nav-id":`team:${X}`,onClick:()=>{b&&X!=="_ungrouped"&&b(X)},onContextMenu:Wt=>{if(!B||!le)return;Wt.preventDefault();const wr=Yt(Wt);Pt({teamId:X,...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:[c.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?c.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,c.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:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ht>0&&c.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${Mi}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[il===X?c.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=>xe(Wt.target.value),onBlur:()=>ol(X),onKeyDown:Wt=>{Wt.key==="Enter"&&ol(X),Wt.key==="Escape"&&ne(null)},onClick:Wt=>Wt.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:je}),c.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&&c.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&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Os,"/",Ht]})]})]}),Ls>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:Ls}),c.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),B&&le&&c.jsx("button",{onClick:Wt=>{if(Wt.stopPropagation(),ot?.teamId===X)Pt(null);else{const wr=Yt(Wt);Pt({teamId:X,...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:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ge&&us&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:z("chat.dropHere")})]},X)},Xs=k.useMemo(()=>{const X=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 et=X.get(Ge.teamId)??[];et.push(Ge),X.set(Ge.teamId,et)}else{const et=r.find(Ot=>Ge.name.toLowerCase().includes(Ot.name.toLowerCase())||Ot.name.toLowerCase().includes(Ge.name.toLowerCase()));if(et){const Ot=X.get(et.id)??[];Ot.push(Ge),X.set(et.id,Ot)}else le.push(Ge)}return{byTeam:X,unmatched:le,custom:pe,dmChannels:je}},[o,r]),[lt,ft]=k.useState(!1),ni=l==="channel"&&Xs.dmChannels.some(X=>X.channelKey===d);k.useEffect(()=>{ni&&ft(!0)},[ni]);const ln=k.useMemo(()=>{const X=[];e&&X.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const pe of i)pe.id!==e?.id&&X.push({kind:"dm",id:`dm:${pe.id}`,userId:pe.id});for(const pe of Xs.custom)X.push({kind:"channel",id:`channel:${pe.channelKey}`,channelKey:pe.channelKey});for(const pe of Xs.unmatched)X.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)X.push({kind:"agent",id:`agent:${pe.id}`,agentId:pe.id});for(const pe of r)X.push({kind:"team",id:`team:${pe.id}`,teamId:pe.id});if(lt)for(const pe of Xs.dmChannels)X.push({kind:"channel",id:`channel:${pe.channelKey}`,channelKey:pe.channelKey});return X},[e,i,Xs,ar,r,t,lt]),ll=k.useRef(ln);ll.current=ln;const cn=k.useCallback(X=>{X.kind==="dm"?v(X.userId):X.kind==="channel"?m(X.channelKey):X.kind==="agent"?f(X.agentId):X.kind==="team"&&b?.(X.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${X.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,m,f,b]);k.useEffect(()=>{if(D||J||!Q||N)return;const X=le=>{const pe=A?.keyboardPane??"content";if(pe==="l0"||pe==="l2"||le.metaKey||le.ctrlKey||le.altKey||Ax(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 et=ll.current;if(et.length===0)return;let Ot=-1;if(l==="dm"){const Ue=u||e?.id;Ue&&(Ot=et.findIndex(ns=>ns.kind==="dm"&&ns.userId===Ue))}else l==="direct"?Ot=et.findIndex(Ue=>Ue.kind==="agent"&&Ue.agentId===h):l==="channel"&&(Ot=et.findIndex(Ue=>Ue.kind==="channel"&&Ue.channelKey===d),Ot<0&&g&&(Ot=et.findIndex(Ue=>Ue.kind==="team"&&Ue.teamId===g)));Ot<0&&(Ot=Ge>0?-1:0);const St=Math.max(0,Math.min(et.length-1,Ot+Ge));cn(et[St])};return document.addEventListener("keydown",X,!0),()=>document.removeEventListener("keydown",X,!0)},[D,J,Q,N,A,V,Z,l,u,e?.id,h,d,g,cn]);const Ps=X=>X?V?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${P!=null?"shrink-0":"flex-1 min-w-0"} ${V?"ring-1 ring-inset ring-brand-500/30":""}`,style:N?{display:"none"}:P!=null?{width:P}:void 0,children:[c.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[J&&c.jsx(g_,{}),!J&&$&&c.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:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsx("h2",{className:"text-lg font-semibold",children:z("chat.title")}),B&&c.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ja,children:[c.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:[c.jsx("span",{className:"text-brand-500",children:"+"})," ",z("chat.manage"),c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${ir?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),ir&&c.jsxs("div",{ref:X=>{if(!X)return;const le=X.getBoundingClientRect(),pe=window.innerWidth,je=8;le.right>pe-je&&(X.style.left="auto",X.style.right="0"),le.left<je&&(X.style.left="0",X.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[c.jsxs("button",{onClick:()=>{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:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),c.jsx("circle",{cx:"12",cy:"5",r:"2"}),c.jsx("path",{d:"M12 7v4"}),c.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),z("chat.addAgent")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.addAgentDesc")})]}),c.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:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),c.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),z("chat.newTeam")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.newTeamDesc")})]}),c.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:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M20 8v6"}),c.jsx("path",{d:"M23 11h-6"})]}),z("chat.addHuman")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.addHumanDesc")})]}),c.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:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),c.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),z("chat.newGroupChat")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z("chat.newGroupChatDesc")})]}),nr!==null&&c.jsxs("button",{onClick:()=>{ts(!1),Ch()},disabled:In,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:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:nr?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",z("chat.resume")]}):c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",z("contextMenu.stopAll")]})}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:z(nr?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:nn,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:z("chat.people")}),e&&c.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${Ps(l==="dm"&&(u===e.id||!u))}`,children:[c.jsx(js,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:z("chat.myNotes")})]}),c.jsx("span",{className:"text-fg-secondary shrink-0",children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(X=>X.id!==e?.id).map(X=>{const le=e?.id?`dm:${[e.id,X.id].sort().join(":")}`:"",pe=le&&_?_[le]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${X.id}`,onClick:()=>v(X.id),onContextMenu:je=>{if(!B||X.id===e?.id)return;je.preventDefault();const Ge=Yt(je);ge({userId:X.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===X.id?V?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[c.jsx(js,{name:X.name,avatarUrl:X.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:X.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:X.email||X.role})]}),pe>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:pe}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},X.id)})]}),Xs.custom.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:z("chat.groups")}),Xs.custom.map(X=>{const le=l==="channel"&&d===X.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${X.channelKey}`,onClick:()=>m(X.channelKey),onContextMenu:pe=>{pe.preventDefault();const je=Yt(pe);at({gcId:X.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:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:X.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:z("chat.members_other",{count:X.memberCount??0})})]})]},X.id)})]}),R?c.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((X,le)=>c.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[c.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),c.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),c.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},le))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:z("chat.noAgentsYet")}):null,Xs.unmatched.map(X=>{const le=_?.[X.channelKey]??0;return c.jsxs("button",{"data-l1-nav-id":`channel:${X.channelKey}`,onClick:()=>m(X.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===X.channelKey)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:X.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:z("chat.groupChat")})]}),le>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:le}):X.memberCount!==void 0&&X.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:X.memberCount}):null]},X.id)}),ar.ungrouped.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:z("chat.agents")}),ar.ungrouped.map(X=>ii(X))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:si,children:[c.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(X=>{const le=ar.byTeam.get(X.id)??[],pe=X.members?.length||le.length;return Sr(X.id,X,pe,X.name)})]}),r.length===0&&ar.ungrouped.length===0&&t.length>0&&t.map(X=>ii(X)),Xs.dmChannels.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>ft(X=>!X),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${lt?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),z("chat.agentDMs"),c.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Xs.dmChannels.length})]}),lt&&Xs.dmChannels.map(X=>{const le=l==="channel"&&d===X.channelKey,pe=_?.[X.channelKey]??0,je=X.name.replace(/^DM:\s*/,"");return c.jsxs("button",{"data-l1-nav-id":`channel:${X.channelKey}`,onClick:()=>m(X.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:[c.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:je}),pe>0&&c.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:pe})]},X.id)})]})]})]}),L&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:L,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),ot&&(()=>{const X=ar.byTeam.get(ot.teamId)??[],le=X.some(je=>je.status==="offline"),pe=X.some(je=>je.status!=="offline");return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:ot.x,top:ot.y},onClick:je=>je.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const je=ss.get(ot.teamId);je&&(ne(ot.teamId),xe(je.name)),Pt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),z("contextMenu.renameTeam")]}),le&&c.jsxs("button",{onClick:()=>{Ai(ot.teamId,"start"),Pt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),z("contextMenu.startAll")]}),pe&&c.jsxs("button",{onClick:()=>{Ai(ot.teamId,"stop"),Pt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),z("contextMenu.stopAll")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{Pt(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:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),z("chat.addAgent")]}),H.length>0&&c.jsxs("button",{onClick:()=>{Pt(null),ee(ot.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),c.jsx("polyline",{points:"17 11 19 13 23 9"})]}),z("contextMenu.addExisting")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{const je=ss.get(ot.teamId);je&&nl(ot.teamId,je.name),Pt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.deleteTeam")]})]})})(),pt&&(()=>{const X=t.find(et=>et.id===pt.agentId);if(!X||!B)return null;const pe=(pt.teamId?ss.get(pt.teamId):void 0)?.managerId===X.id,je=X.id===e?.id,Ge=Ms(X);return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:pt.x,top:pt.y,maxHeight:Math.max(160,window.innerHeight-pt.y-8)},onClick:et=>et.stopPropagation(),children:[Ge&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:z("contextMenu.orgSecretaryProtected")}),c.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),c.jsxs("button",{onClick:()=>{qt(null),S(X.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),z("contextMenu.viewProfile")]}),X.status==="offline"?c.jsxs("button",{onClick:()=>{al(X.id,"offline"),qt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),z("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{al(X.id,X.status??"idle"),qt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),z("contextMenu.stop")]}),!Ge&&pt.teamId&&!pe&&c.jsxs("button",{onClick:()=>{Eo(pt.teamId,X.id,"agent"),qt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),z("contextMenu.setAsManager")]}),!Ge&&pt.teamId&&c.jsxs("button",{onClick:()=>{Zt(pt.teamId,X.id),qt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),z("contextMenu.removeFromTeam")]}),!Ge&&(()=>{const et=r.filter(Ue=>Ue.id!==pt.teamId);if(et.length===0)return null;const Ot=Tt.trim().toLowerCase(),St=Ot?et.filter(Ue=>Ue.name.toLowerCase().includes(Ot)):et;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>Rt(Ue=>!Ue),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:z("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${wt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),wt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:Ue=>Ue.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:Tt,onChange:Ue=>he(Ue.target.value),onKeyDown:Ue=>Ue.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"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:St.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:z("contextMenu.moveToEmpty")}):St.map(Ue=>c.jsx("button",{type:"button",onClick:async()=>{pt.teamId&&await K.teams.removeMember(pt.teamId,X.id),await K.teams.addMember(Ue.id,X.id,"agent"),O(),p(),ms(),qt(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Ue.name,children:Ue.name},Ue.id))})]})]})})(),!Ge&&!je&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{Cs(X.id,X.name,"agent",pt.teamId),qt(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.removeFromOrg")]})]})]})})(),Xe&&(()=>{const X=i.find(le=>le.id===Xe.userId);return!X||!B?null:c.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Xe.x,top:Xe.y},onClick:le=>le.stopPropagation(),children:c.jsxs("button",{onClick:()=>{Cs(X.id,X.name,"human"),ge(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("contextMenu.removeFromOrg")]})})})(),U&&c.jsx(hw,{onClose:()=>I(!1),onCreate:async(X,le)=>{try{const{team:pe}=await K.teams.create(X,le);I(!1),O(),tl(pe.id),setTimeout(()=>{document.querySelector(`[data-team-id="${pe.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>tl(null),3e3)}catch(pe){ji(z("chat.failedToCreateTeam",{message:pe instanceof Error?pe.message:String(pe)}),"error")}}}),se&&c.jsx(dw,{onClose:()=>{F(!1),x?.()},onAdd:async(X,le,pe)=>{const{inviteToken:je}=await K.users.create(X,le,void 0,pe);return x?.(),{inviteToken:je}}}),G!==null&&c.jsx(uw,{teamId:G,ungrouped:H,onClose:()=>ee(null),onAdd:async(X,le)=>{await K.teams.addMember(G,X,le),ee(null),O(),ms()}}),ke&&c.jsx(fw,{onClose:()=>Le(!1),onConnected:()=>{Le(!1),p(),O()}}),bt&&(()=>{const X=o.find(le=>le.id===bt.gcId);return X?c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:bt.x,top:bt.y},onClick:le=>le.stopPropagation(),children:[X.type==="custom"&&c.jsxs("button",{onClick:()=>{at(null),w?w(X.channelKey):m(X.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),z("contextMenu.manageMembers")]}),c.jsxs("button",{onClick:async()=>{at(null),an(z("modals.deleteGroupChat.title"),z("modals.deleteGroupChat.message",{name:X.name}),async()=>{await K.groupChats.delete(X.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:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),z("modals.deleteGroupChat.menuLabel")]})]}):null})(),be&&c.jsx(pw,{agents:t,humans:i,authUser:e,onClose:()=>me(!1),onCreate:async(X,le,pe,je)=>{await K.groupChats.create({name:X,memberIds:le,memberTypes:pe,memberNames:je,creatorId:e?.id,creatorName:e?.name}),me(!1),y()}}),Oe&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>He(null),children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:X=>X.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:z(Oe==="agent"?"chat.addAgent":"chat.newTeam")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:z("chat.methodChoiceSubtitle")})]}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsxs("button",{onClick:()=>{const X=Oe;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(X==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):X==="agent"?Qr.navigate(Kt.STORE):I(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),c.jsx("path",{d:"M20 3v4"}),c.jsx("path",{d:"M22 5h-4"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:z("chat.methodSecretary")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:z("chat.methodSecretaryDesc")})]}),c.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:z("chat.recommended")})]}),c.jsxs("button",{onClick:()=>{const X=Oe;He(null),X==="agent"?Qr.navigate(Kt.STORE):I(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:z("chat.methodManual")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:z(Oe==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),c.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:c.jsx("button",{onClick:()=>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&&c.jsx(So,{title:Lr.title,message:Lr.message,confirmLabel:Lr.confirmLabel,checkboxes:Lr.checkboxes,onConfirm:X=>{Lr.onConfirm(X),Ri(null)},onCancel:()=>Ri(null)}),To&&c.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${To.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:To.message})]})});function sg({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:h,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:m,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:g,unreadByAgent:O,width:p,onResizeStart:x,focused:y}){const{t:S}=Lt(["team","common"]),w=ah(),T=Mf(Kt.TEAM),_=r?.role==="owner"||r?.role==="admin",P=k.useMemo(()=>e.filter(F=>F.teamId===s.id),[e,s.id]),L=k.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]),N=i&&n==="channel"&&o===i.channelKey,$=k.useMemo(()=>{const F=[];i&&F.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const G of P)F.push({kind:"agent",id:`agent:${G.id}`,agentId:G.id});for(const G of L)F.push({kind:"dm",id:`dm:${G.id}`,userId:G.id});return F},[i,P,L]),R=k.useRef($);R.current=$;const D=k.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]);k.useEffect(()=>{if(!T)return;const F=G=>{if((w?.keyboardPane??"content")!=="l2"||G.metaKey||G.ctrlKey||G.altKey||Ax(G.target))return;const ke=G.key.length===1?G.key.toLowerCase():G.key;if(ke==="h"||ke==="ArrowLeft"){G.preventDefault(),G.stopPropagation(),w?.setKeyboardPane("l1");return}if(ke==="l"||ke==="ArrowRight"){G.preventDefault(),G.stopPropagation();return}const Le=ke==="j"||ke==="ArrowDown"?1:ke==="k"||ke==="ArrowUp"?-1:0;if(!Le)return;G.preventDefault(),G.stopPropagation();const be=R.current;if(be.length===0)return;let me=-1;n==="channel"?me=be.findIndex(He=>He.kind==="channel"&&He.channelKey===o):n==="direct"?me=be.findIndex(He=>He.kind==="agent"&&He.agentId===a):n==="dm"&&l&&(me=be.findIndex(He=>He.kind==="dm"&&He.userId===l)),me<0&&(me=Le>0?-1:0);const Oe=Math.max(0,Math.min(be.length-1,me+Le));D(be[Oe])};return document.addEventListener("keydown",F,!0),()=>document.removeEventListener("keydown",F,!0)},[T,w,n,o,a,l,D]);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]=k.useState(null),[J,Q]=k.useState(!1),[A,B]=k.useState(""),[q,H]=k.useState(null),te=(F,G,ee,ke,Le)=>{H({title:F,message:G,onConfirm:ee,confirmLabel:ke,checkboxes:Le})},de=k.useCallback((F,G=176,ee=220)=>{const ke=window.innerWidth,Le=window.innerHeight,be=8;let me=F.clientX,Oe=F.clientY;return me+G>ke-be&&(me=Math.max(be,ke-G-be)),Oe+ee>Le-be&&(Oe=Math.max(be,Le-ee-be)),me=Math.max(be,Math.min(me,ke-G-be)),Oe=Math.max(be,Math.min(Oe,Le-ee-be)),{x:me,y:Oe}},[]);k.useEffect(()=>{if(!Z)return;const F=()=>z(null),G=setTimeout(()=>document.addEventListener("click",F),0);return()=>{clearTimeout(G),document.removeEventListener("click",F)}},[Z]);const we=k.useCallback(async(F,G)=>{G==="offline"?await K.agents.start(F):await K.agents.stop(F),b()},[b]),U=k.useCallback(async F=>{await K.teams.update(s.id,{managerId:F,managerType:"agent"}),g()},[s.id,g]),I=k.useCallback(async F=>{await K.teams.removeMember(s.id,F),g(),b()},[s.id,g,b]),se=k.useCallback(async(F,G)=>{await K.teams.removeMember(s.id,F),await K.teams.addMember(G,F,"agent"),g(),b()},[s.id,g,b]);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:p!=null?{width:p}:{width:260},children:[c.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:m,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:S("common:back",{defaultValue:"Back"}),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&c.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&c.jsxs("div",{className:"mb-3",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:S("chat.groupChat",{defaultValue:"Group Chat"})}),c.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${V(!!N)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:S("chat.members_other",{count:i.memberCount||P.length+L.length})})]})]})]}),P.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[S("chat.agents",{defaultValue:"Agents"}),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:P.length})]}),P.map(F=>{const G=n==="direct"&&a===F.id,ee=s.managerId===F.id,ke=F.status==="offline",Le=F.status==="idle"?"bg-green-500":F.status==="working"?"bg-blue-500 animate-pulse":F.status==="error"?"bg-red-500":"bg-gray-600";return c.jsxs("button",{"data-l2-nav-id":`agent:${F.id}`,onClick:()=>d(F.id),onContextMenu:be=>{if(!_)return;be.preventDefault();const me=de(be);Q(!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 ${ke?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${V(G)}`,children:[c.jsx(js,{name:F.name,avatarUrl:F.avatarUrl,size:28,bgClass:ke?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:F.name}),ee&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),ke&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:S("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:F.role||" "})]}),(O?.get(F.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(F.id)}),c.jsx("span",{title:F.status,onClick:be=>{be.stopPropagation(),v(F.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${Le}`})]},F.id)})]}),L.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[S("chat.people"),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:L.length})]}),L.map(F=>{const G=F.id===r?.id,ee=n==="dm"&&l===F.id;return c.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:[c.jsx(js,{name:F.name,avatarUrl:F.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[F.name,G?` (${S("chat.you",{defaultValue:"You"})})`:""]}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:F.email||F.role})]}),c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},F.id)})]}),P.length===0&&L.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:S("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),Z&&(()=>{const F=P.find(ee=>ee.id===Z.agentId);if(!F||!_)return null;const G=s.managerId===F.id;return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:Z.x,top:Z.y,maxHeight:Math.max(160,window.innerHeight-Z.y-8)},onClick:ee=>ee.stopPropagation(),children:[c.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:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),S("contextMenu.viewProfile")]}),F.status==="offline"?c.jsxs("button",{onClick:()=>{we(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:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),S("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{we(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:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),S("contextMenu.stop")]}),!G&&c.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:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),S("contextMenu.setAsManager")]}),c.jsxs("button",{onClick:()=>{I(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:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),S("contextMenu.removeFromTeam")]}),(()=>{const ee=h.filter(be=>be.id!==s.id);if(ee.length===0)return null;const ke=A.trim().toLowerCase(),Le=ke?ee.filter(be=>be.name.toLowerCase().includes(ke)):ee;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>Q(be=>!be),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:S("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${J?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),J&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:be=>be.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:A,onChange:be=>B(be.target.value),onKeyDown:be=>be.stopPropagation(),placeholder:S("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Le.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:S("contextMenu.moveToEmpty")}):Le.map(be=>c.jsx("button",{type:"button",onClick:()=>{se(F.id,be.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:be.name,children:be.name},be.id))})]})]})})(),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{te(`${S("common:remove")} "${F.name}"?`,S("modals.removeAgent.message"),async ee=>{const ke=ee?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await K.agents.remove(F.id,{purgeFiles:ke}),b(),z(null)},S("common:remove"),[{id:"purgeFiles",label:S("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),S("contextMenu.removeFromOrg")]})]})})(),q&&c.jsx(So,{title:q.title,message:q.message,confirmLabel:q.confirmLabel,checkboxes:q.checkboxes,onConfirm:F=>{q.onConfirm(F),H(null)},onCancel:()=>H(null)})]})}function wu(){return wu=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},wu.apply(null,arguments)}function gw(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 ku=[],Wx=[];(()=>{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?Wx:ku).push(t=t+s[e])})();function Ow(s){if(s<768)return!1;for(let e=0,t=ku.length;;){let r=e+t>>1;if(s<ku[r])t=r;else if(s>=Wx[r])e=r+1;else return!0;if(e==t)return!1}}function rg(s){return s>=127462&&s<=127487}const ig=8205;function xw(s,e,t=!0,r=!0){return(t?Xx:bw)(s,e,r)}function Xx(s,e,t){if(e==s.length)return e;e&&qx(s.charCodeAt(e))&&zx(s.charCodeAt(e-1))&&e--;let r=md(s,e);for(e+=ng(r);e<s.length;){let i=md(s,e);if(r==ig||i==ig||t&&Ow(i))e+=ng(i),r=i;else if(rg(i)){let n=0,a=e-2;for(;a>=0&&rg(md(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function bw(s,e,t){for(;e>1;){let r=Xx(s,e-2,t);if(r<e)return r;e--}return 0}function md(s,e){let t=s.charCodeAt(e);if(!zx(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return qx(r)?(t-55296<<10)+(r-56320)+65536:t}function qx(s){return s>=56320&&s<57344}function zx(s){return s>=55296&&s<56320}function ng(s){return s<65536?1:2}let Ct=class Zx{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]=uo(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]=uo(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 ca(this),n=new ca(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 ca(this,e)}iterRange(e,t=this.length){return new Vx(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 Fx(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]?Zx.empty:e.length<=32?new is(e):Zr.from(is.split(e,[]))}};class is extends Ct{constructor(e,t=vw(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 yw(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new is(og(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=hc(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]=uo(this,e,t);let i=hc(this.text,hc(r.text,og(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
  """`}},[de,se,p,s]),G=k.useCallback((he,Xe)=>{!he.trim()||!i||(i(F(he.trim(),Xe)),$(null),window.getSelection()?.removeAllRanges(),q.current?.clearSelection())},[i,F]),ee=k.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]);k.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),Xe=ge=>{if(!(he?ge.metaKey&&!ge.ctrlKey:ge.ctrlKey&&!ge.metaKey)||!ge.shiftKey||ge.altKey||ge.key.toLowerCase()!=="a")return;const Me=q.current?.getSelection()?.trim();Me&&(ge.preventDefault(),G(Me))};return window.addEventListener("keydown",Xe),()=>window.removeEventListener("keydown",Xe)},[s.kind,i,G]);const ke=k.useCallback(he=>{if(!he.text.trim()||!i)return;const Xe=Q.current?.querySelector("iframe")?.getBoundingClientRect(),ge=(Xe?.left??0)+he.rect.x+he.rect.width/2,Je=(Xe?.top??0)+he.rect.y;$({x:ge,y:Je,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);k.useEffect(()=>{const he=Q.current;if(!he||!i)return;const Xe=()=>{requestAnimationFrame(()=>{const Je=window.getSelection(),Me=Je?.toString().trim();if(!Me||!Je?.rangeCount){$(null);return}const bt=Je.getRangeAt(0);if(!he.contains(bt.commonAncestorContainer)){$(null);return}const at=bt.getBoundingClientRect();$({x:at.left+at.width/2,y:at.top,text:Me})})},ge=Je=>{const Me=document.getElementById("right-panel-selection-toolbar");Me&&Me.contains(Je.target)||$(null)};return he.addEventListener("mouseup",Xe),document.addEventListener("mousedown",ge),()=>{he.removeEventListener("mouseup",Xe),document.removeEventListener("mousedown",ge)}},[i,x.mode]);const Le=()=>{K.files.reveal(de).catch(()=>{})},be=()=>{navigator.clipboard?.writeText(de).then(()=>{w(!0),setTimeout(()=>w(!1),1500)}).catch(()=>{})},me=k.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 ge=await window.markusDesktop.browser.getState(s.browserId);if(ge.ok){if(ge.directoryPath){await K.system.openPath(ge.directoryPath).catch(()=>K.files.reveal(ge.directoryPath));return}ge.url&&ge.url!=="about:blank"&&(Xe=ge.url)}}catch{}if(!Xe||Xe==="about:blank")return;if(/^https?:\/\//i.test(Xe)||/^file:\/\//i.test(Xe)){$l(Xe);return}await K.system.openPath(Xe).catch(()=>$l(cx(Xe)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){$l(he);return}await K.system.openPath(he).catch(()=>$l(cx(he)))}},[s]),Oe=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"),ot=!!de&&!ic(de)&&(s.kind==="file"||s.kind==="deliverable"),Pt=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!de&&!ic(de)&&!s.deliverable.artifactType&&F_(s.deliverable.format),pt=s.kind==="deliverable"?{...s.deliverable,hubShareId:P?.id??s.deliverable.hubShareId??null,shareStatus:P?.status??s.deliverable.shareStatus??null,shareUrl:P?.url??s.deliverable.shareUrl??null,shareVisibility:P?.visibility??s.deliverable.shareVisibility??null}:null,qt=k.useCallback(he=>{L(he)},[]),wt=k.useMemo(()=>Y_(Im,Lf.getUrl()),[]),Rt=s.kind==="deliverable"?s.deliverable.id:null;k.useEffect(()=>{if(!Rt||!Im())return;let he=!1;const Xe=async()=>{try{const Je=await wt.listMine();if(he)return;const Me=s.kind==="deliverable"?s.deliverable:null;if(!Me)return;const bt=Me.hubShareId&&Je.find(ts=>ts.id===Me.hubShareId)||Je.find(ts=>ts.localId===Me.id);if(!bt)return;L(ts=>ts&&ts.id===bt.id&&ts.status===bt.status?ts:bt);const at={hubShareId:Me.hubShareId??bt.id??null,shareStatus:bt.status??null,shareUrl:bt.url??null,shareVisibility:Me.shareVisibility??bt.visibility??null};(Me.shareStatus!==at.shareStatus||Me.hubShareId!==at.hubShareId||Me.shareUrl!==at.shareUrl||Me.shareVisibility!==at.shareVisibility)&&Me.id&&K.deliverables.update(Me.id,at).catch(ts=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ts)})}catch{}};Xe();const ge=setInterval(Xe,3e4);return()=>{he=!0,clearInterval(ge)}},[wt,Rt,s]);const Tt=pt?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":m==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${m==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":m==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${m==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||h?c.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,ge=he.payload.kind==="url"?he.payload.pageId:void 0,Je=he.payload.kind==="terminal"?he.payload.terminalId:void 0,Me=ge!=null?R[ge]:Je?V[Je]:void 0,bt=Me?`${he.title} — ${p("common:browserTabControlledBy",{name:Me.agentName})}`:he.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${Xe?Me?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Me?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":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:at=>{at.button===0&&(he.id!==a&&!te()||o?.(he.id))},onClick:()=>{he.id!==a&&!te()||o?.(he.id)},children:[Me&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:p("common:browserTabControlledBy",{name:Me.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:Me.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:at=>{at.button===0&&(at.preventDefault(),at.stopPropagation(),!(he.id===a&&!te())&&l(he.id))},onClick:at=>{at.preventDefault(),at.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:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:de||we,children:we}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&i&&c.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:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),Pt&&c.jsxs("button",{type:"button",onClick:()=>_(!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 ${Tt==="published"?"text-green-500 hover:text-green-400":Tt==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"18",cy:"5",r:"3"}),c.jsx("circle",{cx:"6",cy:"12",r:"3"}),c.jsx("circle",{cx:"18",cy:"19",r:"3"}),c.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),c.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(Tt==="published"||Tt==="pending_review"||Tt==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${Tt==="published"?"bg-green-500":Tt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),Oe&&c.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:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),ot&&c.jsx("button",{onClick:Le,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:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?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?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{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:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${yu(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${yu(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${yu(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.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==="office"&&c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(U_,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{K.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const he=de?de.replace(/[/\\][^/\\]+$/,""):void 0,Xe=de&&!ic(de)?de:"",ge=x.format;return Xe&&(ge==="code"||ge==="json"||ge==="text")?c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(lS,{path:Xe,initialContent:x.content,language:zp(Xe,ge),onDirtyChange:J})}):Xe&&(ge==="markdown"||ge==="html")?c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(sM,{path:Xe,content:x.content,format:ge,basePath:he,onHtmlSelection:ke,onDirtyChange:J})}):c.jsx("div",{ref:Q,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(_u,{content:x.content,format:ge,className:"text-fg-secondary text-sm",onHtmlSelection:ke,basePath:he})})})(),x.mode==="artifact"&&c.jsx("div",{ref:Q,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(_u,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(oM,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(gM,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:q,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:he=>{if(!he||!i){$(null);return}$({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.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&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:Le,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}),c.jsx("button",{onClick:Le,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"})}),c.jsx("button",{onClick:be,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${S?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:S?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},I)]}),N&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:N.x,top:N.y-8},children:c.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),G(N.text,N.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&pt&&c.jsx(H_,{item:pt,onClose:()=>_(!1),onShared:qt})]})}const yM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook","session"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function SM(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of yM){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}const _M=k.lazy(()=>Ix(()=>import("./index-C-JeUF8o.js").then(s=>s.aH),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Zp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Ef(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function fS(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 pS={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function la(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function hx({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:h}=Lt(["agent","common"]),d=Af(),[u,f]=k.useState(null),[m,v]=k.useState(null),[b,g]=k.useState(r??"overview"),O=o&&l?l:b,[p,x]=k.useState(null),y=k.useMemo(()=>Zp.map($=>({...$,label:h(`agent:tabs.${$.key}`)})),[h]),S=k.useMemo(()=>y.map($=>({id:$.key})),[y]),w=k.useMemo(()=>({onSwipeOutLeft:i}),[i]),T=Mx(S,b,g,w),_=k.useRef(null);k.useEffect(()=>{const $=_.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[b]);const P=k.useCallback(()=>{K.agents.get(s).then(f).catch(()=>{})},[s]);if(k.useEffect(()=>(g(r??"overview"),x(null),P(),K.externalAgents.list().then(R=>{const D=R.agents.find(V=>V.markusAgentId===s);x(D??null)}).catch(()=>{}),yt.on("agent:update",R=>{R.payload.agentId===s&&P()})),[s,P]),!u)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:h("agent:profilePage.loadingAgent")});const L=pS[u.state.status]??"bg-gray-500",N=a?.role==="owner"||a?.role==="admin";return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&c.jsxs(c.Fragment,{children:[c.jsx(dx,{agent:u,onUpdate:P,externalInfo:p,t:h,canManageAgents:N}),c.jsx("div",{className:"mt-6",children:c.jsx(kx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:N,onAgentStateChange:P})})]}),O==="files"&&c.jsx(px,{agentId:s}),O==="tools"&&c.jsx(mx,{tools:u.tools??[],agent:u}),O==="memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Ox,{agentId:s,initialData:u.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(gx,{agentId:s})})]}),O==="deliverables"&&c.jsx(Cx,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(js,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:u.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:fS(u.state.status,h)}),p&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:h("agent:profilePage.badges.external")}),u.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:h("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.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:[c.jsx("span",{children:"◈"})," ",h("agent:profilePage.chat")]}),N&&c.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await K.agents.getFilesMap(s),R={type:"agent",name:Lx(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 Lf.publishViaProxy({itemType:"agent",name:u.name,description:R.description,category:"general",config:R,files:$}),v({title:h("agent:profilePage.hub"),message:h("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){v({title:h("agent:profilePage.hub"),message:h("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:h("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",h("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:_,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>c.jsxs("button",{onClick:()=>g($.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:[c.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?T.onTouchStart:void 0,onTouchEnd:d?T.onTouchEnd:void 0,children:[(b==="overview"||b==="mind")&&c.jsxs(c.Fragment,{children:[c.jsx(dx,{agent:u,onUpdate:P,externalInfo:p,t:h,canManageAgents:N}),c.jsx("div",{className:"mt-6",children:c.jsx(kx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:N,onAgentStateChange:P})})]}),b==="files"&&c.jsx(px,{agentId:s}),b==="tools"&&c.jsx(mx,{tools:u.tools??[],agent:u}),b==="memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Ox,{agentId:s,initialData:u.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(gx,{agentId:s})})]}),b==="deliverables"&&c.jsx(Cx,{agentId:s})]}),m&&c.jsx(So,{alertOnly:!0,variant:m.variant??"primary",title:m.title,message:m.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function dx({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i}){const[n,a]=k.useState(null),[o,l]=k.useState([]),[h,d]=k.useState(null),[u,f]=k.useState(null),[m,v]=k.useState(""),[b,g]=k.useState([]),[O,p]=k.useState(0);k.useEffect(()=>{K.usage.agents().then(P=>{const L=P.agents.find(N=>N.agentId===s.id);L&&a(L)}).catch(()=>{}),K.agents.getRecentActivities(s.id).then(P=>l(P.activities)).catch(()=>{}),K.system.storage().then(P=>{v(P.dataDir+"/agents/"+s.id);const L=P.agents.find(N=>N.id===s.id);L&&f(L)}).catch(()=>{}),s.state.activeTaskIds?.length&&K.tasks.list({assignedAgentId:s.id}).then(P=>{g(P.tasks.filter(L=>s.state.activeTaskIds?.includes(L.id)))}).catch(()=>{}),K.agents.getMailbox(s.id,{limit:1}).then(P=>{p(P.queued?.length??0)}).catch(()=>{})},[s.id,s.state.activeTaskIds,s.state.status]);const x=()=>{s.state.status==="offline"?K.agents.start(s.id).then(e):K.agents.stop(s.id).then(e)},y=k.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]),S=k.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(as,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:S.map(P=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:P.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:P.desc})]},P.field))})}),c.jsx(as,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:y.map(P=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${P.method==="POST"?"text-amber-600":"text-green-600"}`,children:P.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:P.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:P.desc})]},P.path))})})]});const w=o.filter(P=>P.type==="heartbeat").length,T=o.filter(P=>P.type==="chat").length,_=s.state.activeTaskIds?.length??0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${pS[s.state.status]||"bg-gray-500"}`}),c.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:fS(s.state.status,r)})]}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:la(s.state.tokensUsedToday)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(_),color:_>0?"blue":void 0}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),i&&c.jsx("button",{onClick:x,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:Cc(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(_>0||O>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),b.map(P=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:P.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Ef(P.status,r)})]},P.id)),O>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:O})})]})]})}),n&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/40"}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:la(n.totalTokens)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.promptTokens"),value:la(n.promptTokens)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.completionTokens"),value:la(n.completionTokens)})]})]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/40"}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.storage"),value:yx(u.size)}),u.subItems.filter(P=>P.size>0).map(P=>c.jsx(bs,{label:P.name,value:yx(P.size)},P.name)),c.jsxs("button",{onClick:()=>{K.system.openPath(m)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),w>0&&c.jsx(as,{title:r("agent:profilePage.overview.recentHeartbeats"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:w})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(P=>P.type==="heartbeat").map(P=>{const L=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(L?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s.id,activityId:P.id})})]},P.id)})})}),T>0&&c.jsx(as,{title:r("agent:profilePage.overview.recentA2A"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:T})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(P=>P.type==="chat").map(P=>{const L=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(L?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s.id,activityId:P.id})})]},P.id)})})})]})}function wM(s,e){const t=s.split(`
55
+ `)})},[i,s]);k.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),Xe=ge=>{if(!(he?ge.metaKey&&!ge.ctrlKey:ge.ctrlKey&&!ge.metaKey)||!ge.shiftKey||ge.altKey||ge.key.toLowerCase()!=="a")return;const Me=q.current?.getSelection()?.trim();Me&&(ge.preventDefault(),G(Me))};return window.addEventListener("keydown",Xe),()=>window.removeEventListener("keydown",Xe)},[s.kind,i,G]);const ke=k.useCallback(he=>{if(!he.text.trim()||!i)return;const Xe=Q.current?.querySelector("iframe")?.getBoundingClientRect(),ge=(Xe?.left??0)+he.rect.x+he.rect.width/2,Je=(Xe?.top??0)+he.rect.y;$({x:ge,y:Je,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);k.useEffect(()=>{const he=Q.current;if(!he||!i)return;const Xe=()=>{requestAnimationFrame(()=>{const Je=window.getSelection(),Me=Je?.toString().trim();if(!Me||!Je?.rangeCount){$(null);return}const bt=Je.getRangeAt(0);if(!he.contains(bt.commonAncestorContainer)){$(null);return}const at=bt.getBoundingClientRect();$({x:at.left+at.width/2,y:at.top,text:Me})})},ge=Je=>{const Me=document.getElementById("right-panel-selection-toolbar");Me&&Me.contains(Je.target)||$(null)};return he.addEventListener("mouseup",Xe),document.addEventListener("mousedown",ge),()=>{he.removeEventListener("mouseup",Xe),document.removeEventListener("mousedown",ge)}},[i,x.mode]);const Le=()=>{K.files.reveal(de).catch(()=>{})},be=()=>{navigator.clipboard?.writeText(de).then(()=>{w(!0),setTimeout(()=>w(!1),1500)}).catch(()=>{})},me=k.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 ge=await window.markusDesktop.browser.getState(s.browserId);if(ge.ok){if(ge.directoryPath){await K.system.openPath(ge.directoryPath).catch(()=>K.files.reveal(ge.directoryPath));return}ge.url&&ge.url!=="about:blank"&&(Xe=ge.url)}}catch{}if(!Xe||Xe==="about:blank")return;if(/^https?:\/\//i.test(Xe)||/^file:\/\//i.test(Xe)){$l(Xe);return}await K.system.openPath(Xe).catch(()=>$l(cx(Xe)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){$l(he);return}await K.system.openPath(he).catch(()=>$l(cx(he)))}},[s]),Oe=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"),ot=!!de&&!ic(de)&&(s.kind==="file"||s.kind==="deliverable"),Pt=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!de&&!ic(de)&&!s.deliverable.artifactType&&F_(s.deliverable.format),pt=s.kind==="deliverable"?{...s.deliverable,hubShareId:P?.id??s.deliverable.hubShareId??null,shareStatus:P?.status??s.deliverable.shareStatus??null,shareUrl:P?.url??s.deliverable.shareUrl??null,shareVisibility:P?.visibility??s.deliverable.shareVisibility??null}:null,qt=k.useCallback(he=>{L(he)},[]),wt=k.useMemo(()=>Y_(Im,Lf.getUrl()),[]),Rt=s.kind==="deliverable"?s.deliverable.id:null;k.useEffect(()=>{if(!Rt||!Im())return;let he=!1;const Xe=async()=>{try{const Je=await wt.listMine();if(he)return;const Me=s.kind==="deliverable"?s.deliverable:null;if(!Me)return;const bt=Me.hubShareId&&Je.find(ts=>ts.id===Me.hubShareId)||Je.find(ts=>ts.localId===Me.id);if(!bt)return;L(ts=>ts&&ts.id===bt.id&&ts.status===bt.status?ts:bt);const at={hubShareId:Me.hubShareId??bt.id??null,shareStatus:bt.status??null,shareUrl:bt.url??null,shareVisibility:Me.shareVisibility??bt.visibility??null};(Me.shareStatus!==at.shareStatus||Me.hubShareId!==at.hubShareId||Me.shareUrl!==at.shareUrl||Me.shareVisibility!==at.shareVisibility)&&Me.id&&K.deliverables.update(Me.id,at).catch(ts=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ts)})}catch{}};Xe();const ge=setInterval(Xe,3e4);return()=>{he=!0,clearInterval(ge)}},[wt,Rt,s]);const Tt=pt?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:p("common:browserMode",{defaultValue:"Browser"}),"aria-label":p("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":m==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${m==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:p("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":p("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":m==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${m==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),U||h?c.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,ge=he.payload.kind==="url"?he.payload.pageId:void 0,Je=he.payload.kind==="terminal"?he.payload.terminalId:void 0,Me=ge!=null?R[ge]:Je?V[Je]:void 0,bt=Me?`${he.title} — ${p("common:browserTabControlledBy",{name:Me.agentName})}`:he.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${Xe?Me?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":Me?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":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:at=>{at.button===0&&(he.id!==a&&!te()||o?.(he.id))},onClick:()=>{he.id!==a&&!te()||o?.(he.id)},children:[Me&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:p("common:browserTabControlledBy",{name:Me.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:Me.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:at=>{at.button===0&&(at.preventDefault(),at.stopPropagation(),!(he.id===a&&!te())&&l(he.id))},onClick:at=>{at.preventDefault(),at.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:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:p("common:newTab",{defaultValue:"New Tab"}),"aria-label":p("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:de||we,children:we}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[s.kind==="terminal"&&i&&c.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:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),Pt&&c.jsxs("button",{type:"button",onClick:()=>_(!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 ${Tt==="published"?"text-green-500 hover:text-green-400":Tt==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"18",cy:"5",r:"3"}),c.jsx("circle",{cx:"6",cy:"12",r:"3"}),c.jsx("circle",{cx:"18",cy:"19",r:"3"}),c.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),c.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(Tt==="published"||Tt==="pending_review"||Tt==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${Tt==="published"?"bg-green-500":Tt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),Oe&&c.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:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),ot&&c.jsx("button",{onClick:Le,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:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?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?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{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:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${yu(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${yu(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${yu(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.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==="office"&&c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(U_,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{K.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const he=de?de.replace(/[/\\][^/\\]+$/,""):void 0,Xe=de&&!ic(de)?de:"",ge=x.format;return Xe&&(ge==="code"||ge==="json"||ge==="text")?c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(lS,{path:Xe,initialContent:x.content,language:zp(Xe,ge),onDirtyChange:J})}):Xe&&(ge==="markdown"||ge==="html")?c.jsx("div",{ref:Q,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(sM,{path:Xe,content:x.content,format:ge,basePath:he,onHtmlSelection:ke,onDirtyChange:J})}):c.jsx("div",{ref:Q,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(_u,{content:x.content,format:ge,className:"text-fg-secondary text-sm",onHtmlSelection:ke,basePath:he})})})(),x.mode==="artifact"&&c.jsx("div",{ref:Q,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(_u,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(oM,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(gM,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:q,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:he=>{if(!he||!i){$(null);return}$({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.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&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:Le,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}),c.jsx("button",{onClick:Le,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"})}),c.jsx("button",{onClick:be,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${S?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:S?p("common:copied",{defaultValue:"Copied"}):p("common:copy",{defaultValue:"Copy"})})]})]})]},I)]}),N&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:N.x,top:N.y-8},children:c.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),G(N.text,N.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),p("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&pt&&c.jsx(H_,{item:pt,onClose:()=>_(!1),onShared:qt})]})}const yM=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook","session"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function SM(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of yM){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}const _M=k.lazy(()=>Ix(()=>import("./index-ByDm2R2Q.js").then(s=>s.aH),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Zp=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Ef(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function fS(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 pS={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function la(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function hx({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l}){const{t:h}=Lt(["agent","common"]),d=Af(),[u,f]=k.useState(null),[m,v]=k.useState(null),[b,g]=k.useState(r??"overview"),O=o&&l?l:b,[p,x]=k.useState(null),y=k.useMemo(()=>Zp.map($=>({...$,label:h(`agent:tabs.${$.key}`)})),[h]),S=k.useMemo(()=>y.map($=>({id:$.key})),[y]),w=k.useMemo(()=>({onSwipeOutLeft:i}),[i]),T=Mx(S,b,g,w),_=k.useRef(null);k.useEffect(()=>{const $=_.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[b]);const P=k.useCallback(()=>{K.agents.get(s).then(f).catch(()=>{})},[s]);if(k.useEffect(()=>(g(r??"overview"),x(null),P(),K.externalAgents.list().then(R=>{const D=R.agents.find(V=>V.markusAgentId===s);x(D??null)}).catch(()=>{}),yt.on("agent:update",R=>{R.payload.agentId===s&&P()})),[s,P]),!u)return c.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:h("agent:profilePage.loadingAgent")});const L=pS[u.state.status]??"bg-gray-500",N=a?.role==="owner"||a?.role==="admin";return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[(O==="overview"||O==="mind")&&c.jsxs(c.Fragment,{children:[c.jsx(dx,{agent:u,onUpdate:P,externalInfo:p,t:h,canManageAgents:N}),c.jsx("div",{className:"mt-6",children:c.jsx(kx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:N,onAgentStateChange:P})})]}),O==="files"&&c.jsx(px,{agentId:s}),O==="tools"&&c.jsx(mx,{tools:u.tools??[],agent:u}),O==="memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Ox,{agentId:s,initialData:u.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(gx,{agentId:s})})]}),O==="deliverables"&&c.jsx(Cx,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(js,{name:u.name,avatarUrl:u.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:u.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:fS(u.state.status,h)}),p&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:h("agent:profilePage.badges.external")}),u.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:h("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[u.role,u.roleDescription?` — ${u.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.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:[c.jsx("span",{children:"◈"})," ",h("agent:profilePage.chat")]}),N&&c.jsxs("button",{onClick:async()=>{if(u)try{const{filesMap:$}=await K.agents.getFilesMap(s),R={type:"agent",name:Lx(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 Lf.publishViaProxy({itemType:"agent",name:u.name,description:R.description,category:"general",config:R,files:$}),v({title:h("agent:profilePage.hub"),message:h("agent:profilePage.publishSuccess",{name:u.name}),variant:"primary"})}catch($){v({title:h("agent:profilePage.hub"),message:h("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:h("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",h("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:_,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:y.filter($=>!p||["overview","mind"].includes($.key)).map($=>c.jsxs("button",{onClick:()=>g($.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:[c.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?T.onTouchStart:void 0,onTouchEnd:d?T.onTouchEnd:void 0,children:[(b==="overview"||b==="mind")&&c.jsxs(c.Fragment,{children:[c.jsx(dx,{agent:u,onUpdate:P,externalInfo:p,t:h,canManageAgents:N}),c.jsx("div",{className:"mt-6",children:c.jsx(kx,{agentId:s,highlightId:n,agentStatus:u.state.status,canManageAgents:N,onAgentStateChange:P})})]}),b==="files"&&c.jsx(px,{agentId:s}),b==="tools"&&c.jsx(mx,{tools:u.tools??[],agent:u}),b==="memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Ox,{agentId:s,initialData:u.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(gx,{agentId:s})})]}),b==="deliverables"&&c.jsx(Cx,{agentId:s})]}),m&&c.jsx(So,{alertOnly:!0,variant:m.variant??"primary",title:m.title,message:m.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function dx({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i}){const[n,a]=k.useState(null),[o,l]=k.useState([]),[h,d]=k.useState(null),[u,f]=k.useState(null),[m,v]=k.useState(""),[b,g]=k.useState([]),[O,p]=k.useState(0);k.useEffect(()=>{K.usage.agents().then(P=>{const L=P.agents.find(N=>N.agentId===s.id);L&&a(L)}).catch(()=>{}),K.agents.getRecentActivities(s.id).then(P=>l(P.activities)).catch(()=>{}),K.system.storage().then(P=>{v(P.dataDir+"/agents/"+s.id);const L=P.agents.find(N=>N.id===s.id);L&&f(L)}).catch(()=>{}),s.state.activeTaskIds?.length&&K.tasks.list({assignedAgentId:s.id}).then(P=>{g(P.tasks.filter(L=>s.state.activeTaskIds?.includes(L.id)))}).catch(()=>{}),K.agents.getMailbox(s.id,{limit:1}).then(P=>{p(P.queued?.length??0)}).catch(()=>{})},[s.id,s.state.activeTaskIds,s.state.status]);const x=()=>{s.state.status==="offline"?K.agents.start(s.id).then(e):K.agents.stop(s.id).then(e)},y=k.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]),S=k.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(as,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(as,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:S.map(P=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:P.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:P.desc})]},P.field))})}),c.jsx(as,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:y.map(P=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${P.method==="POST"?"text-amber-600":"text-green-600"}`,children:P.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:P.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:P.desc})]},P.path))})})]});const w=o.filter(P=>P.type==="heartbeat").length,T=o.filter(P=>P.type==="chat").length,_=s.state.activeTaskIds?.length??0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ds,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Ds,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${pS[s.state.status]||"bg-gray-500"}`}),c.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:fS(s.state.status,r)})]}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.tokensToday"),value:la(s.state.tokensUsedToday)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(_),color:_>0?"blue":void 0}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:s.state.lastHeartbeat?new Date(s.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),i&&c.jsx("button",{onClick:x,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:Cc(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(_>0||O>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),b.map(P=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:P.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Ef(P.status,r)})]},P.id)),O>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:O})})]})]})}),n&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/40"}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.labels.totalTokens"),value:la(n.totalTokens)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.requests"),value:String(n.requestCount)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(n.toolCalls)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.promptTokens"),value:la(n.promptTokens)}),c.jsx(bs,{label:r("agent:profilePage.overview.labels.completionTokens"),value:la(n.completionTokens)})]})]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/40"}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(bs,{label:r("agent:profilePage.overview.storage"),value:yx(u.size)}),u.subItems.filter(P=>P.size>0).map(P=>c.jsx(bs,{label:P.name,value:yx(P.size)},P.name)),c.jsxs("button",{onClick:()=>{K.system.openPath(m)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),w>0&&c.jsx(as,{title:r("agent:profilePage.overview.recentHeartbeats"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:w})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(P=>P.type==="heartbeat").map(P=>{const L=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(L?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s.id,activityId:P.id})})]},P.id)})})}),T>0&&c.jsx(as,{title:r("agent:profilePage.overview.recentA2A"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:T})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:o.filter(P=>P.type==="chat").map(P=>{const L=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(L?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s.id,activityId:P.id})})]},P.id)})})})]})}function wM(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 m=n-1;m>=0;m--)a[f][m]=t[f]===r[m]?a[f+1][m+1]+1:Math.max(a[f+1][m],a[f][m+1]);const o=[];let l=0,h=0,d=1,u=1;for(;l<i||h<n;)l<i&&h<n&&t[l]===r[h]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,h++):h<n&&(l>=i||a[l][h+1]>=a[l+1][h])?(o.push({type:"add",content:r[h],lineNum:u++}),h++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function ux(s){return s.match(/\S+|\s+/g)??[""]}function fx({oldText:s,newText:e,mode:t}){const r=ux(s),i=ux(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=r[u]===i[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let h=0,d=0;for(;h<n||d<a;)h<n&&d<a&&r[h]===i[d]?(l.push({text:t==="remove"?r[h]:i[d],changed:!1}),h++,d++):d<a&&(h>=n||o[h][d+1]>=o[h+1][d])?(t==="add"&&l.push({text:i[d],changed:!0}),d++):(t==="remove"&&l.push({text:r[h],changed:!0}),h++);return c.jsx("span",{children:l.map((u,f)=>u.changed?c.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):c.jsx("span",{children:u.text},f))})}function kM({agent:s,template:e,templateId:t}){const{t:r}=Lt(["agent","common"]),i=k.useMemo(()=>wM(s,e),[s,e]),[n,a]=k.useState(!0),o=3,l=k.useMemo(()=>{const m=i.map((O,p)=>O.type!=="equal"?p:-1).filter(O=>O>=0);if(m.length===0)return[];const v=[];let b=Math.max(0,m[0]-o),g=Math.min(i.length-1,m[0]+o);for(let O=1;O<m.length;O++){const p=Math.max(0,m[O]-o),x=Math.min(i.length-1,m[O]+o);p<=g+1||(v.push({start:b,end:g}),b=p),g=x}return v.push({start:b,end:g}),v},[i]),h=(m,v,b)=>{const g=m.type==="add"?"+":m.type==="remove"?"-":" ",O=m.type==="add"?"bg-green-500/8":m.type==="remove"?"bg-red-500/8":"",p=m.type==="add"?"text-green-600/90":m.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=m.type==="add"?"text-green-500":m.type==="remove"?"text-red-500":"text-fg-muted",y=m.type==="remove"?m.oldLineNum:m.lineNum;let S=null;return m.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?S=c.jsx(fx,{oldText:m.content,newText:b[v+1].content,mode:"remove"}):m.type==="add"&&v>0&&b[v-1].type==="remove"&&(S=c.jsx(fx,{oldText:b[v-1].content,newText:m.content,mode:"add"})),c.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[c.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),c.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:g}),c.jsxs("span",{className:`flex-1 text-[11px] font-mono ${p} whitespace-pre-wrap break-words leading-[20px]`,children:[S??m.content,m.content===""&&" "]})]},v)},d=i.filter(m=>m.type==="add").length,u=i.filter(m=>m.type==="remove").length,f=n?l.flatMap(m=>{const v=[];for(let b=m.start;b<=m.end;b++)v.push({...i[b],_idx:b});return v}):i.map((m,v)=>({...m,_idx:v}));return c.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),c.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),c.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),c.jsx("button",{onClick:()=>a(m=>!m),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),c.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((m,v)=>{const b=v>0?f[v-1]:null,g=n&&b&&m._idx-b._idx>1;return c.jsxs("div",{children:[g&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),h(m,m._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function CM(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:Q})},N=async Z=>{if(y?.file===Z){S(null);return}try{const z=await K.agents.roleDiff(s,Z);z.agentContent!=null&&z.templateContent!=null&&S({file:Z,agent:z.agentContent,template:z.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},R=Z=>{const z=$[Z];return z?e(`agent:profilePage.filesTab.fileLabels.${z}`):Z},D=p?.hasTemplate&&!p.isUpToDate,V=a?P.some(Z=>Z.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[D&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:P.length,templateId:p.templateId})," ",P.map(Z=>Z.file).join(", ")]})]}),c.jsx("button",{onClick:()=>L(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(as,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(Z=>{const z=P.some(J=>J.file===Z.name);return c.jsxs("button",{onClick:()=>T(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&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:R(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[V&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),m(!0),setTimeout(()=>m(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{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&&c.jsx(kM,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),c.jsx(PM,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{h(Z),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(oh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function PM({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=k.useState(!1),o=k.useRef(null);return k.useEffect(()=>{n&&o.current?.focus()},[n]),k.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(k.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_M,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function TM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function QM({tools:s}){const{t:e}=Lt(["agent","common"]),t=SM(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(as,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=k_(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=TM(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(C_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function $M({agent:s}){const{t:e}=Lt(["agent","common"]),t=s.proficiency??{},[r,i]=k.useState(null),[n,a]=k.useState(null),[o,l]=k.useState(!1),h=s.availableSkills??[],d=new Map;for(const g of h){const O=g.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(g)}const u=async g=>{if(r===g){i(null),a(null);return}i(g),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(g)}`);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"},m=g=>{const O=t[g.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&c.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===g.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(g.name),children:[c.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:g.name}),g.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),g.builtIn&&!g.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!g.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:g.description}),x]}),p!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(S=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:S},S))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(S=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",S]},S))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(S=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:S.name}),S.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:S.description})]},S.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},g.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],b=[...d.entries()].sort((g,O)=>{const p=v.indexOf(g[0]),x=v.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),b.map(([g,O])=>c.jsx(as,{title:c.jsxs("span",{className:"capitalize",children:[g," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:O.map(p=>m(p))})},g)),h.length===0&&c.jsx(oh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function mx({tools:s,agent:e}){const{t}=Lt(["agent","common"]),[r,i]=k.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(QM,{tools:s}):c.jsx($M,{agent:e})]})}function gx({agentId:s}){const{t:e}=Lt(["agent","common"]),[t,r]=k.useState(null),[i,n]=k.useState(!0),[a,o]=k.useState("longterm"),[l,h]=k.useState(""),[d,u]=k.useState(""),[f,m]=k.useState(!1),[v,b]=k.useState(null),[g,O]=k.useState(null),[p,x]=k.useState([]),[y,S]=k.useState(!1),w=k.useCallback(()=>{n(!0),K.agents.getMemory(s).then($=>{r($),h($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);k.useEffect(()=>{w()},[w]);const T=async()=>{m(!0),await K.agents.updateDailyMemory(s,l).catch(()=>{}),m(!1),w()},_=async()=>{m(!0),await K.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),m(!1),w()},P=l!==(t?.recentDailyLogs??""),L=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const N=[{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 c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex gap-2",children:N.map($=>c.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"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(oh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,R)=>{const D=v===R;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(D?null:R),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.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}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${D?"":"line-clamp-2"}`,children:$.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&c.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]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:D?"▲":"▼"})]})]}),D&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),c.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},R)})})}),a==="sessions"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(oh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const R=g===$.id,D=async()=>{if(R){O(null),x([]);return}O($.id),S(!0);try{const V=await K.agents.getMemorySession(s,$.id);x(V.messages)}catch{x([])}S(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:D,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:R?"▲":"▼"})]}),R&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?c.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 c.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(Z=>Z.role!=="tool").map((Z,z)=>c.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(xa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[Z.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(xa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(J=>{let Q;try{Q=JSON.parse(J.arguments)}catch{}const A={tool:J.name,status:"done",args:Q,result:V.get(J.id)};return c.jsx(v_,{entry:{type:"tool",info:A}},J.id)})})]})]},z))})})()})]},$.id)})})}),a==="daily"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:P?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:T,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:$=>h($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:L?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:$=>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 Ox({agentId:s,initialData:e}){const{t}=Lt(["agent","common"]),[r,i]=k.useState(e??null),[n,a]=k.useState(!e),[o,l]=k.useState([]),[h,d]=k.useState(null),[u,f]=k.useState(!1),[m,v]=k.useState(null),b=k.useCallback(()=>Promise.all([K.agents.getHeartbeat(s).then(i).catch(()=>{}),K.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(S=>S.type==="heartbeat"))}).catch(()=>{})]),[s]);k.useEffect(()=>{a(!0),b().finally(()=>a(!1))},[b]),k.useEffect(()=>yt.on("agent:update",S=>{S.payload?.agentId===s&&b()}),[s,b]);const g=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 c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=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 S=Date.now()-new Date(y).getTime();if(S<0){const w=Math.abs(S);return w<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(w/1e3)}):w<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(w/6e4)}):t("agent:profilePage.relative.inHours",{hours:(w/36e5).toFixed(1)})}return S<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(S/1e3)}):S<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(S/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(S/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(as,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:b,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:g,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(bs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(EM,{agentId:s,intervalMs:r.intervalMs,onChanged:b}),c.jsx(bs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?x(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(bs,{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")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),m&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:m})]}),r.wakeups&&r.wakeups.length>0&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(y=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.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")}`]})]}),c.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&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(y=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),c.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&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx(xa,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const S=h===y.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(S?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:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${S?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),S&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s,activityId:y.id})})]},y.id)})})}):r.lastHeartbeat?null:c.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:g,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 jM({taskId:s,isLive:e}){const{t}=Lt("agent"),[r,i]=k.useState([]),[n,a]=k.useState(""),[o,l]=k.useState(!0),[h,d]=k.useState("compact");if(k.useEffect(()=>{l(!0),a(""),K.tasks.getLogs(s).then(m=>{i(m.logs),l(!1)}).catch(()=>l(!1))},[s]),k.useEffect(()=>{if(!e)return;const m=yt.on("task:log",b=>{const g=b.payload;if(g.taskId!==s)return;const O={id:g.id,taskId:g.taskId,agentId:g.agentId,seq:g.seq,type:g.logType,content:g.content,metadata:g.metadata,createdAt:g.createdAt};i(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 g=b.payload;g.taskId===s&&a(O=>O+g.text)});return()=>{m(),v()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(m=>w_(m)),f=new Set(u.filter(m=>m.executionRound!=null).map(m=>m.executionRound)).size>1;return c.jsx("div",{className:"px-3 py-2",children:h==="compact"?c.jsx(Nx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):c.jsx(Dx,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function qa({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Lt("agent"),[i,n]=k.useState([]),[a,o]=k.useState(!0),[l,h]=k.useState("compact");if(k.useEffect(()=>{o(!0),K.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),k.useEffect(()=>t?yt.on("agent:activity_log",f=>{const m=f.payload;if(m.agentId!==s||m.activityId!==e)return;const v={seq:m.seq,type:m.type,content:m.content,metadata:m.metadata,createdAt:m.createdAt};n(b=>b.some(g=>g.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>__(u,e,s)).filter(u=>u!==null);return c.jsx("div",{className:"px-3 py-2",children:l==="compact"?c.jsx(Nx,{entries:d,isActive:t,onExpand:()=>h("full")}):c.jsx(Dx,{entries:d,isActive:t,onCollapse:()=>h("compact")})})}function as({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Ds({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function bs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const xx=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],bx=5,vx=1440;function EM({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Lt(["agent","common"]),[i,n]=k.useState(!1),[a,o]=k.useState(null),[l,h]=k.useState(!1),[d,u]=k.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)}),m=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"){h(!0);return}h(!1),m(Number(p.target.value))},b=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<bx||p>vx){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}m(p*60*1e3)},g=xx.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),xx.map(p=>c.jsx("option",{value:String(p),children:f(p)},p)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:bx,max:vx,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"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function oh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function yx(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 Sx={0:"0",1:"1",2:"2",3:"3",4:"4"},_x={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},RM={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"},AM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},nc={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:"🧠"},MM=["all","interaction","task","notification","system"],LM={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"]},NM={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"},DM={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 Su(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 wx(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=Ef(d,e),m=Ef(u,e),v=DM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:m}),badge:{label:m,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=Su(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=Su(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=Su(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 kx({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r,onAgentStateChange:i}){const{t:n}=Lt(["agent","common","team"]),[a,o]=k.useState(null),[l,h]=k.useState(null),[d,u]=k.useState(!0),[f,m]=k.useState("all"),[v,b]=k.useState("all"),[g,O]=k.useState(e??null),[p,x]=k.useState(e??null),[y,S]=k.useState(!1),[w,T]=k.useState(!0),[_,P]=k.useState(null),L=50,N=3,$=k.useCallback(async(Q=!0)=>{Q&&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:L,category:A,status:B})]);o(q),h(H),T((H.history?.length??0)>=L)}catch{}u(!1)},[s,f,v]),R=k.useCallback(async()=>{if(!l)return;const Q=f==="all"?void 0:f,A=v==="all"?void 0:v;try{const B=await K.agents.getMailbox(s,{limit:L,offset:l.history.length,category:Q,status:A});h(q=>q?{...q,history:[...q.history,...B.history]}:B),T((B.history?.length??0)>=L)}catch{}},[s,l,f,v]);k.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const D=k.useRef(!1);if(k.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){D.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 w&&!D.current&&(D.current=!0,(async()=>{let A=l?.history??[],B=w;for(;B;)try{const q=await K.agents.getMailbox(s,{limit:L,offset:A.length}),H=[...A,...q.history];A=H,B=(q.history?.length??0)>=L;const te=q.history.some(de=>de.id===p);if(h(de=>de?{...de,history:H}:q),T(B),te||!B)break}catch{break}D.current=!1})())},[p,d,l,w,s]),k.useEffect(()=>{let Q=null;const A=q=>{q.payload?.agentId===s&&(Q&&clearTimeout(Q),Q=setTimeout(()=>{Q=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()=>{Q&&clearTimeout(Q),B.forEach(q=>q())}},[s,$]),d&&!a)return c.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 Q=a?.attentionState??"idle";return Q==="deciding"||Q==="idle"&&V>0?"deciding":Q!=="idle"&&!a?.currentFocus?"idle":Q})(),z=Z==="idle"&&l?.history?.some(Q=>Q.status==="processing"),J=(a?.attentionState??"idle")==="idle"&&V>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${AM[Z]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${Z}`)}),a?.currentFocus?(()=>{const Q=wx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[nc[a.currentFocus.type]??"●"," ",c.jsx("span",{className:"text-fg-primary font-medium",children:Q.title}),Q.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:Q.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>P(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?c.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"?c.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:V})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),c.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&t==="offline"&&c.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")&&c.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")]}),c.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&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const Q=a.queuedItems,A=Q.length>N,B=A&&!y?Q.slice(0,N):Q,q=Q.reduce((H,te)=>(H[te.sourceType]=(H[te.sourceType]??0)+1,H),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:Q.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(q).map(([H,te])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[nc[H]??"●"," ",te]},H))})]}),c.jsxs("div",{className:"space-y-1",children:[B.map((H,te)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:te+1}),c.jsx("span",{className:"text-sm",children:nc[H.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${_x[H.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${Sx[H.priority]??H.priority}`,{defaultValue:`P${H.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:H.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(H.queuedAt).toLocaleTimeString()})]},H.id)),A&&c.jsx("button",{onClick:()=>S(!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:Q.length-N})})]})]})})()]}),(a?.notebook?.length??0)>0&&c.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{open:!0,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),c.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),c.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(Q=>{const A=Date.now()-Q.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=Q.managed==="system"?"text-blue-400":Q.managed==="cpp"?"text-purple-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:Q.key}),c.jsxs("span",{className:`text-[10px] ${q}`,children:["[",Q.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:B})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:Q.text.length>500?Q.text.slice(0,500)+"…":Q.text})]},Q.key)})})]})}),a?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(qa,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!A,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&c.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&&c.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&&c.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})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:MM.map(Q=>{const A=l?.sourceTypeCounts,B=Q==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?(LM[Q]??[]).reduce((q,H)=>q+(A[H]??0),0):void 0;return c.jsxs("button",{onClick:()=>m(Q),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===Q?"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.${Q}`),B!=null&&B>0&&c.jsx("span",{className:"ml-1 opacity-60",children:B})]},Q)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(Q=>{const A=l?.statusCounts,B=Q.key==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?.[Q.key];return c.jsxs("button",{onClick:()=>b(Q.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===Q.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:[Q.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Q.dot}`}),n(`agent:profilePage.mind.statusFilters.${Q.key}`),B!=null&&B>0&&c.jsx("span",{className:"ml-1 opacity-60",children:B})]},Q.key)})}),(!l?.history||l.history.length===0)&&!d&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:l?.history?.map(Q=>{const A=g===Q.id,B=nc[Q.sourceType]??"●",q=wx(Q,n),H=Q.metadata?.senderName,te=Q.metadata?.senderRole,de=p===Q.id;return c.jsxs("div",{id:`mbx-${Q.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${de?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>O(A?null:Q.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${NM[Q.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:B}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:q.title}),q.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${q.badge.color}`,children:q.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${_x[Q.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${Sx[Q.priority]??Q.priority}`,{defaultValue:""})})]}),q.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:q.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(Q.queuedAt).toLocaleString()}),Q.completedAt&&c.jsxs("span",{children:["→ ",new Date(Q.completedAt).toLocaleTimeString()]}),Q.activity&&c.jsxs(c.Fragment,{children:[Q.activity.totalTokens>0&&c.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:la(Q.activity.totalTokens)})}),Q.activity.totalTools>0&&c.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:Q.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:Q.sourceType}),r&&Q.status==="processing"&&c.jsxs("button",{onClick:we=>{we.stopPropagation(),P(Q.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&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[H&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:H}),te&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",te,")"]})]}),Q.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(Q.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:Q.payload.content}),Q.decisions&&Q.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:Q.decisions.map(we=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${RM[we.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:we.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:we.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(we.createdAt).toLocaleTimeString()})]},we.id))})]}),Q.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:Q.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${Q.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:Q.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),Q.activity.type==="task"&&Q.payload?.taskId?c.jsx(jM,{taskId:Q.payload.taskId,isLive:!Q.activity.endedAt}):c.jsx(qa,{agentId:s,activityId:Q.activity.id,isLive:!Q.activity.endedAt})]}):Q.status==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):Q.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},Q.id)})}),w&&(l?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:R,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),_&&c.jsx(So,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{P(null),K.agents.cancelProcessing(s).then(()=>{let Q=0;const A=()=>{Q+=1,$(),Q<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>P(null)})]})}function Cx({agentId:s}){const{t:e}=Lt(["agent","common"]),t=ah(),[r,i]=k.useState([]),[n,a]=k.useState(!0),[o,l]=k.useState(null),h=k.useCallback(u=>{t?.openRightPanel?t.openRightPanel({kind:"deliverable",deliverable:u}):l(u)},[t]),d=k.useCallback(async()=>{a(!0);try{const{results:u}=await K.deliverables.search({agentId:s,limit:200});i(u)}catch{i([])}a(!1)},[s]);return k.useEffect(()=>{d()},[d]),k.useEffect(()=>{const u=yt.on("deliverable:created",()=>d()),f=yt.on("deliverable:updated",()=>d()),m=yt.on("deliverable:removed",()=>d());return()=>{u(),f(),m()}},[d]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(u=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},u))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(u=>{const f=y_[u.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},m=Bm[u.status]??Bm.active;return c.jsxs("button",{onClick:()=>h(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:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${f.color}`,children:f.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:u.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${m.color}`,children:u.status})]}),u.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:u.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(u.createdAt).toLocaleDateString()}),u.tags.length>0&&c.jsx("span",{children:u.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},u.id)})]}),o&&c.jsx(S_,{item:o,onClose:()=>l(null),onOpenInPage:u=>{l(null),Qr.navigate(Kt.DELIVERABLES,{openDeliverable:u})}})]})}const IM=k.lazy(()=>Ix(()=>import("./index-C-JeUF8o.js").then(s=>s.aH),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Vp=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Px={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Tx({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Lt("team"),[o,l]=k.useState(null),[h,d]=k.useState(null),[u,f]=k.useState("overview"),m=r&&i?i:u,[v,b]=k.useState(""),[g,O]=k.useState(""),[p,x]=k.useState(!1),[y,S]=k.useState(!1),[w,T]=k.useState(""),[_,P]=k.useState(""),L=k.useRef(null),N=k.useRef(null),$=k.useRef(null),R=k.useRef(null),[D,V]=k.useState(!1),[Z,z]=k.useState(!1),[J,Q]=k.useState(""),[A,B]=k.useState(""),[q,H]=k.useState(!1),[te,de]=k.useState([]),we=k.useRef(null),U=k.useCallback(async()=>{try{const Oe=(await K.teams.list()).teams.find(ot=>ot.id===s);Oe&&l(Oe);const He=await K.teams.status(s);de(He.agents)}catch{}},[s]),I=k.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]);k.useEffect(()=>{f("overview"),U(),I()},[s,U,I]),k.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),k.useEffect(()=>{y&&R.current&&R.current.focus()},[y]);const se=async(me,Oe)=>{V(!0);try{await K.teams.updateFile(s,me,Oe),me==="ANNOUNCEMENT.md"?(b(Oe),x(!1)):(O(Oe),S(!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 c.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"),ke=te.filter(me=>me.status!=="offline").length,Le=m==="announcements"&&p||m==="norms"&&y;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Le?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Le?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[m==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const Oe=te.find(Pt=>Pt.id===me.id),He=Px[Oe?.status??"offline"]??"bg-gray-500",ot=me.type==="agent";return c.jsxs("div",{onClick:()=>ot&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ot&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:me.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Oe?.status??"offline"}),me.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),ot&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),m==="announcements"&&c.jsx(oc,{content:v,draft:w,setDraft:T,editing:p,setEditing:x,textareaRef:N,contentRef:L,saving:D,onSave:()=>se("ANNOUNCEMENT.md",w),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),m==="norms"&&c.jsx(oc,{content:g,draft:_,setDraft:P,editing:y,setEditing:S,textareaRef:R,contentRef:$,saving:D,onSave:()=>se("NORMS.md",_),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),m==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:we,value:J,onChange:me=>Q(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}),c.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"}),c.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{Q(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?c.jsxs("div",{className:"space-y-2",children:[c.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}),c.jsxs("div",{className:"flex gap-2",children:[c.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"}),c.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"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Qx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const be=u==="announcements"&&p||u==="norms"&&y;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${be?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[ke," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:me}=await K.teams.getFilesMap(o.id),Oe=o.members.filter(ot=>ot.type==="agent"),He={type:"team",name:Lx(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Oe.map(ot=>({name:ot.name,roleName:ot.role,role:ot.agentRole??"worker",count:1,skills:[]}))}};await Lf.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:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Vp.map(me=>c.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))})]}),c.jsxs("div",{className:`${be?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const Oe=te.find(Pt=>Pt.id===me.id),He=Px[Oe?.status??"offline"]??"bg-gray-500",ot=me.type==="agent";return c.jsxs("div",{onClick:()=>ot&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ot&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:me.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Oe?.status??"offline"}),me.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),ot&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&c.jsx(oc,{content:v,draft:w,setDraft:T,editing:p,setEditing:x,textareaRef:N,contentRef:L,saving:D,onSave:()=>se("ANNOUNCEMENT.md",w),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&c.jsx(oc,{content:g,draft:_,setDraft:P,editing:y,setEditing:S,textareaRef:R,contentRef:$,saving:D,onSave:()=>se("NORMS.md",_),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:we,value:J,onChange:me=>Q(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}),c.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"}),c.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{Q(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?c.jsxs("div",{className:"space-y-2",children:[c.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}),c.jsxs("div",{className:"flex gap-2",children:[c.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"}),c.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"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Qx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),h&&c.jsx(So,{alertOnly:!0,variant:h.variant??"primary",title:h.title,message:h.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function oc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?c.jsx(k.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(IM,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Qx({teamId:s,teamName:e,onDeleted:t}){const[r,i]=k.useState(!1),[n,a]=k.useState(!1),[o,l]=k.useState(!1),[h,d]=k.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await 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:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function ac(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 h=this.mergeDbWithCache(r,n?i:void 0);return this.msgBuffers.set(e,h),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:h}}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,h)=>l+h.text.length,0),n=t.reduce((l,h)=>l+h.text.length,0);if(i>n)return!0;const a=r.reduce((l,h)=>l+(h.segments?.length??0),0),o=t.reduce((l,h)=>l+(h.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 kt=bi.NEW_CHAT_ID;function BM(s){const e=k.useRef(new bi),[t,r]=k.useState(s??[]),[i,n]=k.useState(!1),[a,o]=k.useState([]),l=k.useRef(null);k.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const h=k.useCallback((p,x,y)=>{const S=e.current.updateMessages(p,x,y);S.displayChanged&&S.newMessages&&r(S.newMessages)},[]),d=k.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const w=e.current.getMessages(p);w&&e.current.currentConvKey===p&&r([...w])}))},[]),u=k.useCallback((p,x,y)=>{const S=e.current.appendActivity(p,x,y);S.displayChanged&&S.newActivities&&o(S.newActivities)},[]),f=k.useCallback(p=>e.current.getPhase(p),[]),m=k.useCallback(p=>e.current.beginLoad(p),[]),v=k.useCallback(p=>e.current.beginStream(p),[]),b=k.useCallback(p=>e.current.endStream(p),[]),g=k.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=k.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const S=await y(),w=e.current.applyLoadResult(x,p,S.messages);return w.displayChanged&&w.newMessages&&r(w.newMessages),{count:S.messages.length,hasMore:S.hasMore,oldestCursor:S.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:h,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:m,beginStream:v,endStream:b,resetConv:g,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 WM({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Lt("team"),[n,a]=k.useState(!1),[o,l]=k.useState("agent"),[h,d]=k.useState(""),[u,f]=k.useState(!1),[m,v]=k.useState([]),[b,g]=k.useState(null),O=k.useRef(null),p=k.useCallback(async()=>{f(!0);try{const _=await fetch("/api/settings/llm",{credentials:"include"});if(!_.ok)throw new Error(`HTTP ${_.status}`);const P=await _.json(),L=P.providers?.markus;if(L?.configured&&L.enabled!==!1&&(!L.models||L.models.length===0))try{const D=await fetch("/api/models/live/markus",{credentials:"include"});if(D.ok){const V=await D.json();V.models?.length&&(L.models=V.models)}}catch{}const N=[];for(const[D,V]of Object.entries(P.providers??{})){if(!V.configured||V.enabled===!1)continue;const Z=(V.models??[]).map(z=>({id:z.id,name:z.name}));Z.length!==0&&N.push({provider:D,displayName:V.displayName??D,models:Z})}N.sort((D,V)=>D.displayName.localeCompare(V.displayName)),v(N);const $=D=>!D?.provider||!D.model?!1:!!N.find(Z=>Z.provider===D.provider)?.models.some(Z=>Z.id===D.model);let R=null;if(P.routingDefaultModel?.provider&&P.routingDefaultModel?.model)R={provider:P.routingDefaultModel.provider,model:P.routingDefaultModel.model};else if(P.defaultProvider){const D=P.providers?.[P.defaultProvider];D?.model&&(R={provider:P.defaultProvider,model:D.model})}if(R&&!$(R)){const D=N.find(Z=>Z.provider==="markus"),V=D?.models[0]?{provider:"markus",model:D.models[0].id}:N[0]?.models[0]?{provider:N[0].provider,model:N[0].models[0].id}:null;V?(R=V,K.settings.updateRouting({defaultProvider:V.provider,routingDefaultModel:V}).catch(()=>{})):R=null}g(R)}catch{v([])}finally{f(!1)}},[]);k.useEffect(()=>{p()},[p]),k.useEffect(()=>{n&&(l("agent"),d(""),p())},[n,p]),k.useEffect(()=>{if(!n)return;const _=P=>{O.current?.contains(P.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=k.useMemo(()=>{const _=h.trim().toLowerCase();return m.map(P=>({...P,models:_?P.models.filter(L=>L.id.toLowerCase().includes(_)||(L.name?.toLowerCase().includes(_)??!1)||P.displayName.toLowerCase().includes(_)||P.provider.toLowerCase().includes(_)):P.models})).filter(P=>P.models.length>0)},[m,h]),y=k.useCallback(_=>!_?.provider||!_.model?!1:m.length===0?!0:!!m.find(L=>L.provider===_.provider)?.models.some(L=>L.id===_.model),[m]);k.useEffect(()=>{if(!s||m.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const P=m.find(L=>L.provider==="markus");return P?.models[0]?{provider:"markus",model:P.models[0].id}:m[0]?.models[0]?{provider:m[0].provider,model:m[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!1})},[s,m,b,y,e]);const S=s&&y(s)?s:b,T=(S?.model?S.model.includes("/")?S.model.split("/").pop():S.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:O,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(_=>!_),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:S?`${S.provider}: ${S.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:T}),c.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&c.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:[c.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[c.jsx("input",{autoFocus:!0,value:h,onChange:_=>d(_.target.value),placeholder:i("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"}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),c.jsx("button",{type:"button",role:"switch","aria-checked":o==="global",disabled:!t,onClick:()=>l("global"),className:`relative w-9 h-5 rounded-full transition-colors ${o==="global"?"bg-brand-600":"bg-fg-tertiary/30 disabled:opacity-40"}`,children:c.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${o==="global"?"translate-x-4":""}`})})]}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"})}),c.jsx("button",{type:"button",role:"switch","aria-checked":o==="agent",disabled:!t,onClick:()=>l("agent"),className:`relative w-9 h-5 rounded-full transition-colors ${o==="agent"?"bg-brand-600":"bg-fg-tertiary/30 disabled:opacity-40"}`,children:c.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${o==="agent"?"translate-x-4":""}`})})]}),!t&&c.jsx("div",{className:"px-0.5 text-[10px] text-fg-tertiary",children:i("chatModel.noAgent",{defaultValue:"Select an agent to apply per-agent"})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[u&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!u&&x.length===0&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!u&&x.map(_=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:_.displayName}),_.models.slice(0,80).map(P=>{const L=S?.provider===_.provider&&S?.model===P.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:P.id},o),o==="global"&&g({provider:_.provider,model:P.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${L?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:P.id}),L&&c.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${_.provider}:${P.id}`)})]},_.provider))]})]})]})}async function $x(s,e,t,r,i){if(t==="agent"){r&&(s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,null).catch(()=>{}),await K.agents.updateConfig(r,{llmConfig:{modelMode:"custom",primary:e.provider,defaultModel:e.model}}));return}r&&i?.resetCurrentAgent!==!1&&await K.agents.updateConfig(r,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,e),await K.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const jx="markus_team_sidebars_c";function XM(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 qM=["chat","overview","files","tools","memory","deliverables"],zM=["chat","overview","announcements","norms","settings"];function ZM(s,e){if(s==="chat")return e("page.chatTitle");if(Zp.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=Vp.find(i=>i.key===s);return r?e(r.labelKey):s}function VM(s){if(s==="chat")return"💬";const e=Zp.find(r=>r.key===s);if(e)return e.icon;const t=Vp.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}const Rf=new Set;function FM(){return window.location.hash}function YM(s){return Rf.add(s),()=>{Rf.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Rf.forEach(s=>s()));function cL({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Lt(["team","common"]),a=k.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Mf(Kt.TEAM),[l,h]=k.useState(r?.agents??[]),[d,u]=k.useState(r?.humans??[]),[f,m]=k.useState(!r),v=Af(),b=k.useSyncExternalStore(YM,FM),g=v&&(b.startsWith(`#${Kt.TEAM}/`)||b.startsWith("#chat/")),O=v&&b.match(/^#team\/t\/(.+)$/),p=v?O?"team":g?"chat":"roster":"roster",x=O?O[1]:null,y=k.useRef(Kt.TEAM),S=k.useCallback(()=>{y.current=window.location.hash.slice(1)||Kt.TEAM,window.location.hash=`${Kt.TEAM}/d`},[]),w=k.useCallback(C=>{window.location.hash=`${Kt.TEAM}/t/${C}`},[]);k.useEffect(()=>{if(!v)return;const C=()=>{fi(P.current)&&_("chat")};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[v]);const[T,_]=k.useState("chat"),P=k.useRef("chat");P.current=T;const L=Wm({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[N,$]=k.useState(()=>{try{return localStorage.getItem(jx)==="1"}catch{return!1}}),R=k.useCallback(C=>{$(C);try{localStorage.setItem(jx,C?"1":"0")}catch{}},[]),D=ah(),V=D?.leftCollapsed??!1,Z=D?.rightPanel??null,z=D?.rightPanelTabs??[],J=D?.activeRightPanelTabId??null,Q=D?.rightPanelFullscreen??!1,A=Z?"2xl:pr-8":"2xl:pr-[280px]",B=D?.setHostAvailable,q=D?.collapseRightPanelOnly??D?.toggleRightPanel,H=D?.openRightPanel,te=400,de=320,we=6,[U,I]=k.useState(typeof window<"u"?window.innerWidth:1440),[se,F]=k.useState("auto"),G=k.useRef(V);k.useEffect(()=>{G.current!==V&&(G.current=V,$(V))},[V]);const ee=D?.keyboardPane??"content",ke=k.useRef(!1),Le=k.useRef(ee);k.useEffect(()=>{if(t||v||!o)return;const C=Le.current;Le.current=ee,(ee==="l1"||ee==="l2")&&C!==ee&&N&&($(!1),D?.setLeftCollapsed(!1))},[ee,t,v,o,N,D]),k.useEffect(()=>{if(t||v||!o)return;const C=E=>{const j=D?.keyboardPane??"content";if(j==="l0"||j==="l1"||j==="l2"||E.metaKey||E.ctrlKey||E.altKey)return;if(E.target instanceof HTMLElement){const Y=E.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||E.target.isContentEditable||E.target.closest(".xterm"))return}const W=E.key.length===1?E.key.toLowerCase():E.key;W!=="h"&&W!=="ArrowLeft"||(E.preventDefault(),N&&(R(!1),D?.setLeftCollapsed(!1)),D?.setKeyboardPane(ke.current?"l2":"l1"))};return document.addEventListener("keydown",C,!0),()=>document.removeEventListener("keydown",C,!0)},[t,v,o,D,N,R]),k.useEffect(()=>{if(B)return B(o&&!v),()=>B(!1)},[o,v,B]),k.useEffect(()=>t||v||!o?void 0:yt.on("ui:right_panel",E=>{const j=E.payload;if(j.action==="collapse"){q?.();return}if(j.action!=="open"||!j.panel||!H)return;const W=j.panel;if(W.kind==="url"&&W.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"url",url:W.url,title:W.title||W.url,browserId:Y});return}if(W.kind==="file"&&W.path){H({kind:"file",path:W.path,title:W.title});return}if(W.kind==="terminal"){const Y=W.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"terminal",terminalId:Y,title:W.title||"Terminal",cwd:W.cwd});return}W.kind==="deliverable"&&W.deliverableId&&K.deliverables.get(W.deliverableId).then(Y=>{Y.deliverable&&H({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,q,H]);const be=k.useCallback(C=>{const E=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Mi(j=>[...j,{id:E,...C}]),requestAnimationFrame(()=>cr.current?.focus())},[]),me=k.useCallback(C=>{if(C)try{const E=JSON.parse(C);if(!Array.isArray(E)||E.length===0)return;const j=E.filter(Y=>!!Y&&typeof Y.content=="string"&&Y.content.trim().length>0);if(j.length===0)return;const W=j.map(Y=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:Y.label?.trim()||"Context",content:Y.content}));Mi(Y=>[...Y,...W]),requestAnimationFrame(()=>{const Y=cr.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))})}catch{}},[]),[Oe,He]=k.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ot=Wm({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Pt=k.useRef(null),[pt,qt]=k.useState(!1),[wt,Rt]=k.useState(!1),Tt=k.useCallback(()=>{pt?Rt(C=>!C):He(C=>{const E=!C;try{localStorage.setItem("markus_team_panel_visible",String(E))}catch{}return E})},[pt]);k.useEffect(()=>{if(v)return;const C=Pt.current;if(!C)return;const E=new ResizeObserver(([j])=>{if(!j)return;const W=j.contentRect.width;if(I(W),!t){const Y=W-L.width-ot.width;qt(Y<400)}});return E.observe(C),()=>E.disconnect()},[v,t,L.width,ot.width]);const he=Oe&&!pt&&!wt,Xe=N?0:L.width+we+(he?ot.width+we:0),ge=Math.max(0,U-Xe-we-8),Je=Math.min(te,Math.floor(ge*.4)),Me=Math.max(0,ge-Je),bt=Math.min(Math.round(ge/2),Me),ir=Math.max(0,Math.min(se==="auto"?bt:se,Me)),ts=k.useRef(!1);k.useEffect(()=>{const C=(D?.rightPanel??null)!==null;C&&!ts.current&&($(!0),F("auto")),ts.current=C},[D?.rightPanel]);const Ja=k.useRef(ir);Ja.current=ir;const el=k.useRef(Me);el.current=Me;const tl=k.useCallback(C=>{C.preventDefault();const E=C.clientX,j=Ja.current,W=fe=>{const ie=j+(E-fe.clientX),ve=el.current,ae=Math.min(de,ve);F(Math.max(ae,Math.min(ve,ie)))},Y=()=>{document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",W),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);k.useEffect(()=>{if(!wt)return;const C=E=>{E.target.closest("[data-l2-floating]")||Rt(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[wt]);const[nn,si]=k.useState(null),[To,sl]=k.useState(),[ji,nr]=k.useState(),[Ei,In]=k.useState(!1),[Qo,on]=k.useState(""),[Ch,Lr]=k.useState(!1),[Ri,an]=k.useState(""),or=k.useRef(null),rl=k.useRef(null),vr=k.useCallback((C,E)=>{sl(C),nr(E),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(C??"overview")},[v]),$o=[{id:"chat"},{id:"profile"}],ri=k.useCallback(C=>{C==="profile"?vr():fi(P.current)?history.back():_("chat")},[vr]),Nr=Mx($o,T,ri),us=k.useCallback((C,E)=>{gt("direct"),Yt(C),v&&S(),vr(E?.tab,E?.highlightMailboxId),si(null)},[v,S,vr]),jo=k.useCallback((C,E)=>{const j=l.find(W=>W.name.toLowerCase()===C.toLowerCase());if(j){const W=E.target.getBoundingClientRect();si({agentId:j.id,top:W.bottom,left:W.left})}},[l]),il=k.useMemo(()=>l.map(C=>C.name),[l]),[ne,gt]=k.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[xe,Yt]=k.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[mt,ks]=k.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Ut,ms]=k.useState(""),nl=500,Ai=k.useRef(new Set),Eo=C=>{if(Ai.current.add(C),Ai.current.size>nl){const E=Math.floor(nl*.2),j=Ai.current.values();for(let W=0;W<E;W++){const Y=j.next().value;Y&&Ai.current.delete(Y)}}},ol=k.useMemo(()=>{if(r?.channelMessages){const C=r.activeChannel??"custom:general";return r.channelMessages.filter(E=>E.channel===C).map(E=>_n(E))}},[]),{manager:al,messages:Zt,setMessages:Cs,sending:Ms,setSending:gs,activities:Ph,setActivities:yr,msgBuffers:ss,sessionMsgCache:ar,activeSessionBuffer:ii,actBuffers:Sr,sessionTabsBuffer:Xs,currentConvKeyRef:lt,updateConvMsgs:ft,updateConvMsgsRaf:ni,appendConvActivity:ln,beginLoad:ll,beginStream:cn,endStream:Ps,resetConv:X,loadAndDisplay:le,incrementSending:pe,decrementSending:je,resetSending:Ge,isSendingFor:et,setStreamSession:Ot,clearStreamSession:St,getStreamSession:Ue,saveSessionToCache:ns,restoreSessionFromCache:Ls}=BM(ol),[At,Os]=k.useState(""),[Ht,Ts]=k.useState(null),[_r,Mi]=k.useState([]),[Wt,wr]=k.useState([]),lr=k.useRef(null),[Th,cl]=k.useState(!!r?.streamLastMessage),hn=k.useRef(null),mS=400;k.useEffect(()=>(Ms?(hn.current&&(clearTimeout(hn.current),hn.current=null),cl(!0)):Th&&(hn.current=setTimeout(()=>{cl(!1),hn.current=null},mS)),()=>{hn.current&&clearTimeout(hn.current)}),[Ms]);const Fp=Ms||Th||(()=>{for(let C=Zt.length-1;C>=Math.max(0,Zt.length-8);C--){const E=Zt[C];if(E.isStreaming&&!E.isStopped)return!0}return!1})(),Qh=k.useRef({fullText:"",timers:[]});k.useEffect(()=>{if(!t||!r?.streamLastMessage||Zt.length===0)return;const C=Zt[Zt.length-1];if(!C||C.sender!=="agent")return;const E=C.text;Qh.current.fullText=E;const j=Qh.current.timers;function W(){let fe=0;Cs(ve=>ve.map((ae,ce)=>ce===ve.length-1?{...ae,text:""}:ae)),cl(!0);const ie=setInterval(()=>{if(fe+=1+Math.floor(Math.random()*2),fe>=E.length){clearInterval(ie),Cs(ce=>ce.map((We,Ze)=>Ze===ce.length-1?{...We,text:E}:We));const ve=setTimeout(()=>cl(!1),800);j.push(ve);const ae=setTimeout(W,6e3);j.push(ae)}else Cs(ve=>ve.map((ae,ce)=>ce===ve.length-1?{...ae,text:E.slice(0,fe)}:ae))},30);j.push(ie)}const Y=setTimeout(W,1500);return j.push(Y),()=>{j.forEach(fe=>clearTimeout(fe)),Qh.current.timers=[]}},[]);const Li=k.useRef(0),[Yp,Dr]=k.useState(!1),[$h,Up]=k.useState(!1),[hl,oi]=k.useState(!1),[qs,jh]=k.useState([]),[Hp,Gp]=k.useState(null),Eh=k.useRef(null),cr=k.useRef(null),[dl,dn]=k.useState(null),[gS,Ro]=k.useState(null),Ni=k.useRef(null),Rh=k.useRef(!1),Ao=k.useCallback(()=>{const C=cr.current;if(!C)return;const E=Rh.current,j=E?36:52,W=E?160:120;C.style.height="auto";const Y=Math.max(j,Math.min(C.scrollHeight,W));C.style.height=`${Y}px`,C.style.overflowY=Y>=W?"auto":"hidden"},[]);k.useEffect(()=>{const C=requestAnimationFrame(()=>Ao());return()=>cancelAnimationFrame(C)},[At,qs.length,Ao]);const Ah=C=>{try{const E=localStorage.getItem(`markus_closed_tabs_${C}`);return E?new Set(JSON.parse(E)):new Set}catch{return new Set}},OS=(C,E)=>{const j=Ah(C);j.add(E);try{localStorage.setItem(`markus_closed_tabs_${C}`,JSON.stringify([...j]))}catch{}},xS=(C,E)=>{const j=Ah(C);if(j.delete(E))try{localStorage.setItem(`markus_closed_tabs_${C}`,JSON.stringify([...j]))}catch{}},bS=C=>{try{return localStorage.getItem(`markus_active_session_${C}`)}catch{return null}},ul=(C,E)=>{if(C)try{E&&E!==kt?localStorage.setItem(`markus_active_session_${C}`,E):localStorage.removeItem(`markus_active_session_${C}`)}catch{}},[Mh,Di]=k.useState([]),[Ke,Ir]=k.useState(null),[un,fn]=k.useState(!1),[Kp,Lh]=k.useState([]),[Mo,Nh]=k.useState(null),[vS,Jp]=k.useState(null),[fl,Dh]=k.useState([]),[Bn,Ih]=k.useState(null),[yS,em]=k.useState(null),[tm,Bh]=k.useState([]),[Lo,SS]=k.useState([]),zs=C=>{SS(E=>{const j=typeof C=="function"?C(E):C,W=new Set;return j.filter(Y=>W.has(Y.id)?!1:(W.add(Y.id),!0))})},pl=k.useRef(null),Wh=k.useRef(null),kr=k.useRef(null),[Qs,No]=k.useState(r?.groupChats??[]),Xh=k.useRef(Qs);Xh.current=Qs;const sm=k.useRef(null),[Do,xs]=k.useState(!1),[pn,Io]=k.useState(!1),[rm,Wn]=k.useState(""),[qh,Ii]=k.useState([]),[im,nm]=k.useState(!1),zh=k.useRef(void 0),[Cr,om]=k.useState(r?.teams??[]),[_S,wS]=k.useState([]),[ml,am]=k.useState([]),[kS,CS]=k.useState(null),[UM,HM]=k.useState(!1),[GM,KM]=k.useState(""),[lm,Bo]=k.useState(!1),[cm,PS]=k.useState(""),[Wo,Xn]=k.useState(0),[hm,gl]=k.useState(!1),[dm,TS]=k.useState(""),[Zh,Xo]=k.useState(0),[Vh,QS]=k.useState([]),um=k.useRef(!1),Fh=k.useCallback(()=>{um.current||(um.current=!0,(async()=>{try{const{skills:C}=await K.skills.list();QS(C.map(E=>({name:E.name,description:E.description??E.name})))}catch{}})())},[]);k.useEffect(()=>{Fh()},[Fh]);const mn=dm?Vh.filter(C=>C.name.toLowerCase().includes(dm.toLowerCase())):Vh,[$S,jS]=k.useState([]),fm=k.useRef(!1),ES=k.useCallback(()=>{fm.current||(fm.current=!0,(async()=>{const C=[];try{const[E,j,W,Y,fe]=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 ie of E.projects)C.push({id:ie.id,name:ie.name,entityType:"project",role:ie.status});for(const ie of j.requirements)C.push({id:ie.id,name:ie.title,entityType:"requirement",role:ie.priority});for(const ie of W.tasks)C.push({id:ie.id,name:ie.title,entityType:"task",role:ie.status});for(const ie of Y.results)C.push({id:ie.id,name:ie.title,entityType:"deliverable",role:ie.type});for(const ie of fe.teams)try{const ve=await K.workflows.list(ie.id);for(const ae of ve.workflows)C.push({id:ae.name,name:ae.displayName||ae.name,entityType:"workflow",role:`v${ae.version}`})}catch{}}catch{}jS(C)})())},[]),rs=ne==="channel"?Qs.find(C=>C.channelKey===mt)?.teamId:void 0,RS=k.useRef(null),qn=k.useRef(null),$s=k.useRef(null),pm=k.useRef(void 0),Ol=k.useRef(!1),Br=k.useRef(!0),mm=k.useRef(void 0);k.useEffect(()=>{if(!un)return;const C=E=>{Wh.current&&!Wh.current.contains(E.target)&&pl.current&&!pl.current.contains(E.target)&&fn(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[un]);const xl=(C,E)=>{if(!E||C===E)return`notes:${C}`;const[j,W]=[C,E].sort();return`dm:${j}:${W}`};k.useEffect(()=>{localStorage.setItem("markus_chat_mode",ne)},[ne]),k.useEffect(()=>{localStorage.setItem("markus_chat_agent",xe)},[xe]),k.useEffect(()=>{localStorage.setItem("markus_chat_channel",mt)},[mt]),k.useEffect(()=>{let C=!1;if(t||!xe||ne!=="direct"){Ro(null);return}return K.agents.get(xe).then(E=>{if(C)return;const j=E.config?.llmConfig;Ro(j?.modelMode==="custom"&&j.primary&&j.defaultModel?{provider:j.primary,model:j.defaultModel}:null)}).catch(()=>{C||Ro(null)}),()=>{C=!0}},[xe,ne,t]);const{counts:Yh,sessionAgentMap:qo,markRead:zo,setActiveKey:AS,clearActiveKey:MS}=P_({enabled:!t}),bl=k.useMemo(()=>{const C={};for(const[E,j]of Object.entries(Yh))E.startsWith("channel:")&&(C[E.slice(8)]=j);return C},[Yh]),Uh=T_(qo,Yh);k.useEffect(()=>{let C=0;for(const E of Uh.values())C+=E;for(const E of Object.values(bl))C+=E;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:C}}))},[Uh,bl]);const vl=Uh,LS=k.useCallback(async C=>{for(const[E,j]of Object.entries(qo))j===C&&zo(`session:${E}`)},[qo,zo]);k.useEffect(()=>{if(t||!((!v||p==="chat")&&T==="chat"))return;if(ne==="direct"&&xe&&LS(xe),ne==="channel"&&mt)zo(`channel:${mt}`);else if(ne==="direct"&&Ke)zo(`session:${Ke}`);else if(ne==="dm"&&Ut){const j=`dm:${[e?.id,Ut].sort().join(":")}`;zo(`channel:${j}`)}const E=[];if(ne==="direct"&&Ke){E.push(`session:${Ke}`);for(const[j,W]of Object.entries(qo))W===xe&&E.push(`session:${j}`)}else ne==="channel"&&mt?E.push(`channel:${mt}`):ne==="dm"&&Ut&&e?.id&&E.push(`channel:dm:${[e.id,Ut].sort().join(":")}`);for(const j of E)AS(j);return()=>{for(const j of E)MS(j)}},[t,ne,mt,Ke,Ut,xe,p,T,qo]);const hr=k.useCallback(()=>K.agents.list().then(C=>h(C.agents)).catch(()=>{}),[]),Hs=k.useCallback(()=>K.teams.list().then(C=>om(C.teams)).catch(()=>{}),[]),zn=k.useCallback(()=>K.groupChats.list().then(C=>No(C.chats)).catch(()=>{}),[]),NS=k.useMemo(()=>fd(hr,3e3),[hr]),yl=k.useMemo(()=>fd(Hs,5e3),[Hs]),Hh=k.useMemo(()=>fd(zn,3e3),[zn]),Zo=k.useCallback(()=>{K.users.list(e?.orgId).then(C=>u(C.users)).catch(()=>{})},[e?.orgId]);k.useEffect(()=>{t||(Promise.all([hr(),Hs()]).finally(()=>m(!1)),Zo(),K.tasks.list().then(C=>am(C.tasks)).catch(()=>{}),K.externalAgents.list().then(C=>wS(C.agents)).catch(()=>{}),zn())},[t,Zo]),k.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),u(r.humans??[]),om(r.teams??[]),No(r.groupChats??[]),r.channelMessages)){const C=r.activeChannel??"custom:general";Cs(r.channelMessages.filter(E=>E.channel===C).map(E=>_n(E)))}},[t,r]),k.useEffect(()=>{if(t||!o)return;hr(),Hs();const C=setInterval(hr,3e4),E=setInterval(Hs,6e4),j=yt.on("agent:update",()=>{NS(),yl()}),W=yt.on("team:update",()=>{yl(),Hh()}),Y=yt.on("agent:removed",yl),fe=yt.on("chat:group_created",()=>{zn(),Hs(),hr()}),ie=yt.on("chat:group_updated",Hh),ve=yt.on("chat:group_deleted",()=>{Hh(),yl()}),ae=yt.on("task:update",We=>{const Ze=We?.payload;Ze?.taskId&&am(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(C),clearInterval(E),j(),W(),Y(),fe(),ie(),ve(),ae(),window.removeEventListener("markus:data-changed",ce)}},[t,o,Zo]),k.useEffect(()=>{if(t)return;const C=ce=>{const We=ce.detail;if(X_(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),_("chat"),v&&S(),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(ut=>ut.id===Ze);Te&&Tl(Te)}catch{}},300)}}if(We.params?.selectAgent&&(gt("direct"),Yt(We.params.selectAgent),_("chat"),v&&S()),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"),_("chat"),We.params?.autoSend==="true"?setTimeout(()=>pm.current?.(Ze),300):(Os(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"),_("chat"),me(Ze)}if(We.params?.dm&&(gt("dm"),ms(We.params.dm),_("chat"),v&&S()),We.params?.channel&&(gt("channel"),ks(We.params.channel),_("chat"),v&&S()),We.params?.selectTeam){const Ze=We.params.selectTeam;if(v)w(Ze);else{const Ie=Xh.current.find(Te=>Te.type==="team"&&Te.teamId===Ze);gt("channel"),ks(Ie?.channelKey??`group:${Ze}`),_("chat"),xs(!1),He(!0)}}We.params?.openHire}},E=localStorage.getItem("markus_nav_agentId");if(E){localStorage.removeItem("markus_nav_agentId");const ce=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),gt("direct"),Yt(E),ce?us(E,{tab:ce}):(_("chat"),v&&S())}const j=localStorage.getItem("markus_nav_dm");j&&(localStorage.removeItem("markus_nav_dm"),gt("dm"),ms(j),_("chat"),v&&S());const W=localStorage.getItem("markus_nav_channel");W&&(localStorage.removeItem("markus_nav_channel"),gt("channel"),ks(W),_("chat"),v&&S());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Os(Y),setTimeout(()=>{const ce=cr.current;ce&&(ce.focus(),ce.setSelectionRange(ce.value.length,ce.value.length))},150));const fe=localStorage.getItem("markus_nav_chatChips");fe&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),me(fe));const ie=localStorage.getItem("markus_nav_openDeliverable");ie&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:ie}):H&&K.deliverables.get(ie).then(ce=>{ce.deliverable&&H({kind:"deliverable",deliverable:ce.deliverable})}).catch(()=>{}));const ve=localStorage.getItem("markus_nav_selectAgent");ve&&(localStorage.removeItem("markus_nav_selectAgent"),gt("direct"),Yt(ve),_("chat"),v&&S());const ae=localStorage.getItem("markus_nav_selectTeam");if(ae)if(localStorage.removeItem("markus_nav_selectTeam"),v)w(ae);else{const ce=Xh.current.find(We=>We.type==="team"&&We.teamId===ae);gt("channel"),ks(ce?.channelKey??`group:${ae}`),_("chat"),xs(!1),He(!0)}return window.addEventListener("markus:navigate",C),()=>window.removeEventListener("markus:navigate",C)},[t]),k.useEffect(()=>{const C=sm.current;if(!C)return;const E=Qs.find(j=>j.type==="team"&&j.teamId===C);sm.current=null,gt("channel"),ks(E?.channelKey??`group:${C}`),_("chat"),xs(!1),He(!0)},[Qs,Cr]),k.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||xe&&l.some(j=>j.id===xe))return;const C=localStorage.getItem("markus_nav_after_remove");if(C&&(localStorage.removeItem("markus_nav_after_remove"),C.startsWith("channel:"))){gt("channel"),ks(C.slice(8)),_("chat");return}const E=l.find(j=>!j.teamId&&j.role?.toLowerCase()==="secretary")??l.find(j=>j.role?.toLowerCase()==="secretary")??l.find(j=>j.name?.toLowerCase().includes("secretary"));E?(gt("direct"),Yt(E.id),_("chat")):l.length>0&&(gt("direct"),Yt(l[0].id),_("chat"))},[l,xe]);const Zn=k.useRef(!1),Pr=k.useRef(!1),Sl=k.useRef(!1),_l=k.useRef(0),Vn=k.useRef(0),[DS,ai]=k.useState(!1),Bi=k.useRef(0),[gm,gn]=k.useState(0),li=k.useCallback(()=>{Pr.current=!1,Sl.current=!1,Br.current=!0},[]),Gh=k.useCallback(()=>{Pr.current=!0,Br.current=!1,Vn.current+=1,Zn.current=!1,ai(!0)},[]),On=k.useCallback(C=>{const E=qn.current;if(!E)return;const j=E.scrollHeight-E.scrollTop-E.clientHeight,W=j<160,Y=j<48,fe=_l.current,ie=E.scrollTop<fe-2;if(_l.current=E.scrollTop,ie&&j>20){Sl.current=!0,Gh();return}if(Sl.current){Y?(li(),ai(!1),Bi.current=0,gn(0)):Gh();return}if(W&&!Pr.current){li(),ai(!1),Bi.current=0,gn(0);return}C?.fromProgrammatic||Zn.current||!Pr.current&&Br.current||Pr.current&&(Br.current=!1,ai(!0))},[Gh,li]);k.useEffect(()=>{const C=qn.current;if(!C)return;const E=()=>{Sl.current=!0},j=()=>{On({fromProgrammatic:Zn.current})};C.addEventListener("wheel",E,{passive:!0}),C.addEventListener("touchmove",E,{passive:!0}),C.addEventListener("scroll",j,{passive:!0});const W=typeof ResizeObserver<"u"?new ResizeObserver(()=>On()):null;return W?.observe(C),_l.current=C.scrollTop,On(),()=>{C.removeEventListener("wheel",E),C.removeEventListener("touchmove",E),C.removeEventListener("scroll",j),W?.disconnect()}},[p,On]);const Kh=k.useMemo(()=>new Set(tm),[tm]),os=k.useMemo(()=>{const C=ne==="channel"?Zt:Zt.filter(E=>!E.isActivityLog);return Kh.size===0?C:C.filter(E=>!(E.isNotification&&Kh.has(E.id)))},[Zt,ne,Kh]);k.useEffect(()=>{Rh.current=T==="chat"&&os.length>0,Ao()},[T,os.length,Ao]);const ci=lw({count:os.length,getScrollElement:()=>qn.current,getItemKey:C=>os[C]?.id??C,estimateSize:C=>{const E=os[C];return E?E.segments&&E.segments.length>0?300:E.text.length>500?200:120:120},overscan:8});ci.shouldAdjustScrollPositionOnItemSizeChange=(C,E,j)=>Xm()?!1:C.start<(j.scrollOffset??0);const hi=k.useCallback((C="instant")=>{if(!Br.current||Pr.current)return;const E=++Vn.current;Zn.current=!0;const j=()=>E===Vn.current&&Br.current&&!Pr.current,W=()=>{if(E!==Vn.current)return;if(Zn.current=!1,!j()){On();return}const Y=qn.current;Y&&(_l.current=Y.scrollTop,Y.scrollHeight-Y.scrollTop-Y.clientHeight<160&&!Pr.current&&(li(),ai(!1),Bi.current=0,gn(0))),requestAnimationFrame(()=>{E===Vn.current&&On({fromProgrammatic:!0})})};if(os.length>0)ci.scrollToIndex(os.length-1,{align:"end",behavior:C}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!j()){E===Vn.current&&(Zn.current=!1);return}ci.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(W)})});else{const Y=qn.current;Y&&Y.scrollTo({top:Y.scrollHeight,behavior:C}),requestAnimationFrame(W)}},[os.length,ci,On,li]),Om=k.useRef(o);k.useEffect(()=>{Om.current=o},[o]),k.useLayoutEffect(()=>{if(Ol.current){Ol.current=!1;const C=Cl.current;C>0&&(Cl.current=0,ci.scrollToIndex(C,{align:"start",behavior:"instant"}));return}Om.current&&(!Br.current||Pr.current||Xm()||hi())},[Zt,hi,ci]);const xm=k.useRef(T);k.useEffect(()=>{const C=xm.current!=="chat";if(xm.current=T,T==="chat"&&C&&Br.current&&!Pr.current){const E=[],j=requestAnimationFrame(()=>hi("instant"));for(const W of[60,160,320])E.push(setTimeout(()=>hi("instant"),W));return()=>{cancelAnimationFrame(j);for(const W of E)clearTimeout(W)}}},[T,Ms,hi]);const bm=k.useRef(A);k.useEffect(()=>{if(bm.current===A||(bm.current=A,T!=="chat")||os.length===0||Ms||hl||!Br.current||Pr.current)return;const C=[],E=requestAnimationFrame(()=>hi("instant"));for(const j of[60,160,320])C.push(setTimeout(()=>hi("instant"),j));return()=>{cancelAnimationFrame(E);for(const j of C)clearTimeout(j)}},[A,T,os.length,Ms,hl,hi]);const vm=k.useCallback(async(C,E)=>{const j=E??`ch:${C}`;lt.current===j&&oi(!0);try{const W=await K.channels.getMessages(C,50),Y=W.messages.map(fe=>_n(fe,e?.id));ss.set(j,Y),lt.current===j&&(Cs(Y),Dr(W.hasMore),kr.current=W.messages[0]?new Date(W.messages[0].createdAt).toISOString():null)}catch{lt.current===j&&(Cs([]),Dr(!1))}finally{lt.current===j&&oi(!1)}},[]),Jh=k.useCallback(async(C,E)=>{const j=lt.current===E&&(ss.get(E)?.length??0)===0;j&&oi(!0);try{const{count:W,hasMore:Y,oldestCursor:fe}=await le(C,E,async()=>{const ie=await K.sessions.getMessages(C,50);return{messages:Q_(ie.messages.map(pd).filter(ae=>ae.sender!=="agent"||ae.text||ae.segments&&ae.segments.length>0||ae.isStreaming)),hasMore:ie.hasMore,oldestCursor:ie.messages[0]?new Date(ie.messages[0].createdAt).toISOString():null}});return Dr(Y),kr.current=fe,W}finally{j&&lt.current===E&&oi(!1)}},[le,ss]),ym=k.useRef(new Map),wl=k.useRef(new Set),xn=k.useCallback(async(C,E,j)=>{if(!C||!E||E===kt||wl.current.has(E))return;let W=null;try{if($s.current&&!$s.current.signal.aborted&&Ue(j)?.has(E)){cn(j),lt.current===j&&gs(!0);return}const Y=`${C}:${E}`,fe=ym.current.get(Y)??0;if(Date.now()-fe<1500)return;const ie=await K.sessions.streamStatus(C,E),ve=ss.get(j)??[],ae=$_(ve),ce=ie.status==="streaming",We=!!ie.active&&(ie.status==="done"||ie.status==="error")&&!!ae?.isStreaming;if(!ce&&!We)return;ym.current.set(Y,Date.now()),Ni.current?.abort(),W=new AbortController,Ni.current=W,cn(j),gs(!0),Ot(j,E);let Ze=ae?.id;if(!ae||ae.isError)Ze=`reattach_${Date.now()}`,ft(j,ye=>[...ye,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],E);else{const ye=(ae.segments??[]).filter(ze=>ze.type==="tool").map(ze=>ze.status==="stopped"||ze.status==="running"?{...ze,status:"running"}:ze);ft(j,ze=>ze.map(Qe=>Qe.id===ae.id?{...Qe,text:"",isStreaming:!0,isStopped:!1,segments:ye,committedSegments:void 0}:Qe),E)}let Ie=!1;const Te=ye=>{lt.current===j&&(Li.current=Date.now(),ni(j,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(ue=>ue.id===Ze):-1,Ee=De>=0?De:Qe.map((ue,Se)=>({m:ue,j:Se})).reverse().find(ue=>ue.m.sender==="agent"&&ue.m.isStreaming)?.j??-1;if(Ee<0)return ze;const qe=Qe[Ee].segments??[],st=qe[qe.length-1],Mt=st?.type==="text"?st.thinking??"":"";let Gt="",Ns="",oe=ye;for(;oe.length>0;)if(Ie){const ue=oe.indexOf("</think>");ue>=0?(Gt+=oe.slice(0,ue),oe=oe.slice(ue+8),Ie=!1):(Gt+=oe,oe="")}else{const ue=oe.indexOf("<think>");ue>=0?(Ns+=oe.slice(0,ue),oe=oe.slice(ue+7),Ie=!0):(Ns+=oe,oe="")}const Fe=Mt+Gt||void 0,Ce=st?.type==="text"?[...qe.slice(0,-1),{type:"text",content:st.content+Ns,thinking:Fe,createdAt:st.createdAt}]:[...qe,{type:"text",content:Ns,thinking:Fe,createdAt:new Date().toISOString()}];return Qe[Ee]={...Qe[Ee],text:(Qe[Ee].text??"")+Ns,segments:Ce,isStreaming:!0},Qe},E))},ut=ye=>{if(lt.current===j&&(Li.current=Date.now(),ye.phase!=="heartbeat")){if((ye.phase==="start"||ye.phase==="end")&&ln(j,{...ye,phase:ye.phase,ts:Date.now()},E),ye.phase==="start"){const ze=`${ye.tool}_${Date.now()}`,Qe=new Date().toISOString(),De=Ee=>{const qe=[...Ee];for(let st=qe.length-1;st>=0;st--){const Mt=qe[st];if(Mt.type==="tool"&&Mt.tool===ye.tool&&(Mt.status==="running"||Mt.status==="stopped"))return qe[st]={...Mt,status:"running",args:ye.arguments??Mt.args},qe}return qe.push({type:"tool",key:ze,tool:ye.tool,status:"running",args:ye.arguments,createdAt:Qe}),qe};ft(j,Ee=>{const qe=[...Ee],st=Ze?qe.findIndex(oe=>oe.id===Ze):-1;if(st<0)return Ee;const Mt=De(qe[st].segments??[]),Gt=qe[st].committedSegments,Ns=Gt&&De(Gt);return qe[st]={...qe[st],segments:Mt,committedSegments:Ns,isStreaming:!0},qe},E)}else if(ye.phase==="end"){const ze=new Date().toISOString(),Qe=De=>{const Ee=[...De];for(let qe=Ee.length-1;qe>=0;qe--){const st=Ee[qe];if(st.type==="tool"&&st.tool===ye.tool&&(st.status==="running"||st.status==="stopped")){Ee[qe]={...st,status:ye.success===!1?"error":"done",args:ye.arguments??st.args,result:ye.result,error:ye.error,durationMs:ye.durationMs,liveOutput:void 0,createdAt:ze};break}}return Ee};ft(j,De=>{const Ee=[...De],qe=Ze?Ee.findIndex(Ns=>Ns.id===Ze):-1;if(qe<0)return De;const st=Qe(Ee[qe].segments??[]),Mt=Ee[qe].committedSegments,Gt=Mt&&Qe(Mt);return Ee[qe]={...Ee[qe],segments:st,committedSegments:Gt,isStreaming:!0},Ee},E)}else if(ye.phase==="subagent_progress"&&ye.subagentEvent){const ze=Qe=>{const De=[...Qe];for(let Ee=De.length-1;Ee>=0;Ee--){const qe=De[Ee];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){De[Ee]={...qe,status:"running",subagentLogs:qm(qe.subagentLogs,ye.subagentEvent)};break}}return De};ni(j,Qe=>{const De=[...Qe],Ee=Ze?De.findIndex(Gt=>Gt.id===Ze):-1;if(Ee<0)return Qe;const qe=ze(De[Ee].segments??[]),st=De[Ee].committedSegments,Mt=st&&ze(st);return De[Ee]={...De[Ee],segments:qe,committedSegments:Mt,isStreaming:!0},De},E)}}},Be=ye=>{lt.current===j&&(Li.current=Date.now(),ft(j,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(qe=>qe.id===Ze):-1;if(De<0)return ze;const Ee=[...Qe[De].committedSegments??[]];if(ye.type==="thinking_commit")Ee.push({type:"text",content:"",thinking:ye.content,createdAt:ye.createdAt});else if(ye.type==="text_commit")Ee.push({type:"text",content:ye.content,createdAt:ye.createdAt});else return ze;return Qe[De]={...Qe[De],committedSegments:Ee,isStreaming:!0},Qe},E))},tt=ye=>{if(lt.current!==j)return;Li.current=Date.now();const ze=(ye.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(j,Qe=>{const De=[...Qe],Ee=Ze?De.findIndex(qe=>qe.id===Ze):-1;return Ee<0?Qe:(De[Ee]={...De[Ee],text:ye.content||De[Ee].text,segments:ze,committedSegments:ze,isStreaming:!0,isStopped:!1},De)},E);for(const Qe of ze)Qe.type==="tool"&&ln(j,{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()},E)},rt=await K.sessions.reattachStream(C,E,{onChunk:Te,onActivity:ut,onCommit:Be,onSnapshot:tt},W.signal,0);if(!rt.attached){Ps(j),lt.current===j&&(ft(j,ye=>{const ze=[...ye],Qe=Ze?ze.findIndex(qe=>qe.id===Ze):-1,De=Qe>=0?Qe:ze.map((qe,st)=>({m:qe,j:st})).reverse().find(qe=>qe.m.sender==="agent"&&qe.m.isStreaming)?.j??-1;if(De<0)return ye;const Ee=ze[De];return Ee.isStreaming?(ze[De]={...Ee,isStreaming:!1,isStopped:Ee.isError?Ee.isStopped:!0},ze):ye},E),gs(!1));return}lt.current===j&&(ft(j,ye=>{const ze=[...ye],Qe=Ze?ze.findIndex(st=>st.id===Ze):-1,De=Qe>=0?Qe:ze.map((st,Mt)=>({m:st,j:Mt})).reverse().find(st=>st.m.sender==="agent"&&st.m.isStreaming)?.j??-1;if(De<0)return ye;const Ee=ze[De];if(!Ee.isStreaming)return ye;const qe=rt.segments?.length?zm(rt.segments,Ee.segments):void 0;return ze[De]={...Ee,text:rt.content||Ee.text,isStreaming:!1,isStopped:!1,...qe?{segments:qe,committedSegments:qe}:{}},ze},E),gs(!1)),Ps(j),Ni.current===W&&(Ni.current=null)}catch(Y){if(Ni.current===W&&(Ni.current=null),Ps(j),lt.current===j&&gs(!1),Y instanceof Error&&Y.name==="AbortError")return}},[ln,cn,Ps,Ue,ss,Ot,ft,ni]);k.useEffect(()=>{if(!o||t||ne!=="direct"||!xe)return;const C=Ke;!C||C===kt||xn(xe,C,lt.current)},[o,t,ne,xe,Ke,xn]);const kl=k.useCallback(async C=>{if(!C)return Di([]),[];try{const{sessions:E}=await K.sessions.listByAgent(C,10);return Di(E),E}catch{return Di([]),[]}},[]),Cl=k.useRef(0),IS=k.useCallback(async()=>{if(!($h||!Yp||!kr.current)){Up(!0);try{const C=lt.current;if(ne==="channel"||ne==="dm"){const E=ne==="dm"?xl(e?.id??"",Ut):mt,j=await K.channels.getMessages(E,50,kr.current),W=j.messages.map(Y=>_n(Y,e?.id));Cl.current=W.length,Ol.current=!0,Cs(Y=>{let fe=[...W,...Y];return fe.length>500&&(fe=fe.slice(-500)),ss.set(C,fe),fe}),Dr(j.hasMore),j.messages[0]&&(kr.current=new Date(j.messages[0].createdAt).toISOString())}else if(Ke){const E=await K.sessions.getMessages(Ke,50,kr.current),j=E.messages.map(pd);Cl.current=j.length,Ol.current=!0,Cs(W=>{let Y=[...j,...W];return Y.length>500&&(Y=Y.slice(-500)),ss.set(C,Y),Y}),Dr(E.hasMore),E.messages[0]&&(kr.current=new Date(E.messages[0].createdAt).toISOString())}}catch{}finally{Up(!1)}}},[$h,Yp,ne,mt,Ke,e?.id,Ut]);mm.current=IS;const ed=k.useRef(!1),BS=k.useCallback(C=>{ed.current||(ed.current=!0,requestAnimationFrame(()=>{ed.current=!1,C.target.scrollTop<100&&mm.current?.()}))},[]);k.useEffect(()=>{if(t)return;const C=ac(ne,xe,mt,Ut),E=lt.current;lt.current=C,E&&E!==C&&(Xs.set(E,Lo),Ke&&ii.set(E,Ke)),E!==C&&(li(),ai(!1),Bi.current=0,gn(0));const j=ss.get(C),W=Xs.get(C),Y=ii.get(C),fe=Ue(C),ie=Y??Ke,ve=et(C)&&(ne!=="direct"||!fe||!ie||fe.has(ie)),ae=ie??C,ce=Sr.get(ae)??[];if(yr(ve?ce:[]),gs(ve),ne==="direct"&&xe&&kl(xe),W&&W.length>0&&zs(W),fn(!1),j!==void 0&&j.length>0)if(ve||al.completeLoad(C),oi(!1),Cs(j),Dr(!1),Y!==void 0&&Ir(Y),(!W||W.length===0)&&zs([]),ne==="channel"||ne==="dm"){const Ze=ne==="dm"?xl(e?.id??"",Ut):mt;vm(Ze,C)}else ne==="direct"&&xe&&Y&&Y!==kt&&(ve?xn(xe,Y,C):Jh(Y,C).then(()=>{lt.current===C&&xe&&xn(xe,Y,C)}));else if(ll(C),oi(!0),Cs([]),Dr(!1),kr.current=null,ss.delete(C),ne==="channel"||ne==="dm"){const Ze=ne==="dm"?xl(e?.id??"",Ut):mt;vm(Ze,C),(!W||W.length===0)&&zs([])}else ne==="direct"&&xe?kl(xe).then(Ze=>{if(lt.current===C)if(Ze.length>0){const Ie=Ze.find(De=>De.isMain),Te=Ah(xe),ut=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=W&&W.length>0?W:ut;const tt=bS(xe),rt=Y!==void 0?Y:tt??Ie?.id??Be[0].id;if(rt&&rt!==kt&&!Be.some(De=>De.id===rt)){const De=Ze.find(Ee=>Ee.id===rt);De&&(Be=[...Be,De])}const ye=rt&&Be.some(De=>De.id===rt)?rt:Be[0].id;Ir(ye),ii.set(C,ye),ul(xe,ye),zs(Be);const Qe=Ze.find(De=>De.id===ye)?.metadata?.modelOverride;dn(Qe?.provider&&Qe?.model?{provider:Qe.provider,model:Qe.model}:null),Jh(ye,C).then(()=>{lt.current===C&&xe&&xn(xe,ye,C)})}else Ir(null),dn(null),oi(!1),(!W||W.length===0)&&zs([])}).catch(()=>{lt.current===C&&oi(!1)}):oi(!1)},[t,ne,xe,mt,Ut,n.language,i]),k.useEffect(()=>t?void 0:yt.on("chat:message",E=>{const j=E.payload,W=j.channel??"";if(!W)return;const Y=j.senderType??"agent",fe=j.text??j.message??"",ie=j.senderId??j.agentId??"",ve=j.senderName??j.agentId??i("page.fallbackAgent"),ae=j.metadata,ce=j.messageId??j.id??"";if(ce&&Ai.current.has(ce))return;const We=Y==="human"&&ie===(e?.id??""),Ze={id:ce||`ws_${Date.now()}_${ie}`,sender:We?"user":"agent",text:fe,time:new Date().toLocaleTimeString(),agentName:We?void 0:ve,agentId:We?void 0:ie,replyToId:j.replyToId??void 0,replyToSender:j.replyToSender??void 0,replyToText:j.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:Q})},N=async Z=>{if(y?.file===Z){S(null);return}try{const z=await K.agents.roleDiff(s,Z);z.agentContent!=null&&z.templateContent!=null&&S({file:Z,agent:z.agentContent,template:z.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},R=Z=>{const z=$[Z];return z?e(`agent:profilePage.filesTab.fileLabels.${z}`):Z},D=p?.hasTemplate&&!p.isUpToDate,V=a?P.some(Z=>Z.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[D&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:P.length,templateId:p.templateId})," ",P.map(Z=>Z.file).join(", ")]})]}),c.jsx("button",{onClick:()=>L(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(as,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(Z=>{const z=P.some(J=>J.file===Z.name);return c.jsxs("button",{onClick:()=>T(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&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Z.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:R(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[V&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>N(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),m(!0),setTimeout(()=>m(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{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&&c.jsx(kM,{agent:y.agent,template:y.template,templateId:p?.templateId??""}),c.jsx(PM,{content:t.find(Z=>Z.name===a)?.content??"",editContent:l,setEditContent:Z=>{h(Z),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(oh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function PM({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=k.useState(!1),o=k.useRef(null);return k.useEffect(()=>{n&&o.current?.focus()},[n]),k.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(k.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_M,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function TM(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function QM({tools:s}){const{t:e}=Lt(["agent","common"]),t=SM(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(as,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=k_(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=TM(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(C_,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function $M({agent:s}){const{t:e}=Lt(["agent","common"]),t=s.proficiency??{},[r,i]=k.useState(null),[n,a]=k.useState(null),[o,l]=k.useState(!1),h=s.availableSkills??[],d=new Map;for(const g of h){const O=g.category||"custom";d.has(O)||d.set(O,[]),d.get(O).push(g)}const u=async g=>{if(r===g){i(null),a(null);return}i(g),l(!0);try{const O=await fetch(`/api/skills/${encodeURIComponent(g)}`);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"},m=g=>{const O=t[g.name],p=O&&O.uses>0?Math.round(O.successes/O.uses*100):null,x=O&&c.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===g.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${y?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>u(g.name),children:[c.jsx("span",{className:`text-sm transition-transform ${y?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:g.name}),g.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),g.builtIn&&!g.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!g.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:g.description}),x]}),p!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),y&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${f[n.category]??f.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(S=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:S},S))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(S=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",S]},S))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(S=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:S.name}),S.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:S.description})]},S.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},g.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],b=[...d.entries()].sort((g,O)=>{const p=v.indexOf(g[0]),x=v.indexOf(O[0]);return(p===-1?999:p)-(x===-1?999:x)});return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),b.map(([g,O])=>c.jsx(as,{title:c.jsxs("span",{className:"capitalize",children:[g," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",O.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:O.map(p=>m(p))})},g)),h.length===0&&c.jsx(oh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function mx({tools:s,agent:e}){const{t}=Lt(["agent","common"]),[r,i]=k.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(QM,{tools:s}):c.jsx($M,{agent:e})]})}function gx({agentId:s}){const{t:e}=Lt(["agent","common"]),[t,r]=k.useState(null),[i,n]=k.useState(!0),[a,o]=k.useState("longterm"),[l,h]=k.useState(""),[d,u]=k.useState(""),[f,m]=k.useState(!1),[v,b]=k.useState(null),[g,O]=k.useState(null),[p,x]=k.useState([]),[y,S]=k.useState(!1),w=k.useCallback(()=>{n(!0),K.agents.getMemory(s).then($=>{r($),h($.recentDailyLogs??""),u($.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);k.useEffect(()=>{w()},[w]);const T=async()=>{m(!0),await K.agents.updateDailyMemory(s,l).catch(()=>{}),m(!1),w()},_=async()=>{m(!0),await K.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),m(!1),w()},P=l!==(t?.recentDailyLogs??""),L=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const N=[{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 c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex gap-2",children:N.map($=>c.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"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(oh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map(($,R)=>{const D=v===R;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(D?null:R),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.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}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${D?"":"line-clamp-2"}`,children:$.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&c.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]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:D?"▲":"▼"})]})]}),D&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",$.importance]}),c.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},R)})})}),a==="sessions"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(oh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map($=>{const R=g===$.id,D=async()=>{if(R){O(null),x([]);return}O($.id),S(!0);try{const V=await K.agents.getMemorySession(s,$.id);x(V.messages)}catch{x([])}S(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:D,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:R?"▲":"▼"})]}),R&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?c.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 c.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(Z=>Z.role!=="tool").map((Z,z)=>c.jsxs("div",{className:"px-3 py-2",children:[(Z.role==="user"||Z.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${Z.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${Z.role}`,{defaultValue:Z.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(xa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[Z.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(xa,{content:Z.content,className:"text-xs text-fg-secondary"})})]}),Z.toolCalls&&Z.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:Z.toolCalls.map(J=>{let Q;try{Q=JSON.parse(J.arguments)}catch{}const A={tool:J.name,status:"done",args:Q,result:V.get(J.id)};return c.jsx(v_,{entry:{type:"tool",info:A}},J.id)})})]})]},z))})})()})]},$.id)})})}),a==="daily"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:P?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:T,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:$=>h($.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(as,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:L?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:$=>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 Ox({agentId:s,initialData:e}){const{t}=Lt(["agent","common"]),[r,i]=k.useState(e??null),[n,a]=k.useState(!e),[o,l]=k.useState([]),[h,d]=k.useState(null),[u,f]=k.useState(!1),[m,v]=k.useState(null),b=k.useCallback(()=>Promise.all([K.agents.getHeartbeat(s).then(i).catch(()=>{}),K.agents.getRecentActivities(s).then(y=>{l(y.activities.filter(S=>S.type==="heartbeat"))}).catch(()=>{})]),[s]);k.useEffect(()=>{a(!0),b().finally(()=>a(!1))},[b]),k.useEffect(()=>yt.on("agent:update",S=>{S.payload?.agentId===s&&b()}),[s,b]);const g=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 c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const p=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 S=Date.now()-new Date(y).getTime();if(S<0){const w=Math.abs(S);return w<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(w/1e3)}):w<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(w/6e4)}):t("agent:profilePage.relative.inHours",{hours:(w/36e5).toFixed(1)})}return S<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(S/1e3)}):S<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(S/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(S/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(as,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:b,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:g,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(bs,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(EM,{agentId:s,intervalMs:r.intervalMs,onChanged:b}),c.jsx(bs,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?x(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(bs,{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")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),m&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:m})]}),r.wakeups&&r.wakeups.length>0&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(y=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:y.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.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")}`]})]}),c.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&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(y=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:y.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:y.label}),c.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&&c.jsx(as,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx(xa,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(y=>{const S=h===y.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(S?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:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:y.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:y.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(y.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${S?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),S&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(qa,{agentId:s,activityId:y.id})})]},y.id)})})}):r.lastHeartbeat?null:c.jsx(as,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:g,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 jM({taskId:s,isLive:e}){const{t}=Lt("agent"),[r,i]=k.useState([]),[n,a]=k.useState(""),[o,l]=k.useState(!0),[h,d]=k.useState("compact");if(k.useEffect(()=>{l(!0),a(""),K.tasks.getLogs(s).then(m=>{i(m.logs),l(!1)}).catch(()=>l(!1))},[s]),k.useEffect(()=>{if(!e)return;const m=yt.on("task:log",b=>{const g=b.payload;if(g.taskId!==s)return;const O={id:g.id,taskId:g.taskId,agentId:g.agentId,seq:g.seq,type:g.logType,content:g.content,metadata:g.metadata,createdAt:g.createdAt};i(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 g=b.payload;g.taskId===s&&a(O=>O+g.text)});return()=>{m(),v()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const u=r.map(m=>w_(m)),f=new Set(u.filter(m=>m.executionRound!=null).map(m=>m.executionRound)).size>1;return c.jsx("div",{className:"px-3 py-2",children:h==="compact"?c.jsx(Nx,{entries:u,streamingText:n,isActive:e,onExpand:()=>d("full"),showRounds:f}):c.jsx(Dx,{entries:u,streamingText:n,isActive:e,onCollapse:()=>d("compact"),showRounds:f})})}function qa({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Lt("agent"),[i,n]=k.useState([]),[a,o]=k.useState(!0),[l,h]=k.useState("compact");if(k.useEffect(()=>{o(!0),K.agents.getActivityLogs(s,e).then(u=>{n(u.logs),o(!1)}).catch(()=>o(!1))},[s,e]),k.useEffect(()=>t?yt.on("agent:activity_log",f=>{const m=f.payload;if(m.agentId!==s||m.activityId!==e)return;const v={seq:m.seq,type:m.type,content:m.content,metadata:m.metadata,createdAt:m.createdAt};n(b=>b.some(g=>g.seq===v.seq)?b:[...b,v])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const d=i.map(u=>__(u,e,s)).filter(u=>u!==null);return c.jsx("div",{className:"px-3 py-2",children:l==="compact"?c.jsx(Nx,{entries:d,isActive:t,onExpand:()=>h("full")}):c.jsx(Dx,{entries:d,isActive:t,onCollapse:()=>h("compact")})})}function as({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function Ds({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function bs({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const xx=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],bx=5,vx=1440;function EM({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Lt(["agent","common"]),[i,n]=k.useState(!1),[a,o]=k.useState(null),[l,h]=k.useState(!1),[d,u]=k.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)}),m=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"){h(!0);return}h(!1),m(Number(p.target.value))},b=()=>{const p=Math.round(Number(d));if(!Number.isFinite(p)||p<bx||p>vx){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}m(p*60*1e3)},g=xx.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),xx.map(p=>c.jsx("option",{value:String(p),children:f(p)},p)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:bx,max:vx,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"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function oh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function yx(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 Sx={0:"0",1:"1",2:"2",3:"3",4:"4"},_x={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},RM={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"},AM={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},nc={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:"🧠"},MM=["all","interaction","task","notification","system"],LM={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"]},NM={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"},DM={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 Su(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 wx(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=Ef(d,e),m=Ef(u,e),v=DM[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:m}),badge:{label:m,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),o=Su(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=Su(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=Su(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 kx({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r,onAgentStateChange:i}){const{t:n}=Lt(["agent","common","team"]),[a,o]=k.useState(null),[l,h]=k.useState(null),[d,u]=k.useState(!0),[f,m]=k.useState("all"),[v,b]=k.useState("all"),[g,O]=k.useState(e??null),[p,x]=k.useState(e??null),[y,S]=k.useState(!1),[w,T]=k.useState(!0),[_,P]=k.useState(null),L=50,N=3,$=k.useCallback(async(Q=!0)=>{Q&&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:L,category:A,status:B})]);o(q),h(H),T((H.history?.length??0)>=L)}catch{}u(!1)},[s,f,v]),R=k.useCallback(async()=>{if(!l)return;const Q=f==="all"?void 0:f,A=v==="all"?void 0:v;try{const B=await K.agents.getMailbox(s,{limit:L,offset:l.history.length,category:Q,status:A});h(q=>q?{...q,history:[...q.history,...B.history]}:B),T((B.history?.length??0)>=L)}catch{}},[s,l,f,v]);k.useEffect(()=>{O(e??null),x(e??null),$()},[$,e]);const D=k.useRef(!1);if(k.useEffect(()=>{if(!p||d)return;if(l?.history?.some(A=>A.id===p)){D.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 w&&!D.current&&(D.current=!0,(async()=>{let A=l?.history??[],B=w;for(;B;)try{const q=await K.agents.getMailbox(s,{limit:L,offset:A.length}),H=[...A,...q.history];A=H,B=(q.history?.length??0)>=L;const te=q.history.some(de=>de.id===p);if(h(de=>de?{...de,history:H}:q),T(B),te||!B)break}catch{break}D.current=!1})())},[p,d,l,w,s]),k.useEffect(()=>{let Q=null;const A=q=>{q.payload?.agentId===s&&(Q&&clearTimeout(Q),Q=setTimeout(()=>{Q=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()=>{Q&&clearTimeout(Q),B.forEach(q=>q())}},[s,$]),d&&!a)return c.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 Q=a?.attentionState??"idle";return Q==="deciding"||Q==="idle"&&V>0?"deciding":Q!=="idle"&&!a?.currentFocus?"idle":Q})(),z=Z==="idle"&&l?.history?.some(Q=>Q.status==="processing"),J=(a?.attentionState??"idle")==="idle"&&V>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${AM[Z]??"bg-gray-500/20 text-gray-500"}`,children:n(`agent:profilePage.mind.attention.${Z}`)}),a?.currentFocus?(()=>{const Q=wx({id:a.currentFocus.mailboxItemId,sourceType:a.currentFocus.type,payload:{summary:a.currentFocus.label,taskId:a.currentFocus.taskId},metadata:{},queuedAt:a.currentFocus.startedAt},n);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[nc[a.currentFocus.type]??"●"," ",c.jsx("span",{className:"text-fg-primary font-medium",children:Q.title}),Q.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:Q.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:n("agent:profilePage.mind.since",{time:new Date(a.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>P(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?c.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"?c.jsx("span",{className:"text-sm text-amber-500",children:n("agent:profilePage.mind.decidingWaiting",{count:V})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:n("agent:profilePage.mind.idleWaiting")}),c.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&t==="offline"&&c.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")&&c.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")]}),c.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&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600",children:n("agent:profilePage.mind.staleProcessingWarning")})]}),(a?.queuedItems?.length??0)>0&&(()=>{const Q=a.queuedItems,A=Q.length>N,B=A&&!y?Q.slice(0,N):Q,q=Q.reduce((H,te)=>(H[te.sourceType]=(H[te.sourceType]??0)+1,H),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.queue",{count:Q.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(q).map(([H,te])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[nc[H]??"●"," ",te]},H))})]}),c.jsxs("div",{className:"space-y-1",children:[B.map((H,te)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:te+1}),c.jsx("span",{className:"text-sm",children:nc[H.sourceType]??"●"}),c.jsx("span",{className:`text-[10px] ${_x[H.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${Sx[H.priority]??H.priority}`,{defaultValue:`P${H.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:H.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(H.queuedAt).toLocaleTimeString()})]},H.id)),A&&c.jsx("button",{onClick:()=>S(!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:Q.length-N})})]})]})})()]}),(a?.notebook?.length??0)>0&&c.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{open:!0,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),c.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[a.notebook.length," ",a.notebook.length===1?"entry":"entries"]})]}),c.jsx("div",{className:"mt-2 space-y-2",children:a.notebook.map(Q=>{const A=Date.now()-Q.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=Q.managed==="system"?"text-blue-400":Q.managed==="cpp"?"text-purple-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:Q.key}),c.jsxs("span",{className:`text-[10px] ${q}`,children:["[",Q.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:B})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:Q.text.length>500?Q.text.slice(0,500)+"…":Q.text})]},Q.key)})})]})}),a?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:n("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:n("agent:profilePage.mind.since",{time:new Date(a.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(qa,{agentId:s,activityId:a.deliberationActivity.activityId,isLive:!0})]}),a?.lastTriage&&(()=>{const A=Date.now()-new Date(a.lastTriage.timestamp).getTime()>6e4;return c.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${A?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!A,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:n("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(a.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:a.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:n("agent:profilePage.mind.processingItem",{id:a.lastTriage.processedItemId.slice(0,12)})}),a.lastTriage.deferredItemIds.length>0&&c.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&&c.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&&c.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})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:n("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:MM.map(Q=>{const A=l?.sourceTypeCounts,B=Q==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?(LM[Q]??[]).reduce((q,H)=>q+(A[H]??0),0):void 0;return c.jsxs("button",{onClick:()=>m(Q),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${f===Q?"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.${Q}`),B!=null&&B>0&&c.jsx("span",{className:"ml-1 opacity-60",children:B})]},Q)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(Q=>{const A=l?.statusCounts,B=Q.key==="all"?A?Object.values(A).reduce((q,H)=>q+H,0):void 0:A?.[Q.key];return c.jsxs("button",{onClick:()=>b(Q.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===Q.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:[Q.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Q.dot}`}),n(`agent:profilePage.mind.statusFilters.${Q.key}`),B!=null&&B>0&&c.jsx("span",{className:"ml-1 opacity-60",children:B})]},Q.key)})}),(!l?.history||l.history.length===0)&&!d&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:n("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:l?.history?.map(Q=>{const A=g===Q.id,B=nc[Q.sourceType]??"●",q=wx(Q,n),H=Q.metadata?.senderName,te=Q.metadata?.senderRole,de=p===Q.id;return c.jsxs("div",{id:`mbx-${Q.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${de?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>O(A?null:Q.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:A?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${NM[Q.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:B}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${A?"":"truncate"}`,children:q.title}),q.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${q.badge.color}`,children:q.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${_x[Q.priority]??"text-fg-tertiary"}`,children:n(`agent:profilePage.mind.priority.${Sx[Q.priority]??Q.priority}`,{defaultValue:""})})]}),q.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${A?"":"truncate"}`,children:q.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(Q.queuedAt).toLocaleString()}),Q.completedAt&&c.jsxs("span",{children:["→ ",new Date(Q.completedAt).toLocaleTimeString()]}),Q.activity&&c.jsxs(c.Fragment,{children:[Q.activity.totalTokens>0&&c.jsx("span",{children:n("agent:profilePage.mind.tokensCount",{count:la(Q.activity.totalTokens)})}),Q.activity.totalTools>0&&c.jsx("span",{children:n("agent:profilePage.mind.toolsCount",{count:Q.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:Q.sourceType}),r&&Q.status==="processing"&&c.jsxs("button",{onClick:we=>{we.stopPropagation(),P(Q.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&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[H&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:H}),te&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",te,")"]})]}),Q.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(Q.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:Q.payload.content}),Q.decisions&&Q.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:n("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:Q.decisions.map(we=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${RM[we.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:we.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:we.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(we.createdAt).toLocaleTimeString()})]},we.id))})]}),Q.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[n("agent:profilePage.mind.activityHeading",{label:Q.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${Q.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:Q.activity.success?n("agent:profilePage.mind.success"):n("agent:profilePage.mind.failed")})]}),Q.activity.type==="task"&&Q.payload?.taskId?c.jsx(jM,{taskId:Q.payload.taskId,isLive:!Q.activity.endedAt}):c.jsx(qa,{agentId:s,activityId:Q.activity.id,isLive:!Q.activity.endedAt})]}):Q.status==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:n("agent:profilePage.mind.processing")}):Q.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:n("agent:profilePage.mind.noActivityLog")}):null]})]},Q.id)})}),w&&(l?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:R,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:n("agent:profilePage.mind.loadEarlier")})})]}),_&&c.jsx(So,{title:n("agent:profilePage.mind.cancelConfirmTitle"),message:n("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:n("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{P(null),K.agents.cancelProcessing(s).then(()=>{let Q=0;const A=()=>{Q+=1,$(),Q<8&&window.setTimeout(A,750)};A()}).catch(()=>{$()})},onCancel:()=>P(null)})]})}function Cx({agentId:s}){const{t:e}=Lt(["agent","common"]),t=ah(),[r,i]=k.useState([]),[n,a]=k.useState(!0),[o,l]=k.useState(null),h=k.useCallback(u=>{t?.openRightPanel?t.openRightPanel({kind:"deliverable",deliverable:u}):l(u)},[t]),d=k.useCallback(async()=>{a(!0);try{const{results:u}=await K.deliverables.search({agentId:s,limit:200});i(u)}catch{i([])}a(!1)},[s]);return k.useEffect(()=>{d()},[d]),k.useEffect(()=>{const u=yt.on("deliverable:created",()=>d()),f=yt.on("deliverable:updated",()=>d()),m=yt.on("deliverable:removed",()=>d());return()=>{u(),f(),m()}},[d]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(u=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},u))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(u=>{const f=y_[u.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},m=Bm[u.status]??Bm.active;return c.jsxs("button",{onClick:()=>h(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:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${f.color}`,children:f.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:u.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${m.color}`,children:u.status})]}),u.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:u.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(u.createdAt).toLocaleDateString()}),u.tags.length>0&&c.jsx("span",{children:u.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},u.id)})]}),o&&c.jsx(S_,{item:o,onClose:()=>l(null),onOpenInPage:u=>{l(null),Qr.navigate(Kt.DELIVERABLES,{openDeliverable:u})}})]})}const IM=k.lazy(()=>Ix(()=>import("./index-ByDm2R2Q.js").then(s=>s.aH),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),Vp=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Px={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Tx({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Lt("team"),[o,l]=k.useState(null),[h,d]=k.useState(null),[u,f]=k.useState("overview"),m=r&&i?i:u,[v,b]=k.useState(""),[g,O]=k.useState(""),[p,x]=k.useState(!1),[y,S]=k.useState(!1),[w,T]=k.useState(""),[_,P]=k.useState(""),L=k.useRef(null),N=k.useRef(null),$=k.useRef(null),R=k.useRef(null),[D,V]=k.useState(!1),[Z,z]=k.useState(!1),[J,Q]=k.useState(""),[A,B]=k.useState(""),[q,H]=k.useState(!1),[te,de]=k.useState([]),we=k.useRef(null),U=k.useCallback(async()=>{try{const Oe=(await K.teams.list()).teams.find(ot=>ot.id===s);Oe&&l(Oe);const He=await K.teams.status(s);de(He.agents)}catch{}},[s]),I=k.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]);k.useEffect(()=>{f("overview"),U(),I()},[s,U,I]),k.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),k.useEffect(()=>{y&&R.current&&R.current.focus()},[y]);const se=async(me,Oe)=>{V(!0);try{await K.teams.updateFile(s,me,Oe),me==="ANNOUNCEMENT.md"?(b(Oe),x(!1)):(O(Oe),S(!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 c.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"),ke=te.filter(me=>me.status!=="offline").length,Le=m==="announcements"&&p||m==="norms"&&y;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Le?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Le?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[m==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const Oe=te.find(Pt=>Pt.id===me.id),He=Px[Oe?.status??"offline"]??"bg-gray-500",ot=me.type==="agent";return c.jsxs("div",{onClick:()=>ot&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ot&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:me.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Oe?.status??"offline"}),me.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),ot&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),m==="announcements"&&c.jsx(oc,{content:v,draft:w,setDraft:T,editing:p,setEditing:x,textareaRef:N,contentRef:L,saving:D,onSave:()=>se("ANNOUNCEMENT.md",w),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),m==="norms"&&c.jsx(oc,{content:g,draft:_,setDraft:P,editing:y,setEditing:S,textareaRef:R,contentRef:$,saving:D,onSave:()=>se("NORMS.md",_),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),m==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:we,value:J,onChange:me=>Q(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}),c.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"}),c.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{Q(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?c.jsxs("div",{className:"space-y-2",children:[c.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}),c.jsxs("div",{className:"flex gap-2",children:[c.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"}),c.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"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Qx,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const be=u==="announcements"&&p||u==="norms"&&y;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${be?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[ke," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:me}=await K.teams.getFilesMap(o.id),Oe=o.members.filter(ot=>ot.type==="agent"),He={type:"team",name:Lx(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Oe.map(ot=>({name:ot.name,roleName:ot.role,role:ot.agentRole??"worker",count:1,skills:[]}))}};await Lf.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:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Vp.map(me=>c.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))})]}),c.jsxs("div",{className:`${be?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[u==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:ee?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(me=>{const Oe=te.find(Pt=>Pt.id===me.id),He=Px[Oe?.status??"offline"]??"bg-gray-500",ot=me.type==="agent";return c.jsxs("div",{onClick:()=>ot&&n?.(me.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ot&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(js,{name:me.name,avatarUrl:me.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:me.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Oe?.status??"offline"}),me.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[me.role," · ",me.type]})]}),ot&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},me.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),u==="announcements"&&c.jsx(oc,{content:v,draft:w,setDraft:T,editing:p,setEditing:x,textareaRef:N,contentRef:L,saving:D,onSave:()=>se("ANNOUNCEMENT.md",w),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements")}),u==="norms"&&c.jsx(oc,{content:g,draft:_,setDraft:P,editing:y,setEditing:S,textareaRef:R,contentRef:$,saving:D,onSave:()=>se("NORMS.md",_),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms")}),u==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Z?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:we,value:J,onChange:me=>Q(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}),c.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"}),c.jsx("button",{onClick:()=>z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{Q(o.name),z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),q?c.jsxs("div",{className:"space-y-2",children:[c.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}),c.jsxs("div",{className:"flex gap-2",children:[c.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"}),c.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"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{B(o.description??""),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Qx,{teamId:s,teamName:o.name,onDeleted:e})]})]}),h&&c.jsx(So,{alertOnly:!0,variant:h.variant??"primary",title:h.title,message:h.message,onConfirm:()=>d(null),onCancel:()=>d(null)})]})}function oc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:u=>t(u.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:u=>{u.key==="Enter"&&(t(s),i(!0))},children:s.trim()?c.jsx(k.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(IM,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Qx({teamId:s,teamName:e,onDeleted:t}){const[r,i]=k.useState(!1),[n,a]=k.useState(!1),[o,l]=k.useState(!1),[h,d]=k.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await 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:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function ac(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 h=this.mergeDbWithCache(r,n?i:void 0);return this.msgBuffers.set(e,h),this.loadingSession=t,this.completeLoad(e),{displayChanged:!0,newMessages:h}}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,h)=>l+h.text.length,0),n=t.reduce((l,h)=>l+h.text.length,0);if(i>n)return!0;const a=r.reduce((l,h)=>l+(h.segments?.length??0),0),o=t.reduce((l,h)=>l+(h.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 kt=bi.NEW_CHAT_ID;function BM(s){const e=k.useRef(new bi),[t,r]=k.useState(s??[]),[i,n]=k.useState(!1),[a,o]=k.useState([]),l=k.useRef(null);k.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const h=k.useCallback((p,x,y)=>{const S=e.current.updateMessages(p,x,y);S.displayChanged&&S.newMessages&&r(S.newMessages)},[]),d=k.useCallback((p,x,y)=>{e.current.updateMessages(p,x,y).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const w=e.current.getMessages(p);w&&e.current.currentConvKey===p&&r([...w])}))},[]),u=k.useCallback((p,x,y)=>{const S=e.current.appendActivity(p,x,y);S.displayChanged&&S.newActivities&&o(S.newActivities)},[]),f=k.useCallback(p=>e.current.getPhase(p),[]),m=k.useCallback(p=>e.current.beginLoad(p),[]),v=k.useCallback(p=>e.current.beginStream(p),[]),b=k.useCallback(p=>e.current.endStream(p),[]),g=k.useCallback(p=>{e.current.resetConv(p),e.current.deleteBuffer(p)},[]),O=k.useCallback(async(p,x,y)=>{e.current.loadingSession=p,e.current.beginLoad(x);try{const S=await y(),w=e.current.applyLoadResult(x,p,S.messages);return w.displayChanged&&w.newMessages&&r(w.newMessages),{count:S.messages.length,hasMore:S.hasMore,oldestCursor:S.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:h,updateConvMsgsRaf:d,appendConvActivity:u,getPhase:f,beginLoad:m,beginStream:v,endStream:b,resetConv:g,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 WM({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Lt("team"),[n,a]=k.useState(!1),[o,l]=k.useState("agent"),[h,d]=k.useState(""),[u,f]=k.useState(!1),[m,v]=k.useState([]),[b,g]=k.useState(null),O=k.useRef(null),p=k.useCallback(async()=>{f(!0);try{const _=await fetch("/api/settings/llm",{credentials:"include"});if(!_.ok)throw new Error(`HTTP ${_.status}`);const P=await _.json(),L=P.providers?.markus;if(L?.configured&&L.enabled!==!1&&(!L.models||L.models.length===0))try{const D=await fetch("/api/models/live/markus",{credentials:"include"});if(D.ok){const V=await D.json();V.models?.length&&(L.models=V.models)}}catch{}const N=[];for(const[D,V]of Object.entries(P.providers??{})){if(!V.configured||V.enabled===!1)continue;const Z=(V.models??[]).map(z=>({id:z.id,name:z.name}));Z.length!==0&&N.push({provider:D,displayName:V.displayName??D,models:Z})}N.sort((D,V)=>D.displayName.localeCompare(V.displayName)),v(N);const $=D=>!D?.provider||!D.model?!1:!!N.find(Z=>Z.provider===D.provider)?.models.some(Z=>Z.id===D.model);let R=null;if(P.routingDefaultModel?.provider&&P.routingDefaultModel?.model)R={provider:P.routingDefaultModel.provider,model:P.routingDefaultModel.model};else if(P.defaultProvider){const D=P.providers?.[P.defaultProvider];D?.model&&(R={provider:P.defaultProvider,model:D.model})}if(R&&!$(R)){const D=N.find(Z=>Z.provider==="markus"),V=D?.models[0]?{provider:"markus",model:D.models[0].id}:N[0]?.models[0]?{provider:N[0].provider,model:N[0].models[0].id}:null;V?(R=V,K.settings.updateRouting({defaultProvider:V.provider,routingDefaultModel:V}).catch(()=>{})):R=null}g(R)}catch{v([])}finally{f(!1)}},[]);k.useEffect(()=>{p()},[p]),k.useEffect(()=>{n&&(l("agent"),d(""),p())},[n,p]),k.useEffect(()=>{if(!n)return;const _=P=>{O.current?.contains(P.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=k.useMemo(()=>{const _=h.trim().toLowerCase();return m.map(P=>({...P,models:_?P.models.filter(L=>L.id.toLowerCase().includes(_)||(L.name?.toLowerCase().includes(_)??!1)||P.displayName.toLowerCase().includes(_)||P.provider.toLowerCase().includes(_)):P.models})).filter(P=>P.models.length>0)},[m,h]),y=k.useCallback(_=>!_?.provider||!_.model?!1:m.length===0?!0:!!m.find(L=>L.provider===_.provider)?.models.some(L=>L.id===_.model),[m]);k.useEffect(()=>{if(!s||m.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const P=m.find(L=>L.provider==="markus");return P?.models[0]?{provider:"markus",model:P.models[0].id}:m[0]?.models[0]?{provider:m[0].provider,model:m[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!1})},[s,m,b,y,e]);const S=s&&y(s)?s:b,T=(S?.model?S.model.includes("/")?S.model.split("/").pop():S.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:O,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(_=>!_),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:S?`${S.provider}: ${S.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:T}),c.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&c.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:[c.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[c.jsx("input",{autoFocus:!0,value:h,onChange:_=>d(_.target.value),placeholder:i("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"}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),c.jsx("button",{type:"button",role:"switch","aria-checked":o==="global",disabled:!t,onClick:()=>l("global"),className:`relative w-9 h-5 rounded-full transition-colors ${o==="global"?"bg-brand-600":"bg-fg-tertiary/30 disabled:opacity-40"}`,children:c.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${o==="global"?"translate-x-4":""}`})})]}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"})}),c.jsx("button",{type:"button",role:"switch","aria-checked":o==="agent",disabled:!t,onClick:()=>l("agent"),className:`relative w-9 h-5 rounded-full transition-colors ${o==="agent"?"bg-brand-600":"bg-fg-tertiary/30 disabled:opacity-40"}`,children:c.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${o==="agent"?"translate-x-4":""}`})})]}),!t&&c.jsx("div",{className:"px-0.5 text-[10px] text-fg-tertiary",children:i("chatModel.noAgent",{defaultValue:"Select an agent to apply per-agent"})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[u&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!u&&x.length===0&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!u&&x.map(_=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:_.displayName}),_.models.slice(0,80).map(P=>{const L=S?.provider===_.provider&&S?.model===P.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:P.id},o),o==="global"&&g({provider:_.provider,model:P.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${L?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:P.id}),L&&c.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${_.provider}:${P.id}`)})]},_.provider))]})]})]})}async function $x(s,e,t,r,i){if(t==="agent"){r&&(s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,null).catch(()=>{}),await K.agents.updateConfig(r,{llmConfig:{modelMode:"custom",primary:e.provider,defaultModel:e.model}}));return}r&&i?.resetCurrentAgent!==!1&&await K.agents.updateConfig(r,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),s&&!s.startsWith("new_")&&await K.sessions.setModelOverride(s,e),await K.settings.updateRouting({defaultProvider:e.provider,routingDefaultModel:{provider:e.provider,model:e.model}})}const jx="markus_team_sidebars_c";function XM(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 qM=["chat","overview","files","tools","memory","deliverables"],zM=["chat","overview","announcements","norms","settings"];function ZM(s,e){if(s==="chat")return e("page.chatTitle");if(Zp.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=Vp.find(i=>i.key===s);return r?e(r.labelKey):s}function VM(s){if(s==="chat")return"💬";const e=Zp.find(r=>r.key===s);if(e)return e.icon;const t=Vp.find(r=>r.key===s);return t?t.icon:""}function fi(s){return s!=="chat"}const Rf=new Set;function FM(){return window.location.hash}function YM(s){return Rf.add(s),()=>{Rf.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Rf.forEach(s=>s()));function cL({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Lt(["team","common"]),a=k.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Mf(Kt.TEAM),[l,h]=k.useState(r?.agents??[]),[d,u]=k.useState(r?.humans??[]),[f,m]=k.useState(!r),v=Af(),b=k.useSyncExternalStore(YM,FM),g=v&&(b.startsWith(`#${Kt.TEAM}/`)||b.startsWith("#chat/")),O=v&&b.match(/^#team\/t\/(.+)$/),p=v?O?"team":g?"chat":"roster":"roster",x=O?O[1]:null,y=k.useRef(Kt.TEAM),S=k.useCallback(()=>{y.current=window.location.hash.slice(1)||Kt.TEAM,window.location.hash=`${Kt.TEAM}/d`},[]),w=k.useCallback(C=>{window.location.hash=`${Kt.TEAM}/t/${C}`},[]);k.useEffect(()=>{if(!v)return;const C=()=>{fi(P.current)&&_("chat")};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[v]);const[T,_]=k.useState("chat"),P=k.useRef("chat");P.current=T;const L=Wm({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[N,$]=k.useState(()=>{try{return localStorage.getItem(jx)==="1"}catch{return!1}}),R=k.useCallback(C=>{$(C);try{localStorage.setItem(jx,C?"1":"0")}catch{}},[]),D=ah(),V=D?.leftCollapsed??!1,Z=D?.rightPanel??null,z=D?.rightPanelTabs??[],J=D?.activeRightPanelTabId??null,Q=D?.rightPanelFullscreen??!1,A=Z?"2xl:pr-8":"2xl:pr-[280px]",B=D?.setHostAvailable,q=D?.collapseRightPanelOnly??D?.toggleRightPanel,H=D?.openRightPanel,te=400,de=320,we=6,[U,I]=k.useState(typeof window<"u"?window.innerWidth:1440),[se,F]=k.useState("auto"),G=k.useRef(V);k.useEffect(()=>{G.current!==V&&(G.current=V,$(V))},[V]);const ee=D?.keyboardPane??"content",ke=k.useRef(!1),Le=k.useRef(ee);k.useEffect(()=>{if(t||v||!o)return;const C=Le.current;Le.current=ee,(ee==="l1"||ee==="l2")&&C!==ee&&N&&($(!1),D?.setLeftCollapsed(!1))},[ee,t,v,o,N,D]),k.useEffect(()=>{if(t||v||!o)return;const C=E=>{const j=D?.keyboardPane??"content";if(j==="l0"||j==="l1"||j==="l2"||E.metaKey||E.ctrlKey||E.altKey)return;if(E.target instanceof HTMLElement){const Y=E.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||E.target.isContentEditable||E.target.closest(".xterm"))return}const W=E.key.length===1?E.key.toLowerCase():E.key;W!=="h"&&W!=="ArrowLeft"||(E.preventDefault(),N&&(R(!1),D?.setLeftCollapsed(!1)),D?.setKeyboardPane(ke.current?"l2":"l1"))};return document.addEventListener("keydown",C,!0),()=>document.removeEventListener("keydown",C,!0)},[t,v,o,D,N,R]),k.useEffect(()=>{if(B)return B(o&&!v),()=>B(!1)},[o,v,B]),k.useEffect(()=>t||v||!o?void 0:yt.on("ui:right_panel",E=>{const j=E.payload;if(j.action==="collapse"){q?.();return}if(j.action!=="open"||!j.panel||!H)return;const W=j.panel;if(W.kind==="url"&&W.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"url",url:W.url,title:W.title||W.url,browserId:Y});return}if(W.kind==="file"&&W.path){H({kind:"file",path:W.path,title:W.title});return}if(W.kind==="terminal"){const Y=W.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;H({kind:"terminal",terminalId:Y,title:W.title||"Terminal",cwd:W.cwd});return}W.kind==="deliverable"&&W.deliverableId&&K.deliverables.get(W.deliverableId).then(Y=>{Y.deliverable&&H({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,q,H]);const be=k.useCallback(C=>{const E=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Mi(j=>[...j,{id:E,...C}]),requestAnimationFrame(()=>cr.current?.focus())},[]),me=k.useCallback(C=>{if(C)try{const E=JSON.parse(C);if(!Array.isArray(E)||E.length===0)return;const j=E.filter(Y=>!!Y&&typeof Y.content=="string"&&Y.content.trim().length>0);if(j.length===0)return;const W=j.map(Y=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:Y.label?.trim()||"Context",content:Y.content}));Mi(Y=>[...Y,...W]),requestAnimationFrame(()=>{const Y=cr.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))})}catch{}},[]),[Oe,He]=k.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ot=Wm({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Pt=k.useRef(null),[pt,qt]=k.useState(!1),[wt,Rt]=k.useState(!1),Tt=k.useCallback(()=>{pt?Rt(C=>!C):He(C=>{const E=!C;try{localStorage.setItem("markus_team_panel_visible",String(E))}catch{}return E})},[pt]);k.useEffect(()=>{if(v)return;const C=Pt.current;if(!C)return;const E=new ResizeObserver(([j])=>{if(!j)return;const W=j.contentRect.width;if(I(W),!t){const Y=W-L.width-ot.width;qt(Y<400)}});return E.observe(C),()=>E.disconnect()},[v,t,L.width,ot.width]);const he=Oe&&!pt&&!wt,Xe=N?0:L.width+we+(he?ot.width+we:0),ge=Math.max(0,U-Xe-we-8),Je=Math.min(te,Math.floor(ge*.4)),Me=Math.max(0,ge-Je),bt=Math.min(Math.round(ge/2),Me),ir=Math.max(0,Math.min(se==="auto"?bt:se,Me)),ts=k.useRef(!1);k.useEffect(()=>{const C=(D?.rightPanel??null)!==null;C&&!ts.current&&($(!0),F("auto")),ts.current=C},[D?.rightPanel]);const Ja=k.useRef(ir);Ja.current=ir;const el=k.useRef(Me);el.current=Me;const tl=k.useCallback(C=>{C.preventDefault();const E=C.clientX,j=Ja.current,W=fe=>{const ie=j+(E-fe.clientX),ve=el.current,ae=Math.min(de,ve);F(Math.max(ae,Math.min(ve,ie)))},Y=()=>{document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",W),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);k.useEffect(()=>{if(!wt)return;const C=E=>{E.target.closest("[data-l2-floating]")||Rt(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[wt]);const[nn,si]=k.useState(null),[To,sl]=k.useState(),[ji,nr]=k.useState(),[Ei,In]=k.useState(!1),[Qo,on]=k.useState(""),[Ch,Lr]=k.useState(!1),[Ri,an]=k.useState(""),or=k.useRef(null),rl=k.useRef(null),vr=k.useCallback((C,E)=>{sl(C),nr(E),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(C??"overview")},[v]),$o=[{id:"chat"},{id:"profile"}],ri=k.useCallback(C=>{C==="profile"?vr():fi(P.current)?history.back():_("chat")},[vr]),Nr=Mx($o,T,ri),us=k.useCallback((C,E)=>{gt("direct"),Yt(C),v&&S(),vr(E?.tab,E?.highlightMailboxId),si(null)},[v,S,vr]),jo=k.useCallback((C,E)=>{const j=l.find(W=>W.name.toLowerCase()===C.toLowerCase());if(j){const W=E.target.getBoundingClientRect();si({agentId:j.id,top:W.bottom,left:W.left})}},[l]),il=k.useMemo(()=>l.map(C=>C.name),[l]),[ne,gt]=k.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[xe,Yt]=k.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[mt,ks]=k.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Ut,ms]=k.useState(""),nl=500,Ai=k.useRef(new Set),Eo=C=>{if(Ai.current.add(C),Ai.current.size>nl){const E=Math.floor(nl*.2),j=Ai.current.values();for(let W=0;W<E;W++){const Y=j.next().value;Y&&Ai.current.delete(Y)}}},ol=k.useMemo(()=>{if(r?.channelMessages){const C=r.activeChannel??"custom:general";return r.channelMessages.filter(E=>E.channel===C).map(E=>_n(E))}},[]),{manager:al,messages:Zt,setMessages:Cs,sending:Ms,setSending:gs,activities:Ph,setActivities:yr,msgBuffers:ss,sessionMsgCache:ar,activeSessionBuffer:ii,actBuffers:Sr,sessionTabsBuffer:Xs,currentConvKeyRef:lt,updateConvMsgs:ft,updateConvMsgsRaf:ni,appendConvActivity:ln,beginLoad:ll,beginStream:cn,endStream:Ps,resetConv:X,loadAndDisplay:le,incrementSending:pe,decrementSending:je,resetSending:Ge,isSendingFor:et,setStreamSession:Ot,clearStreamSession:St,getStreamSession:Ue,saveSessionToCache:ns,restoreSessionFromCache:Ls}=BM(ol),[At,Os]=k.useState(""),[Ht,Ts]=k.useState(null),[_r,Mi]=k.useState([]),[Wt,wr]=k.useState([]),lr=k.useRef(null),[Th,cl]=k.useState(!!r?.streamLastMessage),hn=k.useRef(null),mS=400;k.useEffect(()=>(Ms?(hn.current&&(clearTimeout(hn.current),hn.current=null),cl(!0)):Th&&(hn.current=setTimeout(()=>{cl(!1),hn.current=null},mS)),()=>{hn.current&&clearTimeout(hn.current)}),[Ms]);const Fp=Ms||Th||(()=>{for(let C=Zt.length-1;C>=Math.max(0,Zt.length-8);C--){const E=Zt[C];if(E.isStreaming&&!E.isStopped)return!0}return!1})(),Qh=k.useRef({fullText:"",timers:[]});k.useEffect(()=>{if(!t||!r?.streamLastMessage||Zt.length===0)return;const C=Zt[Zt.length-1];if(!C||C.sender!=="agent")return;const E=C.text;Qh.current.fullText=E;const j=Qh.current.timers;function W(){let fe=0;Cs(ve=>ve.map((ae,ce)=>ce===ve.length-1?{...ae,text:""}:ae)),cl(!0);const ie=setInterval(()=>{if(fe+=1+Math.floor(Math.random()*2),fe>=E.length){clearInterval(ie),Cs(ce=>ce.map((We,Ze)=>Ze===ce.length-1?{...We,text:E}:We));const ve=setTimeout(()=>cl(!1),800);j.push(ve);const ae=setTimeout(W,6e3);j.push(ae)}else Cs(ve=>ve.map((ae,ce)=>ce===ve.length-1?{...ae,text:E.slice(0,fe)}:ae))},30);j.push(ie)}const Y=setTimeout(W,1500);return j.push(Y),()=>{j.forEach(fe=>clearTimeout(fe)),Qh.current.timers=[]}},[]);const Li=k.useRef(0),[Yp,Dr]=k.useState(!1),[$h,Up]=k.useState(!1),[hl,oi]=k.useState(!1),[qs,jh]=k.useState([]),[Hp,Gp]=k.useState(null),Eh=k.useRef(null),cr=k.useRef(null),[dl,dn]=k.useState(null),[gS,Ro]=k.useState(null),Ni=k.useRef(null),Rh=k.useRef(!1),Ao=k.useCallback(()=>{const C=cr.current;if(!C)return;const E=Rh.current,j=E?36:52,W=E?160:120;C.style.height="auto";const Y=Math.max(j,Math.min(C.scrollHeight,W));C.style.height=`${Y}px`,C.style.overflowY=Y>=W?"auto":"hidden"},[]);k.useEffect(()=>{const C=requestAnimationFrame(()=>Ao());return()=>cancelAnimationFrame(C)},[At,qs.length,Ao]);const Ah=C=>{try{const E=localStorage.getItem(`markus_closed_tabs_${C}`);return E?new Set(JSON.parse(E)):new Set}catch{return new Set}},OS=(C,E)=>{const j=Ah(C);j.add(E);try{localStorage.setItem(`markus_closed_tabs_${C}`,JSON.stringify([...j]))}catch{}},xS=(C,E)=>{const j=Ah(C);if(j.delete(E))try{localStorage.setItem(`markus_closed_tabs_${C}`,JSON.stringify([...j]))}catch{}},bS=C=>{try{return localStorage.getItem(`markus_active_session_${C}`)}catch{return null}},ul=(C,E)=>{if(C)try{E&&E!==kt?localStorage.setItem(`markus_active_session_${C}`,E):localStorage.removeItem(`markus_active_session_${C}`)}catch{}},[Mh,Di]=k.useState([]),[Ke,Ir]=k.useState(null),[un,fn]=k.useState(!1),[Kp,Lh]=k.useState([]),[Mo,Nh]=k.useState(null),[vS,Jp]=k.useState(null),[fl,Dh]=k.useState([]),[Bn,Ih]=k.useState(null),[yS,em]=k.useState(null),[tm,Bh]=k.useState([]),[Lo,SS]=k.useState([]),zs=C=>{SS(E=>{const j=typeof C=="function"?C(E):C,W=new Set;return j.filter(Y=>W.has(Y.id)?!1:(W.add(Y.id),!0))})},pl=k.useRef(null),Wh=k.useRef(null),kr=k.useRef(null),[Qs,No]=k.useState(r?.groupChats??[]),Xh=k.useRef(Qs);Xh.current=Qs;const sm=k.useRef(null),[Do,xs]=k.useState(!1),[pn,Io]=k.useState(!1),[rm,Wn]=k.useState(""),[qh,Ii]=k.useState([]),[im,nm]=k.useState(!1),zh=k.useRef(void 0),[Cr,om]=k.useState(r?.teams??[]),[_S,wS]=k.useState([]),[ml,am]=k.useState([]),[kS,CS]=k.useState(null),[UM,HM]=k.useState(!1),[GM,KM]=k.useState(""),[lm,Bo]=k.useState(!1),[cm,PS]=k.useState(""),[Wo,Xn]=k.useState(0),[hm,gl]=k.useState(!1),[dm,TS]=k.useState(""),[Zh,Xo]=k.useState(0),[Vh,QS]=k.useState([]),um=k.useRef(!1),Fh=k.useCallback(()=>{um.current||(um.current=!0,(async()=>{try{const{skills:C}=await K.skills.list();QS(C.map(E=>({name:E.name,description:E.description??E.name})))}catch{}})())},[]);k.useEffect(()=>{Fh()},[Fh]);const mn=dm?Vh.filter(C=>C.name.toLowerCase().includes(dm.toLowerCase())):Vh,[$S,jS]=k.useState([]),fm=k.useRef(!1),ES=k.useCallback(()=>{fm.current||(fm.current=!0,(async()=>{const C=[];try{const[E,j,W,Y,fe]=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 ie of E.projects)C.push({id:ie.id,name:ie.name,entityType:"project",role:ie.status});for(const ie of j.requirements)C.push({id:ie.id,name:ie.title,entityType:"requirement",role:ie.priority});for(const ie of W.tasks)C.push({id:ie.id,name:ie.title,entityType:"task",role:ie.status});for(const ie of Y.results)C.push({id:ie.id,name:ie.title,entityType:"deliverable",role:ie.type});for(const ie of fe.teams)try{const ve=await K.workflows.list(ie.id);for(const ae of ve.workflows)C.push({id:ae.name,name:ae.displayName||ae.name,entityType:"workflow",role:`v${ae.version}`})}catch{}}catch{}jS(C)})())},[]),rs=ne==="channel"?Qs.find(C=>C.channelKey===mt)?.teamId:void 0,RS=k.useRef(null),qn=k.useRef(null),$s=k.useRef(null),pm=k.useRef(void 0),Ol=k.useRef(!1),Br=k.useRef(!0),mm=k.useRef(void 0);k.useEffect(()=>{if(!un)return;const C=E=>{Wh.current&&!Wh.current.contains(E.target)&&pl.current&&!pl.current.contains(E.target)&&fn(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[un]);const xl=(C,E)=>{if(!E||C===E)return`notes:${C}`;const[j,W]=[C,E].sort();return`dm:${j}:${W}`};k.useEffect(()=>{localStorage.setItem("markus_chat_mode",ne)},[ne]),k.useEffect(()=>{localStorage.setItem("markus_chat_agent",xe)},[xe]),k.useEffect(()=>{localStorage.setItem("markus_chat_channel",mt)},[mt]),k.useEffect(()=>{let C=!1;if(t||!xe||ne!=="direct"){Ro(null);return}return K.agents.get(xe).then(E=>{if(C)return;const j=E.config?.llmConfig;Ro(j?.modelMode==="custom"&&j.primary&&j.defaultModel?{provider:j.primary,model:j.defaultModel}:null)}).catch(()=>{C||Ro(null)}),()=>{C=!0}},[xe,ne,t]);const{counts:Yh,sessionAgentMap:qo,markRead:zo,setActiveKey:AS,clearActiveKey:MS}=P_({enabled:!t}),bl=k.useMemo(()=>{const C={};for(const[E,j]of Object.entries(Yh))E.startsWith("channel:")&&(C[E.slice(8)]=j);return C},[Yh]),Uh=T_(qo,Yh);k.useEffect(()=>{let C=0;for(const E of Uh.values())C+=E;for(const E of Object.values(bl))C+=E;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:C}}))},[Uh,bl]);const vl=Uh,LS=k.useCallback(async C=>{for(const[E,j]of Object.entries(qo))j===C&&zo(`session:${E}`)},[qo,zo]);k.useEffect(()=>{if(t||!((!v||p==="chat")&&T==="chat"))return;if(ne==="direct"&&xe&&LS(xe),ne==="channel"&&mt)zo(`channel:${mt}`);else if(ne==="direct"&&Ke)zo(`session:${Ke}`);else if(ne==="dm"&&Ut){const j=`dm:${[e?.id,Ut].sort().join(":")}`;zo(`channel:${j}`)}const E=[];if(ne==="direct"&&Ke){E.push(`session:${Ke}`);for(const[j,W]of Object.entries(qo))W===xe&&E.push(`session:${j}`)}else ne==="channel"&&mt?E.push(`channel:${mt}`):ne==="dm"&&Ut&&e?.id&&E.push(`channel:dm:${[e.id,Ut].sort().join(":")}`);for(const j of E)AS(j);return()=>{for(const j of E)MS(j)}},[t,ne,mt,Ke,Ut,xe,p,T,qo]);const hr=k.useCallback(()=>K.agents.list().then(C=>h(C.agents)).catch(()=>{}),[]),Hs=k.useCallback(()=>K.teams.list().then(C=>om(C.teams)).catch(()=>{}),[]),zn=k.useCallback(()=>K.groupChats.list().then(C=>No(C.chats)).catch(()=>{}),[]),NS=k.useMemo(()=>fd(hr,3e3),[hr]),yl=k.useMemo(()=>fd(Hs,5e3),[Hs]),Hh=k.useMemo(()=>fd(zn,3e3),[zn]),Zo=k.useCallback(()=>{K.users.list(e?.orgId).then(C=>u(C.users)).catch(()=>{})},[e?.orgId]);k.useEffect(()=>{t||(Promise.all([hr(),Hs()]).finally(()=>m(!1)),Zo(),K.tasks.list().then(C=>am(C.tasks)).catch(()=>{}),K.externalAgents.list().then(C=>wS(C.agents)).catch(()=>{}),zn())},[t,Zo]),k.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),u(r.humans??[]),om(r.teams??[]),No(r.groupChats??[]),r.channelMessages)){const C=r.activeChannel??"custom:general";Cs(r.channelMessages.filter(E=>E.channel===C).map(E=>_n(E)))}},[t,r]),k.useEffect(()=>{if(t||!o)return;hr(),Hs();const C=setInterval(hr,3e4),E=setInterval(Hs,6e4),j=yt.on("agent:update",()=>{NS(),yl()}),W=yt.on("team:update",()=>{yl(),Hh()}),Y=yt.on("agent:removed",yl),fe=yt.on("chat:group_created",()=>{zn(),Hs(),hr()}),ie=yt.on("chat:group_updated",Hh),ve=yt.on("chat:group_deleted",()=>{Hh(),yl()}),ae=yt.on("task:update",We=>{const Ze=We?.payload;Ze?.taskId&&am(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(C),clearInterval(E),j(),W(),Y(),fe(),ie(),ve(),ae(),window.removeEventListener("markus:data-changed",ce)}},[t,o,Zo]),k.useEffect(()=>{if(t)return;const C=ce=>{const We=ce.detail;if(X_(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),_("chat"),v&&S(),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(ut=>ut.id===Ze);Te&&Tl(Te)}catch{}},300)}}if(We.params?.selectAgent&&(gt("direct"),Yt(We.params.selectAgent),_("chat"),v&&S()),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"),_("chat"),We.params?.autoSend==="true"?setTimeout(()=>pm.current?.(Ze),300):(Os(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"),_("chat"),me(Ze)}if(We.params?.dm&&(gt("dm"),ms(We.params.dm),_("chat"),v&&S()),We.params?.channel&&(gt("channel"),ks(We.params.channel),_("chat"),v&&S()),We.params?.selectTeam){const Ze=We.params.selectTeam;if(v)w(Ze);else{const Ie=Xh.current.find(Te=>Te.type==="team"&&Te.teamId===Ze);gt("channel"),ks(Ie?.channelKey??`group:${Ze}`),_("chat"),xs(!1),He(!0)}}We.params?.openHire}},E=localStorage.getItem("markus_nav_agentId");if(E){localStorage.removeItem("markus_nav_agentId");const ce=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),gt("direct"),Yt(E),ce?us(E,{tab:ce}):(_("chat"),v&&S())}const j=localStorage.getItem("markus_nav_dm");j&&(localStorage.removeItem("markus_nav_dm"),gt("dm"),ms(j),_("chat"),v&&S());const W=localStorage.getItem("markus_nav_channel");W&&(localStorage.removeItem("markus_nav_channel"),gt("channel"),ks(W),_("chat"),v&&S());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Os(Y),setTimeout(()=>{const ce=cr.current;ce&&(ce.focus(),ce.setSelectionRange(ce.value.length,ce.value.length))},150));const fe=localStorage.getItem("markus_nav_chatChips");fe&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),me(fe));const ie=localStorage.getItem("markus_nav_openDeliverable");ie&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Qr.navigate(Kt.DELIVERABLES,{openDeliverable:ie}):H&&K.deliverables.get(ie).then(ce=>{ce.deliverable&&H({kind:"deliverable",deliverable:ce.deliverable})}).catch(()=>{}));const ve=localStorage.getItem("markus_nav_selectAgent");ve&&(localStorage.removeItem("markus_nav_selectAgent"),gt("direct"),Yt(ve),_("chat"),v&&S());const ae=localStorage.getItem("markus_nav_selectTeam");if(ae)if(localStorage.removeItem("markus_nav_selectTeam"),v)w(ae);else{const ce=Xh.current.find(We=>We.type==="team"&&We.teamId===ae);gt("channel"),ks(ce?.channelKey??`group:${ae}`),_("chat"),xs(!1),He(!0)}return window.addEventListener("markus:navigate",C),()=>window.removeEventListener("markus:navigate",C)},[t]),k.useEffect(()=>{const C=sm.current;if(!C)return;const E=Qs.find(j=>j.type==="team"&&j.teamId===C);sm.current=null,gt("channel"),ks(E?.channelKey??`group:${C}`),_("chat"),xs(!1),He(!0)},[Qs,Cr]),k.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||xe&&l.some(j=>j.id===xe))return;const C=localStorage.getItem("markus_nav_after_remove");if(C&&(localStorage.removeItem("markus_nav_after_remove"),C.startsWith("channel:"))){gt("channel"),ks(C.slice(8)),_("chat");return}const E=l.find(j=>!j.teamId&&j.role?.toLowerCase()==="secretary")??l.find(j=>j.role?.toLowerCase()==="secretary")??l.find(j=>j.name?.toLowerCase().includes("secretary"));E?(gt("direct"),Yt(E.id),_("chat")):l.length>0&&(gt("direct"),Yt(l[0].id),_("chat"))},[l,xe]);const Zn=k.useRef(!1),Pr=k.useRef(!1),Sl=k.useRef(!1),_l=k.useRef(0),Vn=k.useRef(0),[DS,ai]=k.useState(!1),Bi=k.useRef(0),[gm,gn]=k.useState(0),li=k.useCallback(()=>{Pr.current=!1,Sl.current=!1,Br.current=!0},[]),Gh=k.useCallback(()=>{Pr.current=!0,Br.current=!1,Vn.current+=1,Zn.current=!1,ai(!0)},[]),On=k.useCallback(C=>{const E=qn.current;if(!E)return;const j=E.scrollHeight-E.scrollTop-E.clientHeight,W=j<160,Y=j<48,fe=_l.current,ie=E.scrollTop<fe-2;if(_l.current=E.scrollTop,ie&&j>20){Sl.current=!0,Gh();return}if(Sl.current){Y?(li(),ai(!1),Bi.current=0,gn(0)):Gh();return}if(W&&!Pr.current){li(),ai(!1),Bi.current=0,gn(0);return}C?.fromProgrammatic||Zn.current||!Pr.current&&Br.current||Pr.current&&(Br.current=!1,ai(!0))},[Gh,li]);k.useEffect(()=>{const C=qn.current;if(!C)return;const E=()=>{Sl.current=!0},j=()=>{On({fromProgrammatic:Zn.current})};C.addEventListener("wheel",E,{passive:!0}),C.addEventListener("touchmove",E,{passive:!0}),C.addEventListener("scroll",j,{passive:!0});const W=typeof ResizeObserver<"u"?new ResizeObserver(()=>On()):null;return W?.observe(C),_l.current=C.scrollTop,On(),()=>{C.removeEventListener("wheel",E),C.removeEventListener("touchmove",E),C.removeEventListener("scroll",j),W?.disconnect()}},[p,On]);const Kh=k.useMemo(()=>new Set(tm),[tm]),os=k.useMemo(()=>{const C=ne==="channel"?Zt:Zt.filter(E=>!E.isActivityLog);return Kh.size===0?C:C.filter(E=>!(E.isNotification&&Kh.has(E.id)))},[Zt,ne,Kh]);k.useEffect(()=>{Rh.current=T==="chat"&&os.length>0,Ao()},[T,os.length,Ao]);const ci=lw({count:os.length,getScrollElement:()=>qn.current,getItemKey:C=>os[C]?.id??C,estimateSize:C=>{const E=os[C];return E?E.segments&&E.segments.length>0?300:E.text.length>500?200:120:120},overscan:8});ci.shouldAdjustScrollPositionOnItemSizeChange=(C,E,j)=>Xm()?!1:C.start<(j.scrollOffset??0);const hi=k.useCallback((C="instant")=>{if(!Br.current||Pr.current)return;const E=++Vn.current;Zn.current=!0;const j=()=>E===Vn.current&&Br.current&&!Pr.current,W=()=>{if(E!==Vn.current)return;if(Zn.current=!1,!j()){On();return}const Y=qn.current;Y&&(_l.current=Y.scrollTop,Y.scrollHeight-Y.scrollTop-Y.clientHeight<160&&!Pr.current&&(li(),ai(!1),Bi.current=0,gn(0))),requestAnimationFrame(()=>{E===Vn.current&&On({fromProgrammatic:!0})})};if(os.length>0)ci.scrollToIndex(os.length-1,{align:"end",behavior:C}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!j()){E===Vn.current&&(Zn.current=!1);return}ci.scrollToIndex(os.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(W)})});else{const Y=qn.current;Y&&Y.scrollTo({top:Y.scrollHeight,behavior:C}),requestAnimationFrame(W)}},[os.length,ci,On,li]),Om=k.useRef(o);k.useEffect(()=>{Om.current=o},[o]),k.useLayoutEffect(()=>{if(Ol.current){Ol.current=!1;const C=Cl.current;C>0&&(Cl.current=0,ci.scrollToIndex(C,{align:"start",behavior:"instant"}));return}Om.current&&(!Br.current||Pr.current||Xm()||hi())},[Zt,hi,ci]);const xm=k.useRef(T);k.useEffect(()=>{const C=xm.current!=="chat";if(xm.current=T,T==="chat"&&C&&Br.current&&!Pr.current){const E=[],j=requestAnimationFrame(()=>hi("instant"));for(const W of[60,160,320])E.push(setTimeout(()=>hi("instant"),W));return()=>{cancelAnimationFrame(j);for(const W of E)clearTimeout(W)}}},[T,Ms,hi]);const bm=k.useRef(A);k.useEffect(()=>{if(bm.current===A||(bm.current=A,T!=="chat")||os.length===0||Ms||hl||!Br.current||Pr.current)return;const C=[],E=requestAnimationFrame(()=>hi("instant"));for(const j of[60,160,320])C.push(setTimeout(()=>hi("instant"),j));return()=>{cancelAnimationFrame(E);for(const j of C)clearTimeout(j)}},[A,T,os.length,Ms,hl,hi]);const vm=k.useCallback(async(C,E)=>{const j=E??`ch:${C}`;lt.current===j&&oi(!0);try{const W=await K.channels.getMessages(C,50),Y=W.messages.map(fe=>_n(fe,e?.id));ss.set(j,Y),lt.current===j&&(Cs(Y),Dr(W.hasMore),kr.current=W.messages[0]?new Date(W.messages[0].createdAt).toISOString():null)}catch{lt.current===j&&(Cs([]),Dr(!1))}finally{lt.current===j&&oi(!1)}},[]),Jh=k.useCallback(async(C,E)=>{const j=lt.current===E&&(ss.get(E)?.length??0)===0;j&&oi(!0);try{const{count:W,hasMore:Y,oldestCursor:fe}=await le(C,E,async()=>{const ie=await K.sessions.getMessages(C,50);return{messages:Q_(ie.messages.map(pd).filter(ae=>ae.sender!=="agent"||ae.text||ae.segments&&ae.segments.length>0||ae.isStreaming)),hasMore:ie.hasMore,oldestCursor:ie.messages[0]?new Date(ie.messages[0].createdAt).toISOString():null}});return Dr(Y),kr.current=fe,W}finally{j&&lt.current===E&&oi(!1)}},[le,ss]),ym=k.useRef(new Map),wl=k.useRef(new Set),xn=k.useCallback(async(C,E,j)=>{if(!C||!E||E===kt||wl.current.has(E))return;let W=null;try{if($s.current&&!$s.current.signal.aborted&&Ue(j)?.has(E)){cn(j),lt.current===j&&gs(!0);return}const Y=`${C}:${E}`,fe=ym.current.get(Y)??0;if(Date.now()-fe<1500)return;const ie=await K.sessions.streamStatus(C,E),ve=ss.get(j)??[],ae=$_(ve),ce=ie.status==="streaming",We=!!ie.active&&(ie.status==="done"||ie.status==="error")&&!!ae?.isStreaming;if(!ce&&!We)return;ym.current.set(Y,Date.now()),Ni.current?.abort(),W=new AbortController,Ni.current=W,cn(j),gs(!0),Ot(j,E);let Ze=ae?.id;if(!ae||ae.isError)Ze=`reattach_${Date.now()}`,ft(j,ye=>[...ye,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],E);else{const ye=(ae.segments??[]).filter(ze=>ze.type==="tool").map(ze=>ze.status==="stopped"||ze.status==="running"?{...ze,status:"running"}:ze);ft(j,ze=>ze.map(Qe=>Qe.id===ae.id?{...Qe,text:"",isStreaming:!0,isStopped:!1,segments:ye,committedSegments:void 0}:Qe),E)}let Ie=!1;const Te=ye=>{lt.current===j&&(Li.current=Date.now(),ni(j,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(ue=>ue.id===Ze):-1,Ee=De>=0?De:Qe.map((ue,Se)=>({m:ue,j:Se})).reverse().find(ue=>ue.m.sender==="agent"&&ue.m.isStreaming)?.j??-1;if(Ee<0)return ze;const qe=Qe[Ee].segments??[],st=qe[qe.length-1],Mt=st?.type==="text"?st.thinking??"":"";let Gt="",Ns="",oe=ye;for(;oe.length>0;)if(Ie){const ue=oe.indexOf("</think>");ue>=0?(Gt+=oe.slice(0,ue),oe=oe.slice(ue+8),Ie=!1):(Gt+=oe,oe="")}else{const ue=oe.indexOf("<think>");ue>=0?(Ns+=oe.slice(0,ue),oe=oe.slice(ue+7),Ie=!0):(Ns+=oe,oe="")}const Fe=Mt+Gt||void 0,Ce=st?.type==="text"?[...qe.slice(0,-1),{type:"text",content:st.content+Ns,thinking:Fe,createdAt:st.createdAt}]:[...qe,{type:"text",content:Ns,thinking:Fe,createdAt:new Date().toISOString()}];return Qe[Ee]={...Qe[Ee],text:(Qe[Ee].text??"")+Ns,segments:Ce,isStreaming:!0},Qe},E))},ut=ye=>{if(lt.current===j&&(Li.current=Date.now(),ye.phase!=="heartbeat")){if((ye.phase==="start"||ye.phase==="end")&&ln(j,{...ye,phase:ye.phase,ts:Date.now()},E),ye.phase==="start"){const ze=`${ye.tool}_${Date.now()}`,Qe=new Date().toISOString(),De=Ee=>{const qe=[...Ee];for(let st=qe.length-1;st>=0;st--){const Mt=qe[st];if(Mt.type==="tool"&&Mt.tool===ye.tool&&(Mt.status==="running"||Mt.status==="stopped"))return qe[st]={...Mt,status:"running",args:ye.arguments??Mt.args},qe}return qe.push({type:"tool",key:ze,tool:ye.tool,status:"running",args:ye.arguments,createdAt:Qe}),qe};ft(j,Ee=>{const qe=[...Ee],st=Ze?qe.findIndex(oe=>oe.id===Ze):-1;if(st<0)return Ee;const Mt=De(qe[st].segments??[]),Gt=qe[st].committedSegments,Ns=Gt&&De(Gt);return qe[st]={...qe[st],segments:Mt,committedSegments:Ns,isStreaming:!0},qe},E)}else if(ye.phase==="end"){const ze=new Date().toISOString(),Qe=De=>{const Ee=[...De];for(let qe=Ee.length-1;qe>=0;qe--){const st=Ee[qe];if(st.type==="tool"&&st.tool===ye.tool&&(st.status==="running"||st.status==="stopped")){Ee[qe]={...st,status:ye.success===!1?"error":"done",args:ye.arguments??st.args,result:ye.result,error:ye.error,durationMs:ye.durationMs,liveOutput:void 0,createdAt:ze};break}}return Ee};ft(j,De=>{const Ee=[...De],qe=Ze?Ee.findIndex(Ns=>Ns.id===Ze):-1;if(qe<0)return De;const st=Qe(Ee[qe].segments??[]),Mt=Ee[qe].committedSegments,Gt=Mt&&Qe(Mt);return Ee[qe]={...Ee[qe],segments:st,committedSegments:Gt,isStreaming:!0},Ee},E)}else if(ye.phase==="subagent_progress"&&ye.subagentEvent){const ze=Qe=>{const De=[...Qe];for(let Ee=De.length-1;Ee>=0;Ee--){const qe=De[Ee];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){De[Ee]={...qe,status:"running",subagentLogs:qm(qe.subagentLogs,ye.subagentEvent)};break}}return De};ni(j,Qe=>{const De=[...Qe],Ee=Ze?De.findIndex(Gt=>Gt.id===Ze):-1;if(Ee<0)return Qe;const qe=ze(De[Ee].segments??[]),st=De[Ee].committedSegments,Mt=st&&ze(st);return De[Ee]={...De[Ee],segments:qe,committedSegments:Mt,isStreaming:!0},De},E)}}},Be=ye=>{lt.current===j&&(Li.current=Date.now(),ft(j,ze=>{const Qe=[...ze],De=Ze?Qe.findIndex(qe=>qe.id===Ze):-1;if(De<0)return ze;const Ee=[...Qe[De].committedSegments??[]];if(ye.type==="thinking_commit")Ee.push({type:"text",content:"",thinking:ye.content,createdAt:ye.createdAt});else if(ye.type==="text_commit")Ee.push({type:"text",content:ye.content,createdAt:ye.createdAt});else return ze;return Qe[De]={...Qe[De],committedSegments:Ee,isStreaming:!0},Qe},E))},tt=ye=>{if(lt.current!==j)return;Li.current=Date.now();const ze=(ye.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(j,Qe=>{const De=[...Qe],Ee=Ze?De.findIndex(qe=>qe.id===Ze):-1;return Ee<0?Qe:(De[Ee]={...De[Ee],text:ye.content||De[Ee].text,segments:ze,committedSegments:ze,isStreaming:!0,isStopped:!1},De)},E);for(const Qe of ze)Qe.type==="tool"&&ln(j,{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()},E)},rt=await K.sessions.reattachStream(C,E,{onChunk:Te,onActivity:ut,onCommit:Be,onSnapshot:tt},W.signal,0);if(!rt.attached){Ps(j),lt.current===j&&(ft(j,ye=>{const ze=[...ye],Qe=Ze?ze.findIndex(qe=>qe.id===Ze):-1,De=Qe>=0?Qe:ze.map((qe,st)=>({m:qe,j:st})).reverse().find(qe=>qe.m.sender==="agent"&&qe.m.isStreaming)?.j??-1;if(De<0)return ye;const Ee=ze[De];return Ee.isStreaming?(ze[De]={...Ee,isStreaming:!1,isStopped:Ee.isError?Ee.isStopped:!0},ze):ye},E),gs(!1));return}lt.current===j&&(ft(j,ye=>{const ze=[...ye],Qe=Ze?ze.findIndex(st=>st.id===Ze):-1,De=Qe>=0?Qe:ze.map((st,Mt)=>({m:st,j:Mt})).reverse().find(st=>st.m.sender==="agent"&&st.m.isStreaming)?.j??-1;if(De<0)return ye;const Ee=ze[De];if(!Ee.isStreaming)return ye;const qe=rt.segments?.length?zm(rt.segments,Ee.segments):void 0;return ze[De]={...Ee,text:rt.content||Ee.text,isStreaming:!1,isStopped:!1,...qe?{segments:qe,committedSegments:qe}:{}},ze},E),gs(!1)),Ps(j),Ni.current===W&&(Ni.current=null)}catch(Y){if(Ni.current===W&&(Ni.current=null),Ps(j),lt.current===j&&gs(!1),Y instanceof Error&&Y.name==="AbortError")return}},[ln,cn,Ps,Ue,ss,Ot,ft,ni]);k.useEffect(()=>{if(!o||t||ne!=="direct"||!xe)return;const C=Ke;!C||C===kt||xn(xe,C,lt.current)},[o,t,ne,xe,Ke,xn]);const kl=k.useCallback(async C=>{if(!C)return Di([]),[];try{const{sessions:E}=await K.sessions.listByAgent(C,10);return Di(E),E}catch{return Di([]),[]}},[]),Cl=k.useRef(0),IS=k.useCallback(async()=>{if(!($h||!Yp||!kr.current)){Up(!0);try{const C=lt.current;if(ne==="channel"||ne==="dm"){const E=ne==="dm"?xl(e?.id??"",Ut):mt,j=await K.channels.getMessages(E,50,kr.current),W=j.messages.map(Y=>_n(Y,e?.id));Cl.current=W.length,Ol.current=!0,Cs(Y=>{let fe=[...W,...Y];return fe.length>500&&(fe=fe.slice(-500)),ss.set(C,fe),fe}),Dr(j.hasMore),j.messages[0]&&(kr.current=new Date(j.messages[0].createdAt).toISOString())}else if(Ke){const E=await K.sessions.getMessages(Ke,50,kr.current),j=E.messages.map(pd);Cl.current=j.length,Ol.current=!0,Cs(W=>{let Y=[...j,...W];return Y.length>500&&(Y=Y.slice(-500)),ss.set(C,Y),Y}),Dr(E.hasMore),E.messages[0]&&(kr.current=new Date(E.messages[0].createdAt).toISOString())}}catch{}finally{Up(!1)}}},[$h,Yp,ne,mt,Ke,e?.id,Ut]);mm.current=IS;const ed=k.useRef(!1),BS=k.useCallback(C=>{ed.current||(ed.current=!0,requestAnimationFrame(()=>{ed.current=!1,C.target.scrollTop<100&&mm.current?.()}))},[]);k.useEffect(()=>{if(t)return;const C=ac(ne,xe,mt,Ut),E=lt.current;lt.current=C,E&&E!==C&&(Xs.set(E,Lo),Ke&&ii.set(E,Ke)),E!==C&&(li(),ai(!1),Bi.current=0,gn(0));const j=ss.get(C),W=Xs.get(C),Y=ii.get(C),fe=Ue(C),ie=Y??Ke,ve=et(C)&&(ne!=="direct"||!fe||!ie||fe.has(ie)),ae=ie??C,ce=Sr.get(ae)??[];if(yr(ve?ce:[]),gs(ve),ne==="direct"&&xe&&kl(xe),W&&W.length>0&&zs(W),fn(!1),j!==void 0&&j.length>0)if(ve||al.completeLoad(C),oi(!1),Cs(j),Dr(!1),Y!==void 0&&Ir(Y),(!W||W.length===0)&&zs([]),ne==="channel"||ne==="dm"){const Ze=ne==="dm"?xl(e?.id??"",Ut):mt;vm(Ze,C)}else ne==="direct"&&xe&&Y&&Y!==kt&&(ve?xn(xe,Y,C):Jh(Y,C).then(()=>{lt.current===C&&xe&&xn(xe,Y,C)}));else if(ll(C),oi(!0),Cs([]),Dr(!1),kr.current=null,ss.delete(C),ne==="channel"||ne==="dm"){const Ze=ne==="dm"?xl(e?.id??"",Ut):mt;vm(Ze,C),(!W||W.length===0)&&zs([])}else ne==="direct"&&xe?kl(xe).then(Ze=>{if(lt.current===C)if(Ze.length>0){const Ie=Ze.find(De=>De.isMain),Te=Ah(xe),ut=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=W&&W.length>0?W:ut;const tt=bS(xe),rt=Y!==void 0?Y:tt??Ie?.id??Be[0].id;if(rt&&rt!==kt&&!Be.some(De=>De.id===rt)){const De=Ze.find(Ee=>Ee.id===rt);De&&(Be=[...Be,De])}const ye=rt&&Be.some(De=>De.id===rt)?rt:Be[0].id;Ir(ye),ii.set(C,ye),ul(xe,ye),zs(Be);const Qe=Ze.find(De=>De.id===ye)?.metadata?.modelOverride;dn(Qe?.provider&&Qe?.model?{provider:Qe.provider,model:Qe.model}:null),Jh(ye,C).then(()=>{lt.current===C&&xe&&xn(xe,ye,C)})}else Ir(null),dn(null),oi(!1),(!W||W.length===0)&&zs([])}).catch(()=>{lt.current===C&&oi(!1)}):oi(!1)},[t,ne,xe,mt,Ut,n.language,i]),k.useEffect(()=>t?void 0:yt.on("chat:message",E=>{const j=E.payload,W=j.channel??"";if(!W)return;const Y=j.senderType??"agent",fe=j.text??j.message??"",ie=j.senderId??j.agentId??"",ve=j.senderName??j.agentId??i("page.fallbackAgent"),ae=j.metadata,ce=j.messageId??j.id??"";if(ce&&Ai.current.has(ce))return;const We=Y==="human"&&ie===(e?.id??""),Ze={id:ce||`ws_${Date.now()}_${ie}`,sender:We?"user":"agent",text:fe,time:new Date().toLocaleTimeString(),agentName:We?void 0:ve,agentId:We?void 0:ie,replyToId:j.replyToId??void 0,replyToSender:j.replyToSender??void 0,replyToText:j.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 ut=0;ut<ae.toolCalls.length;ut++){const Be=ae.toolCalls[ut];Te.push({type:"tool",key:`${Be.tool}_${ut}`,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:fe}),Ze.segments=Te)}let Ie;if(W.startsWith("notes:"))Ie=`dm:${W.slice(6)}`;else if(W.startsWith("dm:")){const Te=W.slice(3).split(":");Ie=`dm:${Te.find(Be=>Be!==(e?.id??""))??Te[0]??""}`}else Ie=`ch:${W}`;ft(Ie,Te=>[...Te,Ze]),Ie===lt.current&&!Br.current&&(Bi.current+=1,gn(Bi.current),ai(!0)),Y==="agent"&&Ie===`ch:${mt}`&&wr(Te=>{const ut=Te.filter(Be=>Be.id!==ie);return ut.length===0&&lr.current&&(clearTimeout(lr.current),lr.current=null),ut})}),[t,ft,e?.id,mt]),k.useEffect(()=>t?void 0:yt.on("chat:agent_no_response",E=>{const j=E.payload,W=j.channel??"",Y=j.agentId??"";W&&Y&&`ch:${mt}`==`ch:${W}`&&wr(fe=>{const ie=fe.filter(ve=>ve.id!==Y);return ie.length===0&&lr.current&&(clearTimeout(lr.current),lr.current=null),ie})}),[t,mt]),k.useEffect(()=>t?void 0:yt.on("chat:proactive_message",E=>{const j=E.payload,W=j.targetUserId;if(W&&W!==e?.id)return;const Y=j.agentId??"",fe=j.agentName??i("page.fallbackAgent"),ie=j.message??"",ve=j.sessionId??"",ae=j.messageId??"",ce=j.metadata??{};if(!Y||!ie||ie==="[cancelled]"||ie==="[Stream cancelled]")return;const We=ce.role==="user",Ze=!We&&(!!ce.activityLog||ie.startsWith("[ACTIVITY:")),{cleaned:Ie,priority:Te}=j_(ie),ut=!We&&(!!ce.notifyUser||Ie!==ie),Be=ac("direct",Y,"","");if(ve&&lt.current===Be){const qe=Ke;if(qe&&qe!==kt&&qe!==ve)return}const tt=!!ce.isMainSession&&!We,rt=ve||Ke,ye=typeof ce.userText=="string"?ce.userText:"",ze=typeof ce.userMessageId=="string"?ce.userMessageId:"",Qe=typeof ce.createdAt=="string"&&ce.createdAt||(typeof E.timestamp=="string"?E.timestamp:void 0)||new Date().toISOString(),De=(()=>{try{return new Date(Qe).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Ee={id:ae||`proactive_${Date.now()}`,sender:We?"user":"agent",text:Ie,time:De,rawCreatedAt:Qe,...We?{}:{agentName:fe,agentId:Y,...ut?{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}:{}}};ut&&Ee.id&&Bh(qe=>qe.includes(Ee.id)?qe:[...qe,Ee.id]),ft(Be,qe=>{if(qe.some(Mt=>Mt.id===Ee.id))return qe;let st=qe;if(!We&&ye&&(st.some(Gt=>ze&&Gt.id===ze||Gt.sender==="user"&&Gt.text===ye)||(st=Zm(st,{id:ze||`feishu_user_${Ee.id}`,sender:"user",text:ye,time:new Date().toLocaleTimeString(),rawCreatedAt:Ee.rawCreatedAt}))),tt)for(let Mt=st.length-1;Mt>=0;Mt--){const Gt=st[Mt];if(Gt.sender==="agent"&&Gt.agentId===Y&&Gt.isStopped){const Ns=[...st];return Ns[Mt]={...Ee,id:Gt.id},Ns}}return Zm(st,Ee)},rt||void 0)}),[t,ft,i,Ke]),ml.find(C=>C.id===kS),k.useEffect(()=>{CS(null)},[xe]);const WS=C=>Z_(C),XS=()=>{const C=ne==="direct"?xe:null;C&&K.agents.cancelProcessing(C).catch(()=>{}),$s.current?.abort(),$s.current=null,Ni.current?.abort(),Ni.current=null,C&&Ke&&Ke!==kt&&wl.current.add(Ke);const E=lt.current;Ge(E),Sr.delete(Ke??E),Ke&&St(E,Ke),Ps(E),gs(!1),yr([])},[bn,td]=k.useState(null),[Sm,_m]=k.useState(!1),wm=k.useRef(null),vn=async(C,E)=>{const j=!C&&_r.length>0?_r.map(Ie=>Ie.content).join(`
75
75