@markus-global/cli 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/markus.mjs +31 -8
  2. package/dist/web-ui/assets/{AsyncState-_UC7xcxJ.js → AsyncState-BTLUPIr1.js} +1 -1
  3. package/dist/web-ui/assets/{ChatComponents-Ca9tWI9W.js → ChatComponents-DTB3H_n2.js} +1 -1
  4. package/dist/web-ui/assets/{ContentRenderer-C-V5k_3K.js → ContentRenderer-BZXRiKE3.js} +2 -2
  5. package/dist/web-ui/assets/{DeliverableShareModal-BvpyowYJ.js → DeliverableShareModal-BwZP39nd.js} +1 -1
  6. package/dist/web-ui/assets/{Deliverables-CQnWqbTb.js → Deliverables-3Y3zjT_1.js} +1 -1
  7. package/dist/web-ui/assets/{MarkdownMessage-DedA8Zob.js → MarkdownMessage-DVfFMzM9.js} +1 -1
  8. package/dist/web-ui/assets/{Search-CVYQIy_D.js → Search-BI3hk-5j.js} +1 -1
  9. package/dist/web-ui/assets/{SendToChat-IOAvuta-.js → SendToChat-D_5zHO-k.js} +1 -1
  10. package/dist/web-ui/assets/{Settings-BQDqf4q5.js → Settings-DTUjLhJY.js} +1 -1
  11. package/dist/web-ui/assets/{Store-BEsLd_RN.js → Store-B8ksRjHF.js} +1 -1
  12. package/dist/web-ui/assets/{Switch-C6InTNUi.js → Switch-RmZHA47D.js} +1 -1
  13. package/dist/web-ui/assets/{Team-nfNyWj-s.js → Team-BRgI1zM9.js} +4 -4
  14. package/dist/web-ui/assets/{Work-BQvgkynj.js → Work-nah0UYFz.js} +1 -1
  15. package/dist/web-ui/assets/{arc-DP1Vf7Sx.js → arc-VmvI7TpW.js} +1 -1
  16. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Buq8JYN8.js → architectureDiagram-3BPJPVTR-CTUtPasm.js} +1 -1
  17. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BCa2p2_X.js → blockDiagram-GPEHLZMM-xeYAqtZJ.js} +1 -1
  18. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BxsgggQY.js → c4Diagram-AAUBKEIU-BiFgoGY5.js} +1 -1
  19. package/dist/web-ui/assets/channel-s7K3KXLr.js +1 -0
  20. package/dist/web-ui/assets/{chunk-2J33WTMH-BJZZ60c9.js → chunk-2J33WTMH-DueHBqOn.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-4BX2VUAB-C5hc4E6J.js → chunk-4BX2VUAB-B8zgDfSV.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-55IACEB6-CbyvZ6Mk.js → chunk-55IACEB6-DieD55CP.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-727SXJPM-JmNt9TVA.js → chunk-727SXJPM-Do4Z9LQ0.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BTk0v5ba.js → chunk-AQP2D5EJ-qrYsW5ml.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-FMBD7UC4-BO-dhB1U.js → chunk-FMBD7UC4-BSz3QT1q.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-ND2GUHAM-BdjCcLdb.js → chunk-ND2GUHAM-utDWSydt.js} +1 -1
  27. package/dist/web-ui/assets/{chunk-QZHKN3VN-BAzRC82n.js → chunk-QZHKN3VN-Cd86CYHV.js} +1 -1
  28. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-B2mHhFY8.js +1 -0
  29. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-B2mHhFY8.js +1 -0
  30. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CVffmErT.js → cose-bilkent-S5V4N54A-Dc6cP9WW.js} +1 -1
  31. package/dist/web-ui/assets/{dagre-BM42HDAG-Dd9pB2fX.js → dagre-BM42HDAG-4b0Wf_6D.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-2AECGRRQ-BG_AUqzM.js → diagram-2AECGRRQ-zS_j1Kf4.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-5GNKFQAL-D5qFMRFf.js → diagram-5GNKFQAL-CPo-_Ime.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-KO2AKTUF-B3qTxSWl.js → diagram-KO2AKTUF-CjHOA4_j.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-LMA3HP47-BrxC1636.js → diagram-LMA3HP47-CalZRF6K.js} +1 -1
  36. package/dist/web-ui/assets/{diagram-OG6HWLK6-BvXyEQ9-.js → diagram-OG6HWLK6-DnLAhsLX.js} +1 -1
  37. package/dist/web-ui/assets/{docx-preview-DBAZFeEb.js → docx-preview-uRVPnxwM.js} +1 -1
  38. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CMap9oy_.js → erDiagram-TEJ5UH35-L0nzlMSn.js} +1 -1
  39. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BZerJtvk.js → flowDiagram-I6XJVG4X-Bdc3UwtW.js} +1 -1
  40. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CagPMHMO.js → ganttDiagram-6RSMTGT7-CFRmj_qc.js} +1 -1
  41. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DZ5dDKRu.js → gitGraphDiagram-PVQCEYII-B5hZwcoJ.js} +1 -1
  42. package/dist/web-ui/assets/{index-CKPQYzzR.js → index-TPf50ZeO.js} +6 -6
  43. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CHLdsDUZ.js → infoDiagram-5YYISTIA-DVT4RgPd.js} +1 -1
  44. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-SdeinQaS.js → ishikawaDiagram-YF4QCWOH-Bf7pvUY_.js} +1 -1
  45. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BtlL2fi0.js → journeyDiagram-JHISSGLW-NVRjJlnd.js} +1 -1
  46. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BKPQYXkB.js → kanban-definition-UN3LZRKU-Co7BKMut.js} +1 -1
  47. package/dist/web-ui/assets/{mermaid.core-MkJR6w4B.js → mermaid.core-CCf28Hq6.js} +5 -5
  48. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CbOmHX_u.js → mindmap-definition-RKZ34NQL-DepMhVEb.js} +1 -1
  49. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CypGjJP1.js → pieDiagram-4H26LBE5-Cq9ANaI0.js} +1 -1
  50. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CGtemfUz.js → quadrantDiagram-W4KKPZXB-CUY0BWhQ.js} +1 -1
  51. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-N7YfpCvE.js → requirementDiagram-4Y6WPE33-D9fU5rCm.js} +1 -1
  52. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CYnSrei-.js → sankeyDiagram-5OEKKPKP-CMHhuSQF.js} +1 -1
  53. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CsB7dCPF.js → sequenceDiagram-3UESZ5HK-Bjx53SID.js} +1 -1
  54. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DTDFUXFP.js → stateDiagram-AJRCARHV-DVvatKnO.js} +1 -1
  55. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-92MmE2MZ.js +1 -0
  56. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-C_bWAN9B.js → timeline-definition-PNZ67QCA-9I80LG9m.js} +1 -1
  57. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CX_qAuUT.js → vennDiagram-CIIHVFJN-B82Deutq.js} +1 -1
  58. package/dist/web-ui/assets/{wardley-L42UT6IY-q53jQ293.js → wardley-L42UT6IY-BKXtp57W.js} +1 -1
  59. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D34dKCJU.js → wardleyDiagram-YWT4CUSO-DzqTzfYa.js} +1 -1
  60. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BFAngp66.js → xychartDiagram-2RQKCTM6-TowyDWYu.js} +1 -1
  61. package/dist/web-ui/index.html +1 -1
  62. package/package.json +1 -1
  63. package/dist/web-ui/assets/channel-BTSrOo6c.js +0 -1
  64. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BSYlcnF9.js +0 -1
  65. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BSYlcnF9.js +0 -1
  66. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-AVnDjlzF.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownMessage-DedA8Zob.js","assets/index-CKPQYzzR.js","assets/index-CzHSs0Vd.css"])))=>i.map(i=>d[i]);
2
- import{r as w,a3 as qh,u as yt,aq as Hp,j as c,U as St,k as ie,ar as nC,a as Yp,b as Gp,P as Ht,c as Zo,X as oC,A as As,n as Ar,a4 as Hn,i as Kp,as as aC,at as Jp,au as lC,av as Vv,aw as _O,ax as kO,ay as cC,az as hC,aA as Fv,aB as Uv,aC as dC,aD as uC,aE as fC,aF as CO,aG as pC,aH as mC,aI as gC,aJ as cc,V as PO,Z as OC,Y as xC,h as em,aK as du,aL as bC,aM as vC,d as yC,aN as Hv,aO as SC,aP as jf,ao as Yv,aQ as wC,aR as TO,aS as _C,aT as kC,aU as CC,a2 as PC,_ as Gv,a5 as QO,aV as TC,al as QC,aW as Kv,aX as $O,R as jO,Q as RO,aY as $C,aZ as jC,a_ as uu,a$ as RC,b0 as EC,b1 as EO,E as AO,b2 as AC,b3 as MC,y as LC,W as NC,b4 as DC}from"./index-CKPQYzzR.js";import{MarkdownMessage as vi}from"./MarkdownMessage-DedA8Zob.js";import{t as tm,f as sm,s as IC,a as oh,E as BC,P as Jv,g as WC,d as ah,b as XC,c as fu,p as zC,r as qC,e as MO,h as LO,i as NO,j as ka,k as DO,l as ZC,m as IO,n as Dn,o as Bc,q as Wc,u as VC,v as FC,w as UC,x as BO,y as HC,z as YC,A as GC,B as pu,C as WO,D as KC,F as mu,G as gu,H as JC,I as hc,J as XO,K as e2,L as t2,M as zO,N as s2,O as r2,Q as i2,R as n2,S as o2,T as a2,U as qO,V as l2,W as c2,X as h2,Y as d2}from"./ChatComponents-Ca9tWI9W.js";import{P as ey,E as u2,L as ty,S as f2}from"./AsyncState-_UC7xcxJ.js";import{c as p2,C as sy,o as Rf,p as m2,a as g2,b as O2}from"./chatChips-DVIRVTpT.js";import{ContentRenderer as Ef,resolveFormat as x2}from"./ContentRenderer-C-V5k_3K.js";import{a as b2,c as v2,D as y2}from"./DeliverableShareModal-BvpyowYJ.js";import{i as S2,S as ZO}from"./Switch-C6InTNUi.js";function mo(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let u;t.key&&((o=t.debug)!=null&&o.call(t))&&(u=Date.now());const d=s();if(!(d.length!==r.length||d.some((v,b)=>r[b]!==v)))return i;r=d;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...d),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-u)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownMessage-DVfFMzM9.js","assets/index-TPf50ZeO.js","assets/index-CzHSs0Vd.css"])))=>i.map(i=>d[i]);
2
+ import{r as w,a3 as qh,u as yt,aq as Hp,j as c,U as St,k as ie,ar as nC,a as Yp,b as Gp,P as Ht,c as Zo,X as oC,A as As,n as Ar,a4 as Hn,i as Kp,as as aC,at as Jp,au as lC,av as Vv,aw as _O,ax as kO,ay as cC,az as hC,aA as Fv,aB as Uv,aC as dC,aD as uC,aE as fC,aF as CO,aG as pC,aH as mC,aI as gC,aJ as cc,V as PO,Z as OC,Y as xC,h as em,aK as du,aL as bC,aM as vC,d as yC,aN as Hv,aO as SC,aP as jf,ao as Yv,aQ as wC,aR as TO,aS as _C,aT as kC,aU as CC,a2 as PC,_ as Gv,a5 as QO,aV as TC,al as QC,aW as Kv,aX as $O,R as jO,Q as RO,aY as $C,aZ as jC,a_ as uu,a$ as RC,b0 as EC,b1 as EO,E as AO,b2 as AC,b3 as MC,y as LC,W as NC,b4 as DC}from"./index-TPf50ZeO.js";import{MarkdownMessage as vi}from"./MarkdownMessage-DVfFMzM9.js";import{t as tm,f as sm,s as IC,a as oh,E as BC,P as Jv,g as WC,d as ah,b as XC,c as fu,p as zC,r as qC,e as MO,h as LO,i as NO,j as ka,k as DO,l as ZC,m as IO,n as Dn,o as Bc,q as Wc,u as VC,v as FC,w as UC,x as BO,y as HC,z as YC,A as GC,B as pu,C as WO,D as KC,F as mu,G as gu,H as JC,I as hc,J as XO,K as e2,L as t2,M as zO,N as s2,O as r2,Q as i2,R as n2,S as o2,T as a2,U as qO,V as l2,W as c2,X as h2,Y as d2}from"./ChatComponents-DTB3H_n2.js";import{P as ey,E as u2,L as ty,S as f2}from"./AsyncState-BTLUPIr1.js";import{c as p2,C as sy,o as Rf,p as m2,a as g2,b as O2}from"./chatChips-DVIRVTpT.js";import{ContentRenderer as Ef,resolveFormat as x2}from"./ContentRenderer-BZXRiKE3.js";import{a as b2,c as v2,D as y2}from"./DeliverableShareModal-BwZP39nd.js";import{i as S2,S as ZO}from"./Switch-RmZHA47D.js";function mo(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let u;t.key&&((o=t.debug)!=null&&o.call(t))&&(u=Date.now());const d=s();if(!(d.length!==r.length||d.some((v,b)=>r[b]!==v)))return i;r=d;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...d),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-u)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
3
3
  font-size: .6rem;
4
4
  font-weight: bold;
5
5
  color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function VO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const w2=(s,e)=>Math.abs(s-e)<1.01,_2=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},FO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},k2=s=>s,C2=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},P2=(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(FO(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(FO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},UO={passive:!0},HO=typeof window>"u"?!0:"onscrollend"in window,T2=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&HO?()=>{}:_2(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=u=>()=>{const{horizontal:d,isRtl:f}=s.options;i=d?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,u)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,UO);const h=s.options.useScrollendEvent&&HO;return h&&t.addEventListener("scrollend",l,UO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},Q2=(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"]},$2=(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 j2{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:k2,rangeExtractor:C2,onChange:()=>{},measureElement:Q2,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=mo(()=>(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=mo(()=>[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=mo(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const p of this.laneAssignments.keys())p>=t&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const u=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const d=this.measurementsCache.slice(0,u),f=new Array(o).fill(void 0);for(let p=0;p<u;p++){const v=d[p];v&&(f[v.lane]=p)}for(let p=u;p<t;p++){const v=n(p),b=this.laneAssignments.get(p);let g,O;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const C=f[g],P=C!==void 0?d[C]:void 0;O=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?d[p-1]:this.getFurthestMeasurement(d,p);O=C?C.end+this.options.gap:r+i,g=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),k=O+y;d[p]={index:p,start:O,size:y,end:k,key:v,lane:g},f[g]=p}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=mo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?R2({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=mo(()=>{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=mo(()=>[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 VO(r[ry(0,r.length-1,i=>VO(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&&w2(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 ry=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function R2({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=ry(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(u=>u<t+e);){const u=s[o];l[u.lane]=u.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(u=>u>=t);){const u=s[a];h[u.lane]=u.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const YO=typeof document<"u"?w.useLayoutEffect:w.useEffect;function E2({useFlushSync:s=!0,...e}){const t=w.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?qh.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=w.useState(()=>new j2(r));return i.setOptions(r),YO(()=>i._didMount(),[]),YO(()=>i._willUpdate()),i}function A2(s){return E2({observeElementRect:P2,observeElementOffset:T2,scrollToFn:$2,...s})}function M2(s){return s.questions&&s.questions.length>0?s.questions:s.options&&s.options.length>0?[{id:"q1",prompt:s.description||s.title,inputType:"choice",options:s.options,allowMultiple:!1,allowFreeform:s.allowFreeform}]:[{id:"q1",prompt:s.description||s.title,inputType:"text",allowFreeform:!0}]}function L2({approval:s,submitting:e,readOnly:t,onClose:r,onSubmit:i}){const{t:n}=yt(["team","common"]);Hp(!0);const a=w.useMemo(()=>M2(s),[s]),[o,l]=w.useState(0),[h,u]=w.useState(()=>{if(t&&s.answers&&s.answers.length>0){const C={};for(const P of s.answers)C[P.questionId]={selectedOptionIds:P.selectedOptionIds??[],text:P.text??""};return C}return{}}),d=a[o],f=o===a.length-1,p=a.length>1,v=C=>h[C]??{selectedOptionIds:[],text:""},b=(C,P)=>{u(_=>({..._,[C]:{...v(C),...P}}))},g=(C,P)=>{const _=v(C.id);if(C.allowMultiple){const T=_.selectedOptionIds.includes(P);b(C.id,{selectedOptionIds:T?_.selectedOptionIds.filter(R=>R!==P):[..._.selectedOptionIds,P],text:T?_.text:""})}else{const T=_.selectedOptionIds.includes(P);b(C.id,{selectedOptionIds:T?[]:[P],text:T?_.text:""})}},O=C=>{const P=v(C.id);return C.inputType==="choice"?P.selectedOptionIds.length>0?(C.options??[]).some(T=>T.id&&P.selectedOptionIds.includes(T.id)&&T.requiresFreeform)?P.text.trim().length>0:!0:!!(C.allowFreeform&&P.text.trim()):P.text.trim().length>0},m=a.every(O),x=(d.options??[]).some(C=>C.id&&v(d.id).selectedOptionIds.includes(C.id)&&C.requiresFreeform),y=()=>a.map(C=>{const P=v(C.id),_={questionId:C.id};return P.selectedOptionIds.length>0&&(_.selectedOptionIds=P.selectedOptionIds),P.text.trim()&&(_.text=P.text.trim()),_}),k=()=>{const C=y();let P=!0,_;if(!s.questions?.length&&s.options?.length){const R=C[0];_=R?.selectedOptionIds?.[0]??(R?.text?"custom":void 0),P=_!=="reject"&&_!=="request_changes"}const T=C.map(R=>R.text).filter(Boolean).join(`
@@ -60,7 +60,7 @@ ${de}
60
60
  `)})},[i,s]);w.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const de=navigator.platform.toUpperCase().includes("MAC"),ge=me=>{if(!(de?me.metaKey&&!me.ctrlKey:me.ctrlKey&&!me.metaKey)||!me.shiftKey||me.altKey||me.key.toLowerCase()!=="a")return;const ye=F.current?.getSelection()?.trim();ye&&(me.preventDefault(),Je(ye))};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[s.kind,i,Je]);const lt=w.useCallback(de=>{if(!de.text.trim()||!i)return;const ge=G.current?.querySelector("iframe")?.getBoundingClientRect(),me=(ge?.left??0)+de.rect.x+de.rect.width/2,pe=(ge?.top??0)+de.rect.y;I({x:me,y:pe,text:de.text,htmlMeta:{xpath:de.xpath,cssSelector:de.cssSelector}})},[i]);w.useEffect(()=>{const de=G.current;if(!de||!i)return;const ge=()=>{requestAnimationFrame(()=>{const pe=window.getSelection(),ye=pe?.toString().trim();if(!ye||!pe?.rangeCount){I(null);return}const xe=pe.getRangeAt(0);if(!de.contains(xe.commonAncestorContainer)){I(null);return}const ze=xe.getBoundingClientRect();I({x:ze.left+ze.width/2,y:ze.top,text:ye})})},me=pe=>{const ye=document.getElementById("right-panel-selection-toolbar");ye&&ye.contains(pe.target)||I(null)};return de.addEventListener("mouseup",ge),document.addEventListener("mousedown",me),()=>{de.removeEventListener("mouseup",ge),document.removeEventListener("mousedown",me)}},[i,x.mode]);const Tt=()=>{ie.files.reveal(ke||Me).catch(()=>{})},gt=()=>{navigator.clipboard?.writeText(ke||Me).then(()=>{_(!0),setTimeout(()=>_(!1),1500)}).catch(()=>{})},_t=w.useMemo(()=>{if(!i)return null;const de=ke||Me;if(s.kind==="deliverable"){const ge=s.deliverable;if(!ge.id&&!ge.reference)return null;const me=$e||ge.title||ge.reference||ge.id;return{kind:"deliverable",label:`📄 ${me.length>40?`${me.slice(0,24)}…${me.slice(-12)}`:me}`,content:["[deliverable]",ge.id?`ID: ${ge.id}`:"",ge.title?`Title: ${ge.title}`:"",ge.reference?`Reference: ${ge.reference}`:"",ge.taskId?`Task: ${ge.taskId}`:"",ge.projectId?`Project: ${ge.projectId}`:""].filter(Boolean).join(`
61
61
  `)}}if(s.kind==="file"){if(!de||Oo(de))return null;const ge=$e||de.split(/[/\\]/).pop()||de;return{kind:"file",label:`📄 ${ge.length>40?`${ge.slice(0,24)}…${ge.slice(-12)}`:ge}`,content:["[file]",`Path: ${de}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
62
62
  `)}}return null},[i,s,ke,Me,$e,x]),[Ee,kt]=w.useState(!1),ds=w.useCallback(()=>{_t&&(i?.(_t),kt(!0),setTimeout(()=>kt(!1),1200))},[_t,i]),bt=w.useCallback(async()=>{if(s.kind==="deliverable"){Ar.navigate(Ht.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ge=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const me=await window.markusDesktop.browser.getState(s.browserId);if(me.ok){if(me.directoryPath){await ie.system.openPath(me.directoryPath).catch(()=>ie.files.reveal(me.directoryPath));return}me.url&&me.url!=="about:blank"&&(ge=me.url)}}catch{}if(!ge||ge==="about:blank")return;if(/^https?:\/\//i.test(ge)||/^file:\/\//i.test(ge)){cc(ge);return}await ie.system.openPath(ge).catch(()=>cc(vv(ge)));return}if(s.kind!=="file")return;const de=s.path;if(de){if(/^https?:\/\//i.test(de)||/^file:\/\//i.test(de)){cc(de);return}await ie.system.openPath(de).catch(()=>cc(vv(de)))}},[s]),Et=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,Ot=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),Wt=!!Me&&!Oo(Me)&&(s.kind==="file"||s.kind==="deliverable"),Ae=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!Me&&!Oo(Me)&&!s.deliverable.artifactType&&b2(s.deliverable.format),Lt=s.kind==="deliverable"?{...s.deliverable,hubShareId:M?.id??s.deliverable.hubShareId??null,shareStatus:M?.status??s.deliverable.shareStatus??null,shareUrl:M?.url??s.deliverable.shareUrl??null,shareVisibility:M?.visibility??s.deliverable.shareVisibility??null}:null,it=w.useCallback(de=>{N(de)},[]),At=w.useMemo(()=>v2(PO,em.getUrl()),[]),Qt=s.kind==="deliverable"?s.deliverable.id:null;w.useEffect(()=>{if(!Qt||!PO())return;let de=!1;const ge=async()=>{try{const pe=await At.listMine();if(de)return;const ye=s.kind==="deliverable"?s.deliverable:null;if(!ye)return;const xe=ye.hubShareId&&pe.find(qe=>qe.id===ye.hubShareId)||pe.find(qe=>qe.localId===ye.id);if(!xe)return;N(qe=>qe&&qe.id===xe.id&&qe.status===xe.status?qe:xe);const ze={hubShareId:ye.hubShareId??xe.id??null,shareStatus:xe.status??null,shareUrl:xe.url??null,shareVisibility:ye.shareVisibility??xe.visibility??null};(ye.shareStatus!==ze.shareStatus||ye.hubShareId!==ze.hubShareId||ye.shareUrl!==ze.shareUrl||ye.shareVisibility!==ze.shareVisibility)&&ye.id&&ie.deliverables.update(ye.id,ze).catch(qe=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",qe)})}catch{}};ge();const me=setInterval(ge,3e4);return()=>{de=!0,clearInterval(me)}},[At,Qt,s]);const es=Lt?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!u&&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 ${u?"flex-1 min-w-0":"shrink-0"}`,style:u?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:m("common:browserMode",{defaultValue:"Browser"}),"aria-label":m("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":p==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:m("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":m("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":p==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),_e||h?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0 self-stretch flex flex-col justify-end",children:[c.jsxs("div",{ref:q,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:de=>{const ge=de.currentTarget;ge.scrollWidth<=ge.clientWidth||Math.abs(de.deltaY)<=Math.abs(de.deltaX)||(ge.scrollLeft+=de.deltaY,de.preventDefault())},children:[n?.map(de=>{const ge=de.id===a,me=de.payload.kind==="url"?de.payload.pageId:void 0,pe=de.payload.kind==="terminal"?de.payload.terminalId:void 0,ye=me!=null?V[me]:pe?W[pe]:void 0,xe=ye?`${de.title} — ${m("common:browserTabControlledBy",{name:ye.agentName})}`:de.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ge?ye?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":ye?"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":ge,ref:ge?ee: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:xe,onPointerDown:ze=>{ze.button===0&&(de.id!==a&&!we()||o?.(de.id))},onClick:()=>{de.id!==a&&!we()||o?.(de.id)},children:[ye&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:m("common:browserTabControlledBy",{name:ye.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:ye.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:de.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:ze=>{ze.button===0&&(ze.preventDefault(),ze.stopPropagation(),!(de.id===a&&!we())&&l(de.id))},onClick:ze=>{ze.preventDefault(),ze.stopPropagation(),!(de.id===a&&!we())&&l(de.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ge?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:m("common:closeTab",{defaultValue:"Close tab"}),"aria-label":m("common:closeTab",{defaultValue:"Close tab"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},de.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:m("common:newTab",{defaultValue:"New Tab"}),"aria-label":m("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),c.jsx(rI,{scrollRef:q,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:Me||$e,children:$e}),c.jsxs("div",{"data-no-drag":!0,"data-panel-actions":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[(s.kind==="file"||s.kind==="deliverable")&&c.jsxs("div",{ref:A,className:"relative shrink-0",children:[c.jsx("button",{type:"button",onClick:()=>Z(de=>!de),title:m("common:browserHistoryRecent",{defaultValue:"最近访问"}),"aria-label":m("common:browserHistoryRecent",{defaultValue:"最近访问"}),"aria-haspopup":"listbox","aria-expanded":X,className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${X?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),c.jsx("polyline",{points:"3 4 3 10 9 10"}),c.jsx("polyline",{points:"12 8 12 12 15 14"})]})}),X&&c.jsx(D_,{items:K,query:"",activeIndex:-1,onHover:()=>{},onPick:de=>{Z(!1),N_(de,{openPanel:J?.openRightPanel})},onRemove:de=>le(Uv(Jp(de))),onClear:()=>{Fv(),Z(!1)},anchorClassName:"right-0 top-full mt-1 w-72",keyboardHint:!1})]}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{mt()},title:m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),_t&&c.jsx("button",{type:"button",onClick:ds,title:Ee?m("common:addedToChat",{defaultValue:"Added to chat"}):s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),"aria-label":s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Ee?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:Ee?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h6"}),c.jsx("line",{x1:"17",y1:"3",x2:"17",y2:"9"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"})]})}),Ae&&c.jsxs("button",{type:"button",onClick:()=>R(!0),title:m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${es==="published"?"text-green-500 hover:text-green-400":es==="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"})]}),(es==="published"||es==="pending_review"||es==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${es==="published"?"bg-green-500":es==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),Et&&c.jsx("button",{type:"button",onClick:()=>{bt()},title:Ot,"aria-label":Ot,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"})]})}),Wt&&c.jsx("button",{onClick:gt,title:P?m("common:copied",{defaultValue:"Copied"}):m("common:copyPath",{defaultValue:"复制路径"}),"aria-label":m("common:copyPath",{defaultValue:"复制路径"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${P?"text-green-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:P?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),Wt&&c.jsx("button",{onClick:Tt,title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),d&&c.jsx("button",{onClick:d,title:u?m("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):m("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:u?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:()=>{we()&&e()},title:m("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":m("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="directory"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[k&&x.mode!=="directory"&&x.mode!=="loading"&&c.jsx("div",{className:"shrink-0 mb-2",children:c.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-fg-secondary hover:text-brand-500 transition-colors cursor-pointer",onClick:()=>C(hI(ke)),children:[c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 20 20",fill:"currentColor",children:c.jsx("path",{fillRule:"evenodd",d:"M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z",clipRule:"evenodd"})}),"返回上级目录"]})}),x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${Pf(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?` · ${Pf(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[m("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${Pf(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{ie.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="office"&&c.jsx("div",{ref:G,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(OC,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{ie.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const de=Me?Me.replace(/[/\\][^/\\]+$/,""):void 0,ge=Me&&!Oo(Me)?Me:"",me=x.format;return ge&&(me==="code"||me==="json"||me==="text")?c.jsx("div",{ref:G,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(j_,{path:ge,initialContent:x.content,language:dg(ge,me),onDirtyChange:B})}):ge&&(me==="markdown"||me==="html")?c.jsx("div",{ref:G,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(RD,{path:ge,content:x.content,format:me,basePath:de,onHtmlSelection:lt,onDirtyChange:B,copyVariant:"preview"})}):c.jsx("div",{ref:G,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(Ef,{content:x.content,format:me,className:"text-fg-secondary text-sm",onHtmlSelection:lt,basePath:de,copyVariant:"preview"})})})(),x.mode==="artifact"&&c.jsx("div",{ref:G,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(Ef,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm",copyVariant:"preview"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(qD,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?de=>f(x.browserId,de):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(eI,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:F,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:de=>{if(!de||!i){I(null);return}I({x:de.x,y:de.y,text:de.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(xC,{path:x.path,entries:x.entries,onNavigate:de=>C(de),onOpenFile:de=>C(de),onReveal:Tt,onCopyPath:gt}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?m("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):m("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:Tt,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),c.jsx("button",{onClick:Tt,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:m("common:open",{defaultValue:"Open"})}),c.jsx("button",{onClick:gt,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?m("common:copied",{defaultValue:"Copied"}):m("common:copy",{defaultValue:"Copy"})})]})]})]},H)]}),E&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:E.x,top:E.y-8},children:c.jsxs("button",{onMouseDown:de=>{de.preventDefault(),de.stopPropagation(),Je(E.text,E.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-on-brand hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),m("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&Lt&&c.jsx(y2,{item:Lt,onClose:()=>R(!1),onShared:it})]})}function uI({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=yt(["team","common"]);return c.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",r,")"]}),c.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(l=>c.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${l.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[c.jsx(As,{name:l.name,size:16,bgClass:l.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),l.name,l.id!==t&&c.jsx("button",{onClick:()=>n(l.id),className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},l.id))}),e.length>0&&c.jsx("div",{className:"mt-1",children:c.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:l=>{l.target.value&&a(l.target.value)},children:[c.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),e.map(l=>c.jsxs("option",{value:l.id,children:["[",l.type==="agent"?"Agent":"Human","] ",l.name]},l.id))]})})]})}const fI={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},pI={text:"bg-brand-500/10 text-brand-500",thinking:"bg-amber-500/10 text-amber-600",tool:"bg-sky-500/10 text-sky-600"};function mI({match:s}){const e=s.snippet.slice(0,s.snippetMatchStart),t=s.snippet.slice(s.snippetMatchStart,s.snippetMatchStart+s.snippetMatchLength),r=s.snippet.slice(s.snippetMatchStart+s.snippetMatchLength);return c.jsxs("span",{className:"text-xs text-fg-secondary",children:[e,c.jsx("mark",{className:"bg-yellow-500/30 text-fg-primary rounded-[3px] px-0.5",children:t}),r]})}function gI({query:s,onQueryChange:e,matches:t,cursor:r,scanned:i,hasMore:n,loadingMore:a,truncated:o,onLoadEarlier:l,onJump:h,onClose:u,labelFor:d,serverResults:f,serverLoading:p,onServerResultClick:v}){const{t:b,i18n:g}=yt(["team","common"]),O=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{O.current?.focus()},[]),w.useEffect(()=>{if(r<0)return;m.current?.querySelector(`[data-find-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);const x=k=>{if(t.length===0)return;const P=(((r<0?k>=0?-1:0:r)+k)%t.length+t.length)%t.length;h(P)},y=s.trim().length>0;return c.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/60 px-4 py-2 space-y-1.5 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("div",{className:"flex-1 relative",children:[c.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),c.jsx("input",{ref:O,value:s,onChange:k=>e(k.target.value),onKeyDown:k=>{k.key==="Escape"?(k.preventDefault(),u()):k.key==="Enter"?(k.preventDefault(),x(k.shiftKey?-1:1)):k.key==="ArrowDown"?(k.preventDefault(),x(1)):k.key==="ArrowUp"&&(k.preventDefault(),x(-1))},placeholder:b("page.findPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),c.jsx("span",{className:"text-[11px] text-fg-tertiary tabular-nums shrink-0 min-w-[44px] text-center",children:y&&t.length>0?b("page.findMatchCount",{current:(r<0?0:r)+1,total:t.length}):y?"0/0":""}),c.jsx("button",{onClick:()=>x(-1),disabled:t.length===0,title:b("page.findPrev"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"18 15 12 9 6 15"})})}),c.jsx("button",{onClick:()=>x(1),disabled:t.length===0,title:b("page.findNext"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("button",{onClick:u,title:b("page.findClose"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated transition-colors",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y&&c.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:b("page.findScopeLoaded",{count:i})}),o&&c.jsx("span",{className:"text-amber-600",children:b("page.findTruncated",{count:t.length})}),t.length===0&&!n&&c.jsx("span",{className:"text-fg-secondary",children:b("page.findNoMatches")}),n&&c.jsx("button",{onClick:l,disabled:a,className:"ml-auto text-brand-500 hover:text-brand-500 disabled:opacity-50 underline decoration-dotted",children:b(a?"page.findLoadingEarlier":"page.findLoadEarlier")})]}),y&&t.length>0&&c.jsx("div",{ref:m,className:"max-h-52 overflow-y-auto scrollbar-thin space-y-0.5",children:t.map((k,C)=>c.jsxs("button",{"data-find-idx":C,onClick:()=>h(C),className:`w-full text-left px-2.5 py-1.5 rounded-lg transition-colors ${C===r?"bg-brand-500/15 ring-1 ring-brand-500/40":"hover:bg-surface-elevated"}`,children:[c.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${pI[k.field]}`,children:b(fI[k.field])}),d&&c.jsx("span",{className:"text-[10px] text-fg-tertiary truncate",children:d(k)})]}),c.jsx("div",{className:"line-clamp-2 break-words",children:c.jsx(mI,{match:k})})]},`${k.messageId}-${k.field}-${C}`))}),y&&(p||f&&f.length>0)&&c.jsxs("div",{className:"border-t border-border-default/60 mt-1 px-1",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-medium py-0.5",children:b("page.findServerResultsTitle")}),p&&c.jsx("div",{className:"text-xs text-fg-tertiary px-2.5 py-1",children:b("page.searching")}),f&&f.length>0&&c.jsx("div",{className:"max-h-40 overflow-y-auto scrollbar-thin space-y-0.5",children:f.map(k=>c.jsxs("button",{onClick:()=>v?.(k),className:"w-full text-left px-2.5 py-1.5 rounded-lg transition-colors hover:bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-fg-tertiary mb-0.5 min-w-0",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${k.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:k.source==="channel"?"#":"1:1"}),c.jsx("span",{className:"truncate max-w-[9rem] text-fg-secondary font-medium",children:k.source==="channel"?k.channel?`#${k.channel}`:b("page.findServerResultsTitle"):k.sessionTitle||b("page.untitledSession")}),k.senderName&&c.jsx("span",{className:"truncate max-w-[6rem] shrink-0",children:k.senderName}),c.jsx("span",{className:"shrink-0 ml-auto tabular-nums",title:sm(k.createdAt,g.language),children:tm(k.createdAt,b)})]}),c.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 break-words",children:k.text.length>200?k.text.slice(0,200)+"…":k.text})]},k.id))})]})]})}const OI=300,xI=48;function bI(s){const e=[];if(s.segments&&s.segments.length>0){for(const t of s.segments)if(t.type==="text")t.thinking&&e.push({field:"thinking",value:t.thinking}),t.content&&e.push({field:"text",value:t.content});else if(t.type==="tool"){const r=[t.tool,t.result,t.error].filter(i=>!!i);r.length>0&&e.push({field:"tool",value:r.join(`
63
- `)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function vI(s,e,t,r=xI){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),u=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${u}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function yI(s,e,t={}){const r=t.limit??OI,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of bI(o)){const u=h.toLocaleLowerCase();let d=0;for(;;){const f=u.indexOf(i,d);if(f===-1)break;const p=vI(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};d=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function SI(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function wI(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,u=!1,d=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){u=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){d=!0;break}if(!h){u=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:d,messages:o,hasMore:h,oldestCursor:f(),exhausted:u}}const _I="markus.scrollDebug";let Tf=null,yv=!1;function kI(){if(!yv){try{Tf=typeof localStorage<"u"&&localStorage.getItem(_I)==="1"}catch{Tf=!1}yv=!0}return Tf===!0}function zi(s,e){kI()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}const Sv={urgent:0,high:1,normal:2,low:3};function wv(s){return Sv[s??"normal"]??Sv.normal}function CI(s){return[...s].sort((e,t)=>{const r=wv(e.priority)-wv(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function PI(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function qp(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function TI(s,e){return e?CI(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&PI(t)===e)):[]}const _v={sessionId:null,messageId:null};function QI(s){if(s.length===0)return _v;const e=new Set(s.map(qp).filter(n=>!!n));if(e.size!==1||s.some(n=>!qp(n)))return _v;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const W_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Dc(s){return s?W_[s]?.icon??"●":"●"}const $I=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries(W_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),jI=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function RI(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of jI){const l=e(`agent:toolCategories.${a}`),h=s.filter(u=>!r.has(u.name)&&o.some(d=>u.name.startsWith(d)));h.length>0&&(t.set(l,h),h.forEach(u=>r.add(u.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function EI(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function AI({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const MI=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function kv(s){if(!s)return null;for(const e of MI){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const X_=16;function LI(s,e,t=X_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function NI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}function z_(s,e={}){const{enabled:t=!0,deps:r=[]}=e,[i,n]=w.useState(du()),[a,o]=w.useState(0),l=w.useRef(s);l.current=s;const h=JSON.stringify(r);w.useEffect(()=>{if(!t){n(du());return}let d=!1;return n(du()),(async()=>{const f=await bC(()=>l.current());d||n(f)})(),()=>{d=!0}},[t,h,a]);const u=w.useCallback(()=>o(d=>d+1),[]);return{resource:i,view:vC(i),reload:u}}const DI=w.lazy(()=>Gv(()=>import("./MarkdownMessage-DedA8Zob.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),nh={mind:"mind",files:"files",tools:"tools",memory:"memory"},ug=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function II(s,e){const{labelKey:t}=Zh(s);return t?e(t):s}function Zp(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Cv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:u}=yt(["agent","common"]),d=Yp(),[f,p]=w.useState(null),[v,b]=w.useState(null),[g,O]=w.useState(r??"overview"),m=o&&l?l:g,[x,y]=w.useState(null),k=w.useMemo(()=>ug.map(U=>({...U,label:u(`agent:tabs.${U.key}`)})),[u]),C=w.useMemo(()=>k.map(U=>({id:U.key})),[k]),P=w.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=yC(C,g,O,P),T=w.useRef(null);w.useEffect(()=>{const U=T.current;if(!U)return;U.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=w.useCallback(()=>{ie.agents.get(s).then(p).catch(()=>{})},[s]);if(w.useEffect(()=>(O(r??"overview"),y(null),R(),ie.externalAgents.list().then(W=>{const ce=W.agents.find(j=>j.markusAgentId===s);y(ce??null)}).catch(()=>{}),St.on("agent:update",W=>{W.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(ey,{label:u("agent:profilePage.loadingAgent")});const M=Zh(f.state.status).dotClass,N=a?.role==="owner"||a?.role==="admin",E=U=>h??nh[U],I=U=>x||nh[U]?"overview":U,V=nh[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[I(m)==="overview"&&c.jsx(Tv,{agent:f,onUpdate:R,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:E(m)}),I(m)==="deliverables"&&c.jsx(Dv,{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(As,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${M}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:II(f.state.status,u)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:u("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:u("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Ar.navigate(Ht.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",u("agent:profilePage.chat")]}),N&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:U}=await ie.agents.getFilesMap(s),W={type:"agent",name:Hv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await em.publishViaProxy({itemType:"agent",name:f.name,description:W.description,category:"general",config:W,files:U}),b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(U){b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishFailed",{error:String(U)}),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:u("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",u("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(U=>!x||U.key==="overview").map(U=>c.jsxs("button",{onClick:()=>O(U.key),"data-active":g===U.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===U.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:U.icon}),U.label]},U.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?_.onTouchStart:void 0,onTouchEnd:d?_.onTouchEnd:void 0,children:[I(g)==="overview"&&c.jsx(Tv,{agent:f,onUpdate:R,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:h??V}),I(g)==="deliverables"&&c.jsx(Dv,{agentId:s})]}),v&&c.jsx(Hn,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function BI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:im.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function xo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function Pv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Xh,{agentId:s,activityId:e.id})})]})}function Tv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=w.useState(null),[h,u]=w.useState([]),[d,f]=w.useState(null),[p,v]=w.useState(null),[b,g]=w.useState(""),[O,m]=w.useState([]),[x,y]=w.useState(0),[k,C]=w.useState(!1),[P,_]=w.useState(!1),[T,R]=w.useState(()=>d0(a,n));w.useEffect(()=>{R(d0(a,n))},[a,n]);const M=(s.state.activeTaskIds??[]).join(",");w.useEffect(()=>{ie.usage.agents().then(K=>{const le=K.agents.find(J=>J.agentId===s.id);le&&l(le)}).catch(()=>{}),s.state.activeTaskIds?.length&&ie.tasks.list({assignedAgentId:s.id}).then(K=>{m(K.tasks.filter(le=>s.state.activeTaskIds?.includes(le.id)))}).catch(()=>{}),ie.agents.getMailbox(s.id,{limit:1}).then(K=>{y(K.queued?.length??0)}).catch(()=>{})},[s.id,M,s.state.status]),w.useEffect(()=>{if(T!=="usage")return;let K=!1;return C(!0),ie.system.storage().then(le=>{if(K)return;g(le.dataDir+"/agents/"+s.id);const J=le.agents.find(G=>G.id===s.id);J&&v(J)}).catch(()=>{}).finally(()=>{K||C(!1)}),()=>{K=!0}},[T,s.id]),w.useEffect(()=>{if(T!=="recent")return;let K=!1;return _(!0),ie.agents.getActivities(s.id,{limit:DP}).then(le=>{K||u(le.activities)}).catch(()=>{}).finally(()=>{K||_(!1)}),()=>{K=!0}},[T,s.id]);const[N,E]=w.useState(!1),I=()=>{s.state.status==="offline"?ie.agents.start(s.id).then(e):E(!0)},V=w.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]),U=w.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(ps,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(ps,{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(Ys,{label:r("agent:profilePage.overview.labels.connection"),value:SC(t.connected?"online":"offline",r),color:t.connected?"green":"gray"}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(ps,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(ps,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:U.map(K=>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:K.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:K.desc})]},K.field))})}),c.jsx(ps,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:V.map(K=>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 ${K.method==="POST"?"text-amber-600":"text-green-600"}`,children:K.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:K.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:K.desc})]},K.path))})})]});const{heartbeats:W,comms:ce}=IP(h),j=h0(W),B=h0(ce),X=s.state.activeTaskIds?.length??0,Z=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,j.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:j.total}):null,B.total>0?r("agent:profilePage.overview.a2aRuns",{count:B.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Zp(RP(o,s.state.tokensUsedToday))}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(X),color:X>0?"blue":void 0}),i&&c.jsx("button",{onClick:I,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:oh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(X>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(K=>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:K.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:jf(K.status,r,K.blockedReason)})]},K.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(BI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(xo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Zp(o.totalTokens)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.storage"),value:Av(p.size)}),EP(p.subItems).map(K=>{const le=MP(K.name);return c.jsx(Ys,{label:le?r(le):K.name,value:Av(K.size)},K.name)}),c.jsxs("button",{onClick:()=>{ie.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(xo,{children:[Z&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:Z}),j.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:j.shown.map(K=>c.jsx(Pv,{agentId:s.id,act:K,dotClass:"bg-green-400",expanded:d===K.id,onToggle:()=>f(d===K.id?null:K.id)},K.id))})]}),B.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:B.shown.map(K=>c.jsx(Pv,{agentId:s.id,act:K,dotClass:"bg-blue-400",expanded:d===K.id,onToggle:()=>f(d===K.id?null:K.id)},K.id))})]}),j.total===0&&B.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(xo,{children:c.jsx(n3,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(xo,{children:c.jsx(qI,{agentId:s.id})}),T==="tools"&&c.jsx(xo,{children:c.jsx(HI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(xo,{children:[c.jsx(GI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(YI,{agentId:s.id})})]}),N&&c.jsx(Hn,{title:r("agent:profilePage.overview.stopAgentConfirm.title"),message:r("agent:profilePage.overview.stopAgentConfirm.message"),confirmLabel:r("agent:profilePage.overview.stopAgentConfirm.confirm"),onConfirm:()=>{E(!1),ie.agents.stop(s.id).then(e)},onCancel:()=>E(!1)})]})}function WI(s,e){const t=s.split(`
63
+ `)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function vI(s,e,t,r=xI){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),u=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${u}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function yI(s,e,t={}){const r=t.limit??OI,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of bI(o)){const u=h.toLocaleLowerCase();let d=0;for(;;){const f=u.indexOf(i,d);if(f===-1)break;const p=vI(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};d=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function SI(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function wI(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,u=!1,d=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){u=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){d=!0;break}if(!h){u=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:d,messages:o,hasMore:h,oldestCursor:f(),exhausted:u}}const _I="markus.scrollDebug";let Tf=null,yv=!1;function kI(){if(!yv){try{Tf=typeof localStorage<"u"&&localStorage.getItem(_I)==="1"}catch{Tf=!1}yv=!0}return Tf===!0}function zi(s,e){kI()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}const Sv={urgent:0,high:1,normal:2,low:3};function wv(s){return Sv[s??"normal"]??Sv.normal}function CI(s){return[...s].sort((e,t)=>{const r=wv(e.priority)-wv(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function PI(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function qp(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function TI(s,e){return e?CI(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&PI(t)===e)):[]}const _v={sessionId:null,messageId:null};function QI(s){if(s.length===0)return _v;const e=new Set(s.map(qp).filter(n=>!!n));if(e.size!==1||s.some(n=>!qp(n)))return _v;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const W_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Dc(s){return s?W_[s]?.icon??"●":"●"}const $I=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries(W_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),jI=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function RI(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of jI){const l=e(`agent:toolCategories.${a}`),h=s.filter(u=>!r.has(u.name)&&o.some(d=>u.name.startsWith(d)));h.length>0&&(t.set(l,h),h.forEach(u=>r.add(u.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function EI(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function AI({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const MI=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function kv(s){if(!s)return null;for(const e of MI){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const X_=16;function LI(s,e,t=X_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function NI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}function z_(s,e={}){const{enabled:t=!0,deps:r=[]}=e,[i,n]=w.useState(du()),[a,o]=w.useState(0),l=w.useRef(s);l.current=s;const h=JSON.stringify(r);w.useEffect(()=>{if(!t){n(du());return}let d=!1;return n(du()),(async()=>{const f=await bC(()=>l.current());d||n(f)})(),()=>{d=!0}},[t,h,a]);const u=w.useCallback(()=>o(d=>d+1),[]);return{resource:i,view:vC(i),reload:u}}const DI=w.lazy(()=>Gv(()=>import("./MarkdownMessage-DVfFMzM9.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),nh={mind:"mind",files:"files",tools:"tools",memory:"memory"},ug=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function II(s,e){const{labelKey:t}=Zh(s);return t?e(t):s}function Zp(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Cv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:u}=yt(["agent","common"]),d=Yp(),[f,p]=w.useState(null),[v,b]=w.useState(null),[g,O]=w.useState(r??"overview"),m=o&&l?l:g,[x,y]=w.useState(null),k=w.useMemo(()=>ug.map(U=>({...U,label:u(`agent:tabs.${U.key}`)})),[u]),C=w.useMemo(()=>k.map(U=>({id:U.key})),[k]),P=w.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=yC(C,g,O,P),T=w.useRef(null);w.useEffect(()=>{const U=T.current;if(!U)return;U.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=w.useCallback(()=>{ie.agents.get(s).then(p).catch(()=>{})},[s]);if(w.useEffect(()=>(O(r??"overview"),y(null),R(),ie.externalAgents.list().then(W=>{const ce=W.agents.find(j=>j.markusAgentId===s);y(ce??null)}).catch(()=>{}),St.on("agent:update",W=>{W.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(ey,{label:u("agent:profilePage.loadingAgent")});const M=Zh(f.state.status).dotClass,N=a?.role==="owner"||a?.role==="admin",E=U=>h??nh[U],I=U=>x||nh[U]?"overview":U,V=nh[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[I(m)==="overview"&&c.jsx(Tv,{agent:f,onUpdate:R,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:E(m)}),I(m)==="deliverables"&&c.jsx(Dv,{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(As,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${M}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:II(f.state.status,u)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:u("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:u("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Ar.navigate(Ht.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",u("agent:profilePage.chat")]}),N&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:U}=await ie.agents.getFilesMap(s),W={type:"agent",name:Hv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await em.publishViaProxy({itemType:"agent",name:f.name,description:W.description,category:"general",config:W,files:U}),b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(U){b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishFailed",{error:String(U)}),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:u("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",u("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(U=>!x||U.key==="overview").map(U=>c.jsxs("button",{onClick:()=>O(U.key),"data-active":g===U.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===U.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:U.icon}),U.label]},U.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?_.onTouchStart:void 0,onTouchEnd:d?_.onTouchEnd:void 0,children:[I(g)==="overview"&&c.jsx(Tv,{agent:f,onUpdate:R,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:h??V}),I(g)==="deliverables"&&c.jsx(Dv,{agentId:s})]}),v&&c.jsx(Hn,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function BI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:im.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function xo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function Pv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Xh,{agentId:s,activityId:e.id})})]})}function Tv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=w.useState(null),[h,u]=w.useState([]),[d,f]=w.useState(null),[p,v]=w.useState(null),[b,g]=w.useState(""),[O,m]=w.useState([]),[x,y]=w.useState(0),[k,C]=w.useState(!1),[P,_]=w.useState(!1),[T,R]=w.useState(()=>d0(a,n));w.useEffect(()=>{R(d0(a,n))},[a,n]);const M=(s.state.activeTaskIds??[]).join(",");w.useEffect(()=>{ie.usage.agents().then(K=>{const le=K.agents.find(J=>J.agentId===s.id);le&&l(le)}).catch(()=>{}),s.state.activeTaskIds?.length&&ie.tasks.list({assignedAgentId:s.id}).then(K=>{m(K.tasks.filter(le=>s.state.activeTaskIds?.includes(le.id)))}).catch(()=>{}),ie.agents.getMailbox(s.id,{limit:1}).then(K=>{y(K.queued?.length??0)}).catch(()=>{})},[s.id,M,s.state.status]),w.useEffect(()=>{if(T!=="usage")return;let K=!1;return C(!0),ie.system.storage().then(le=>{if(K)return;g(le.dataDir+"/agents/"+s.id);const J=le.agents.find(G=>G.id===s.id);J&&v(J)}).catch(()=>{}).finally(()=>{K||C(!1)}),()=>{K=!0}},[T,s.id]),w.useEffect(()=>{if(T!=="recent")return;let K=!1;return _(!0),ie.agents.getActivities(s.id,{limit:DP}).then(le=>{K||u(le.activities)}).catch(()=>{}).finally(()=>{K||_(!1)}),()=>{K=!0}},[T,s.id]);const[N,E]=w.useState(!1),I=()=>{s.state.status==="offline"?ie.agents.start(s.id).then(e):E(!0)},V=w.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]),U=w.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(ps,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(ps,{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(Ys,{label:r("agent:profilePage.overview.labels.connection"),value:SC(t.connected?"online":"offline",r),color:t.connected?"green":"gray"}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(ps,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(Xs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(ps,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:U.map(K=>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:K.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:K.desc})]},K.field))})}),c.jsx(ps,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:V.map(K=>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 ${K.method==="POST"?"text-amber-600":"text-green-600"}`,children:K.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:K.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:K.desc})]},K.path))})})]});const{heartbeats:W,comms:ce}=IP(h),j=h0(W),B=h0(ce),X=s.state.activeTaskIds?.length??0,Z=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,j.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:j.total}):null,B.total>0?r("agent:profilePage.overview.a2aRuns",{count:B.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Xs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Xs,{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(Xs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Zp(RP(o,s.state.tokensUsedToday))}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(X),color:X>0?"blue":void 0}),i&&c.jsx("button",{onClick:I,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:oh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(X>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(K=>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:K.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:jf(K.status,r,K.blockedReason)})]},K.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(BI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(xo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Zp(o.totalTokens)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ys,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ys,{label:r("agent:profilePage.overview.storage"),value:Av(p.size)}),EP(p.subItems).map(K=>{const le=MP(K.name);return c.jsx(Ys,{label:le?r(le):K.name,value:Av(K.size)},K.name)}),c.jsxs("button",{onClick:()=>{ie.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(xo,{children:[Z&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:Z}),j.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:j.shown.map(K=>c.jsx(Pv,{agentId:s.id,act:K,dotClass:"bg-green-400",expanded:d===K.id,onToggle:()=>f(d===K.id?null:K.id)},K.id))})]}),B.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:B.shown.map(K=>c.jsx(Pv,{agentId:s.id,act:K,dotClass:"bg-blue-400",expanded:d===K.id,onToggle:()=>f(d===K.id?null:K.id)},K.id))})]}),j.total===0&&B.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(xo,{children:c.jsx(n3,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(xo,{children:c.jsx(qI,{agentId:s.id})}),T==="tools"&&c.jsx(xo,{children:c.jsx(HI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(xo,{children:[c.jsx(GI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(YI,{agentId:s.id})})]}),N&&c.jsx(Hn,{title:r("agent:profilePage.overview.stopAgentConfirm.title"),message:r("agent:profilePage.overview.stopAgentConfirm.message"),confirmLabel:r("agent:profilePage.overview.stopAgentConfirm.confirm"),onConfirm:()=>{E(!1),ie.agents.stop(s.id).then(e)},onCancel:()=>E(!1)})]})}function WI(s,e){const t=s.split(`
64
64
  `),r=e.split(`
65
65
  `),i=t.length,n=r.length,a=Array.from({length:i+1},()=>new Array(n+1).fill(0));for(let f=i-1;f>=0;f--)for(let p=n-1;p>=0;p--)a[f][p]=t[f]===r[p]?a[f+1][p+1]+1:Math.max(a[f+1][p],a[f][p+1]);const o=[];let l=0,h=0,u=1,d=1;for(;l<i||h<n;)l<i&&h<n&&t[l]===r[h]?(o.push({type:"equal",content:t[l],oldLineNum:u++,lineNum:d++}),l++,h++):h<n&&(l>=i||a[l][h+1]>=a[l+1][h])?(o.push({type:"add",content:r[h],lineNum:d++}),h++):(o.push({type:"remove",content:t[l],oldLineNum:u++}),l++);return o}function Qv(s){return s.match(/\S+|\s+/g)??[""]}function $v({oldText:s,newText:e,mode:t}){const r=Qv(s),i=Qv(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let d=n-1;d>=0;d--)for(let f=a-1;f>=0;f--)o[d][f]=r[d]===i[f]?o[d+1][f+1]+1:Math.max(o[d+1][f],o[d][f+1]);const l=[];let h=0,u=0;for(;h<n||u<a;)h<n&&u<a&&r[h]===i[u]?(l.push({text:t==="remove"?r[h]:i[u],changed:!1}),h++,u++):u<a&&(h>=n||o[h][u+1]>=o[h+1][u])?(t==="add"&&l.push({text:i[u],changed:!0}),u++):(t==="remove"&&l.push({text:r[h],changed:!0}),h++);return c.jsx("span",{children:l.map((d,f)=>d.changed?c.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:d.text},f):c.jsx("span",{children:d.text},f))})}function XI({agent:s,template:e,templateId:t}){const{t:r}=yt(["agent","common"]),i=w.useMemo(()=>WI(s,e),[s,e]),[n,a]=w.useState(!0),o=3,l=w.useMemo(()=>{const p=i.map((O,m)=>O.type!=="equal"?m:-1).filter(O=>O>=0);if(p.length===0)return[];const v=[];let b=Math.max(0,p[0]-o),g=Math.min(i.length-1,p[0]+o);for(let O=1;O<p.length;O++){const m=Math.max(0,p[O]-o),x=Math.min(i.length-1,p[O]+o);m<=g+1||(v.push({start:b,end:g}),b=m),g=x}return v.push({start:b,end:g}),v},[i]),h=(p,v,b)=>{const g=p.type==="add"?"+":p.type==="remove"?"-":" ",O=p.type==="add"?"bg-green-500/8":p.type==="remove"?"bg-red-500/8":"",m=p.type==="add"?"text-green-600/90":p.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=p.type==="add"?"text-green-500":p.type==="remove"?"text-red-500":"text-fg-muted",y=p.type==="remove"?p.oldLineNum:p.lineNum;let k=null;return p.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?k=c.jsx($v,{oldText:p.content,newText:b[v+1].content,mode:"remove"}):p.type==="add"&&v>0&&b[v-1].type==="remove"&&(k=c.jsx($v,{oldText:b[v-1].content,newText:p.content,mode:"add"})),c.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[c.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),c.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:g}),c.jsxs("span",{className:`flex-1 text-[11px] font-mono ${m} whitespace-pre-wrap break-words leading-[20px]`,children:[k??p.content,p.content===""&&" "]})]},v)},u=i.filter(p=>p.type==="add").length,d=i.filter(p=>p.type==="remove").length,f=n?l.flatMap(p=>{const v=[];for(let b=p.start;b<=p.end;b++)v.push({...i[b],_idx:b});return v}):i.map((p,v)=>({...p,_idx:v}));return c.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),c.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",u]}),c.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",d]})]}),c.jsx("button",{onClick:()=>a(p=>!p),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),c.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((p,v)=>{const b=v>0?f[v-1]:null,g=n&&b&&p._idx-b._idx>1;return c.jsxs("div",{children:[g&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),h(p,p._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function zI(s,e){const t=s.split(`
66
66
  `),r=e.split(`
@@ -77,7 +77,7 @@ ${de}
77
77
  `+ce.join(`
78
78
  ---
79
79
 
80
- `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Ar.navigate(Ht.TEAM,{agentId:s,prefillMessage:j})},M=async U=>{if(y?.file===U){k(null);return}try{const W=await ie.agents.roleDiff(s,U);W.agentContent!=null&&W.templateContent!=null&&k({file:U,agent:W.agentContent,template:W.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 N={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=U=>{const W=N[U];return W?e(`agent:profilePage.filesTab.fileLabels.${W}`):U},I=m?.hasTemplate&&!m.isUpToDate,V=a?T.some(U=>U.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[I&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(U=>U.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(ps,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(U=>{const W=T.some(ce=>ce.file===U.name);return c.jsxs("button",{onClick:()=>P(U.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===U.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[U.name,W&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},U.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[V&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>M(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-on-brand 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")})]})]}),u&&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:`${u}/${a}`,children:[u,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${u}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default 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:()=>{ie.system.openPath(u)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx(XI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(ZI,{content:t.find(U=>U.name===a)?.content??"",editContent:l,setEditContent:U=>{h(U),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(zh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function ZI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=w.useState(!1),o=w.useRef(null);return w.useEffect(()=>{n&&o.current?.focus()},[n]),w.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(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(DI,{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 VI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function FI({tools:s}){const{t:e}=yt(["agent","common"]),t=RI(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(ps,{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=WC(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=VI(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(PC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function UI({agent:s}){const{t:e}=yt(["agent","common"]),t=s.proficiency??{},[r,i]=w.useState(null),[n,a]=w.useState(null),[o,l]=w.useState(!1),h=s.availableSkills??[],u=s.skillWarnings?.missing??[],d=new Map;for(const O of h){const m=O.category||"custom";d.has(m)||d.set(m,[]),d.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...d.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[u.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:u.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:u.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(ps,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(zh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function HI({tools:s,agent:e}){const{t}=yt(["agent","common"]),[r,i]=w.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(FI,{tools:s}):c.jsx(UI,{agent:e})]})}function YI({agentId:s}){const{t:e}=yt(["agent","common"]),[t,r]=w.useState(null),[i,n]=w.useState(!0),[a,o]=w.useState("longterm"),[l,h]=w.useState(""),[u,d]=w.useState(""),[f,p]=w.useState(!1),[v,b]=w.useState(null),[g,O]=w.useState(null),m=z_(()=>ie.agents.getMemorySession(s,g??"").then(T=>T.messages),{enabled:g!==null,deps:[s,g]}),x=w.useCallback(()=>{n(!0),ie.agents.getMemory(s).then(T=>{r(T),h(T.recentDailyLogs??""),d(T.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);w.useEffect(()=>{x()},[x]);const y=async()=>{p(!0),await ie.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),x()},k=async()=>{p(!0),await ie.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),u).catch(()=>{}),p(!1),x()},C=l!==(t?.recentDailyLogs??""),P=u!==(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 _=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:_.map(T=>c.jsx("button",{onClick:()=>o(T.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===T.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:T.label},T.key))}),a==="entries"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(zh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((T,R)=>{const M=v===R;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(M?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 ${T.type==="fact"?"bg-blue-500/15 text-blue-600":T.type==="task"?"bg-green-500/15 text-green-600":T.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:T.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${M?"":"line-clamp-2"}`,children:T.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${T.importance>=7?"bg-red-500/15 text-red-500":T.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",T.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(T.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:M?"▲":"▼"})]})]}),M&&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:T.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"),": ",T.type]}),T.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",T.importance]}),c.jsx("span",{children:new Date(T.timestamp).toLocaleString()})]})]})]},R)})})}),a==="sessions"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(zh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(T=>{const R=g===T.id,M=()=>{O(R?null:T.id)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:M,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:T.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[T.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(T.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:m.view.loading?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.view.error?c.jsx(Yv,{variant:"inline",subject:"会话消息",error:m.resource.error??"读取失败",notEquals:"这个会话没有消息",onRetry:m.reload}):m.view.empty?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const N=m.resource.items,E=new Map;for(const I of N)I.role==="tool"&&I.toolCallId&&E.set(I.toolCallId,I.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:N.filter(I=>I.role!=="tool").map((I,V)=>c.jsxs("div",{className:"px-3 py-2",children:[(I.role==="user"||I.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 ${I.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${I.role}`,{defaultValue:I.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(vi,{content:I.content,className:"text-xs text-fg-secondary"})})]}),I.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[I.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(vi,{content:I.content,className:"text-xs text-fg-secondary"})})]}),I.toolCalls&&I.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:I.toolCalls.map(U=>{let W;try{W=JSON.parse(U.arguments)}catch{}const ce={tool:U.name,status:"done",args:W,result:E.get(U.id)};return c.jsx(BC,{entry:{type:"tool",info:ce}},U.id)})})]})]},V))})})()})]},T.id)})})}),a==="daily"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:C?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:y,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:T=>h(T.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(ps,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:P?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>d(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:k,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:u,onChange:T=>d(T.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 GI({agentId:s,initialData:e}){const{t}=yt(["agent","common"]),[r,i]=w.useState(e??null),[n,a]=w.useState(!e),[o,l]=w.useState([]),[h,u]=w.useState(null),[d,f]=w.useState(!1),[p,v]=w.useState(null),[b,g]=w.useState(null),O=w.useRef(null);w.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=w.useCallback(()=>Promise.all([ie.agents.getHeartbeat(s).then(i).catch(()=>{}),ie.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);w.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),w.useEffect(()=>St.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await ie.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await ie.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(ps,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:d||!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(d?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ys,{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(JI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ys,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ys,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(ps,{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(vi,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>u(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Xh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:d,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(d?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function KI({taskId:s,isLive:e}){const{t}=yt("agent"),[r,i]=w.useState([]),[n,a]=w.useState(""),[o,l]=w.useState(!0);if(w.useEffect(()=>{l(!0),a(""),ie.tasks.getLogs(s).then(u=>{i(u.logs),l(!1)}).catch(()=>l(!1))},[s]),w.useEffect(()=>{if(!e)return;const u=St.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),d=St.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{u(),d()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(u=>CC(u));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Jv,{entries:h,isStreaming:e,streamingText:n})})}function Xh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=yt("agent"),[i,n]=w.useState([]),[a,o]=w.useState(!0);if(w.useEffect(()=>{o(!0),ie.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),w.useEffect(()=>t?St.on("agent:activity_log",u=>{const d=u.payload;if(d.agentId!==s||d.activityId!==e)return;const f={seq:d.seq,type:d.type,content:d.content,metadata:d.metadata,createdAt:d.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>kC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Jv,{entries:l,isStreaming:t})})}function ps({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 Xs({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 Ys({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 jv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Rv=5,Ev=1440;function JI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=yt(["agent","common"]),[i,n]=w.useState(!1),[a,o]=w.useState(null),[l,h]=w.useState(!1),[u,d]=w.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await ie.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(u));if(!Number.isFinite(m)||m<Rv||m>Ev){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=jv.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)}),jv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Rv,max:Ev,value:u,onChange:m=>d(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function zh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Av(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 Mv={0:"0",1:"1",2:"2",3:"3",4:"4"},Lv={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},e3={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"},t3={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},s3=["all","interaction","task","notification","system"],r3={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"},i3={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 Qf(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 Nv(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 u=o[1],d=o[2],f=jf(u,e),p=jf(d,e),v=i3[d]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=kv(r),o=Qf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=kv(r),o=Qf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=Qf(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 n3({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=yt(["agent","common","team"]),[n,a]=w.useState(null),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState("all"),[p,v]=w.useState("all"),[b,g]=w.useState(e??null),[O,m]=w.useState(e??null),[x,y]=w.useState(!1),[k,C]=w.useState(!1),[P,_]=w.useState(!0),[T,R]=w.useState(null),M=50,N=3,[E,I]=w.useState(null),V=w.useCallback(async(J=!0)=>{J&&u(!0);try{const G=d==="all"?void 0:d,q=p==="all"?void 0:p,[A,ee]=await Promise.all([ie.agents.getMindState(s),ie.agents.getMailbox(s,{limit:M,category:G,status:q})]);a(A),l(ee),_((ee.history?.length??0)>=M)}catch{}u(!1)},[s,d,p]),U=w.useCallback(async J=>{I(J);try{await ie.agents.dropMailboxItem(s,J,"operator"),await V()}catch{}finally{I(null)}},[s,V]),W=w.useCallback(async()=>{if(!o)return;const J=d==="all"?void 0:d,G=p==="all"?void 0:p;try{const q=await ie.agents.getMailbox(s,{limit:M,offset:o.history.length,category:J,status:G});l(A=>A?{...A,history:[...A.history,...q.history]}:q),_((q.history?.length??0)>=M)}catch{}},[s,o,d,p]),ce=w.useCallback(async()=>{try{await ie.agents.recoverStaleMailbox(s)}catch{}await V()},[s,V]);w.useEffect(()=>{g(e??null),m(e??null),V()},[V,e]);const j=w.useRef(!1);if(w.useEffect(()=>{if(!O||h)return;if(o?.history?.some(G=>G.id===O)){j.current=!1;const G=document.getElementById(`mbx-${O}`);if(G){setTimeout(()=>G.scrollIntoView({behavior:"smooth",block:"center"}),100);const q=setTimeout(()=>m(null),3e3);return()=>clearTimeout(q)}}else P&&!j.current&&(j.current=!0,(async()=>{let G=o?.history??[],q=P;for(;q;)try{const A=await ie.agents.getMailbox(s,{limit:M,offset:G.length}),ee=[...G,...A.history];G=ee,q=(A.history?.length??0)>=M;const F=A.history.some(ae=>ae.id===O);if(l(ae=>ae?{...ae,history:ee}:A),_(q),F||!q)break}catch{break}j.current=!1})())},[O,h,o,P,s]),w.useEffect(()=>{let J=null;const G=A=>{A.payload?.agentId===s&&(J&&clearTimeout(J),J=setTimeout(()=>{J=null,V(!1)},500))},q=[St.on("agent:mailbox",G),St.on("agent:decision",G),St.on("agent:attention",G),St.on("agent:focus",G),St.on("agent:update",G),St.on("agent:triage",G)];return()=>{J&&clearTimeout(J),q.forEach(A=>A())}},[s,V]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const B=n?.mailboxDepth??n?.queuedItems?.length??0,X=Zh(t).running,Z=(()=>{const J=n?.attentionState??"idle";return J==="deciding"||J==="idle"&&B>0?"deciding":J!=="idle"&&!n?.currentFocus?"idle":J})(),K=Z==="idle"&&o?.history?.some(J=>J.status==="processing"),le=(n?.attentionState??"idle")==="idle"&&B>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:[X?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${t3[Z]??"bg-gray-500/20 text-gray-500"}`,children:_C(Z,i)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),X?n?.currentFocus?(()=>{const J=Nv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Dc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:J.title}),J.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:J.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():le?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:B,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):Z==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:B})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{V()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),X&&K&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ce()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const J=n.queuedItems,G=J.length>N,q=G&&!x?J.slice(0,N):J,A=J.reduce((ee,F)=>(ee[F.sourceType]=(ee[F.sourceType]??0)+1,ee),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:J.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([ee,F])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Dc(ee)," ",F]},ee))})]}),c.jsxs("div",{className:"space-y-1",children:[q.map((ee,F)=>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:F+1}),c.jsx("span",{className:"text-sm",children:Dc(ee.sourceType)}),c.jsx("span",{className:`text-[10px] ${Lv[ee.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Mv[ee.priority]??ee.priority}`,{defaultValue:`P${ee.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:ee.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(ee.queuedAt).toLocaleTimeString()})]},ee.id)),G&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:J.length-N})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const J=LI(n.notebook,k);return c.jsx("section",{className:"bg-surface-elevated rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-muted leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:X_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[J.visible.map(G=>{const q=NI(G.updatedAt),A=i(`agent:profilePage.relative.${q.unit==="seconds"?"secondsAgo":q.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:q.count,hours:q.count}),ee=G.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-overlay 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:G.key}),c.jsxs("span",{className:`text-[10px] ${ee}`,children:["[",G.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:G.text.length>500?G.text.slice(0,500)+"…":G.text})]},G.key)}),J.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:J.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-elevated rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Xh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const G=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,q=XP(n.lastTriage);return c.jsx("section",{className:`bg-surface-elevated rounded-lg border p-3 transition-opacity ${G?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!G,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${q.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-overlay text-fg-tertiary"}`,children:q.isBatch?i("agent:profilePage.mind.batchSize",{count:q.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:s3.map(J=>{const G=o?.sourceTypeCounts,q=J==="all"?G?Object.values(G).reduce((A,ee)=>A+ee,0):void 0:G?($I[J]??[]).reduce((A,ee)=>A+(G[ee]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(J),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${d===J?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[i(`agent:profilePage.mind.categoryFilters.${J}`),q!=null&&q>0&&c.jsx("span",{className:"ml-1 opacity-60",children:q})]},J)})})]}),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(J=>{const G=o?.statusCounts,q=J.key==="all"?G?Object.values(G).reduce((A,ee)=>A+ee,0):void 0:G?.[J.key];return c.jsxs("button",{onClick:()=>v(J.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===J.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[J.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${J.dot}`}),i(`agent:profilePage.mind.statusFilters.${J.key}`),q!=null&&q>0&&c.jsx("span",{className:"ml-1 opacity-60",children:q})]},J.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(J=>{const G=b===J.id,q=Dc(J.sourceType),A=Nv(J,i),ee=AI({itemStatus:J.status,agentRunning:X,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:J.id}),F=J.metadata?.senderName,ae=J.metadata?.senderRole,re=O===J.id;return c.jsxs("div",{id:`mbx-${J.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${re?"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-overlay/50 transition-colors rounded-lg",onClick:()=>g(G?null:J.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:G?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${ee==="stale"?"bg-amber-400/70":r3[J.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:q}),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 ${G?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${Lv[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Mv[J.priority]??J.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${G?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(J.queuedAt).toLocaleString()}),J.completedAt&&c.jsxs("span",{children:["→ ",new Date(J.completedAt).toLocaleTimeString()]}),J.activity&&c.jsxs(c.Fragment,{children:[J.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Zp(J.activity.totalTokens)})}),J.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:J.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-overlay px-1.5 py-0.5 rounded shrink-0",children:J.sourceType}),r&&EI({agentRunning:X,itemId:J.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:J.status})&&c.jsxs("button",{onClick:fe=>{fe.stopPropagation(),R(J.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),G&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[F&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:F}),ae&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",ae,")"]})]}),J.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(J.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:J.payload.content}),J.decisions&&J.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:J.decisions.map(fe=>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 ${e3[fe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:fe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:fe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(fe.createdAt).toLocaleTimeString()})]},fe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===J.id,onClick:()=>{U(J.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),J.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:J.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${J.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:J.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),J.activity.type==="task"&&J.payload?.taskId?c.jsx(KI,{taskId:J.payload.taskId,isLive:!J.activity.endedAt}):c.jsx(Xh,{agentId:s,activityId:J.activity.id,isLive:!J.activity.endedAt})]}):ee==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):ee==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):J.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},J.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:W,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Hn,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const J=T;R(null),ie.agents.cancelProcessing(s,{itemId:J}).then(()=>{let G=0;const q=()=>{G+=1,V(),G<8&&window.setTimeout(q,750)};q()}).catch(()=>{V()})},onCancel:()=>R(null)})]})}function Dv({agentId:s}){const{t:e}=yt(["agent","common"]),t=Zo(),r=z_(()=>ie.deliverables.search({agentId:s,limit:200}).then(l=>l.results),{deps:[s]}),i=r.resource.items,n=r.view.loading,a=r.reload,o=w.useCallback(l=>{if(WP(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:l});return}Ar.navigate(Ht.DELIVERABLES,{openDeliverable:l.id})},[t]);return w.useEffect(()=>{const l=St.on("deliverable:created",()=>a()),h=St.on("deliverable:updated",()=>a()),u=St.on("deliverable:removed",()=>a());return()=>{l(),h(),u()}},[a]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(l=>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"})]},l))}):r.view.error?c.jsx(Yv,{variant:"inline",subject:"交付物",error:r.resource.error??"读取失败",notEquals:"这个 agent 没有任何交付物",onRetry:a}):i.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:i.length})}),i.map(l=>{const h=wC[l.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=TO[l.status]??TO.active;return c.jsxs("button",{onClick:()=>o(l),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 ${h.color}`,children:h.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:l.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:l.status})]}),l.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:l.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(l.createdAt).toLocaleDateString()}),l.tags.length>0&&c.jsx("span",{children:l.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"})})]},l.id)})]})})}const o3=w.lazy(()=>Gv(()=>import("./MarkdownMessage-DedA8Zob.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),fg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Iv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Bv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=yt("team"),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState(!0),[p,v]=w.useState(null),[b,g]=w.useState("overview"),O=r&&i?i:b,[m,x]=w.useState(""),[y,k]=w.useState(""),[C,P]=w.useState(!1),[_,T]=w.useState(!1),[R,M]=w.useState(""),[N,E]=w.useState(""),I=w.useRef(null),V=w.useRef(null),U=w.useRef(null),W=w.useRef(null),[ce,j]=w.useState(!1),[B,X]=w.useState(!1),[Z,K]=w.useState(""),[le,J]=w.useState(""),[G,q]=w.useState(!1),[A,ee]=w.useState([]),F=w.useRef(null),ae=w.useCallback(async()=>{try{const Ue=(await ie.teams.list()).teams.find(Je=>Je.id===s);Ue&&l(Ue);const Ze=await ie.teams.status(s);ee(Ze.agents)}catch{}finally{u(!1)}},[s]),re=w.useCallback(async()=>{f(!0);try{const H=await ie.teams.getFile(s,"ANNOUNCEMENT.md");x(H.content)}catch{x("")}try{const H=await ie.teams.getFile(s,"NORMS.md");k(H.content)}catch{k("")}finally{f(!1)}},[s]);w.useEffect(()=>{g("overview"),ae(),re()},[s,ae,re]),w.useEffect(()=>{C&&V.current&&V.current.focus()},[C]),w.useEffect(()=>{_&&W.current&&W.current.focus()},[_]);const fe=async(H,Ue)=>{j(!0);try{await ie.teams.updateFile(s,H,Ue),H==="ANNOUNCEMENT.md"?(x(Ue),P(!1)):(k(Ue),T(!1))}catch{}j(!1)},Le=async()=>{Z.trim()&&(await ie.teams.update(s,{name:Z.trim()}),X(!1),ae())},we=async()=>{await ie.teams.update(s,{description:le}),q(!1),ae()};if(!o)return h?c.jsx(ey,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(u2,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Me=o.members.find(H=>H.agentRole==="manager"),$e=A.filter(H=>H.status!=="offline").length,ke=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${ke?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${ke?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Me?.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(H=>{const Ue=A.find(mt=>mt.id===H.id),Ze=Iv[Ue?.status??"offline"]??"bg-gray-500",Je=H.type==="agent";return c.jsxs("div",{onClick:()=>Je&&n?.(H.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Je&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(As,{name:H.name,avatarUrl:H.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:H.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Ue?.status??"offline"}),H.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:[H.role," · ",H.type]})]}),Je&&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"})})]},H.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:M,editing:C,setEditing:P,textareaRef:V,contentRef:I,saving:ce,onSave:()=>fe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),O==="norms"&&c.jsx(Ic,{content:y,draft:N,setDraft:E,editing:_,setEditing:T,textareaRef:W,contentRef:U,saving:ce,onSave:()=>fe("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),B?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:F,value:Z,onChange:H=>K(H.target.value),onKeyDown:H=>H.key==="Enter"&&Le(),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:Le,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>X(!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:()=>{K(o.name),X(!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"}),G?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:le,onChange:H=>J(H.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>q(!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:()=>{J(o.description??""),q(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Wv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const _e=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${_e?"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-on-brand 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:[$e," 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:H}=await ie.teams.getFilesMap(o.id),Ue=o.members.filter(Je=>Je.type==="agent"),Ze={type:"team",name:Hv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Ue.map(Je=>({name:Je.name,roleName:Je.role,role:Je.agentRole??"worker",count:1,skills:[]}))}};await em.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ze,files:H}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(H){v({title:"Hub",message:`Failed to publish: ${H}`,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:fg.map(H=>c.jsxs("button",{onClick:()=>g(H.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===H.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[H.icon," ",a(H.labelKey)]},H.key))})]}),c.jsxs("div",{className:`${_e?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Me?.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(H=>{const Ue=A.find(mt=>mt.id===H.id),Ze=Iv[Ue?.status??"offline"]??"bg-gray-500",Je=H.type==="agent";return c.jsxs("div",{onClick:()=>Je&&n?.(H.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Je&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(As,{name:H.name,avatarUrl:H.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:H.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Ue?.status??"offline"}),H.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:[H.role," · ",H.type]})]}),Je&&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"})})]},H.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:M,editing:C,setEditing:P,textareaRef:V,contentRef:I,saving:ce,onSave:()=>fe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),b==="norms"&&c.jsx(Ic,{content:y,draft:N,setDraft:E,editing:_,setEditing:T,textareaRef:W,contentRef:U,saving:ce,onSave:()=>fe("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),B?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:F,value:Z,onChange:H=>K(H.target.value),onKeyDown:H=>H.key==="Enter"&&Le(),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:Le,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>X(!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:()=>{K(o.name),X(!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"}),G?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:le,onChange:H=>J(H.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>q(!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:()=>{J(o.description??""),q(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Wv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Hn,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Ic({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:u,loading:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:d&&!s.trim()?c.jsx(ty,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(o3,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:u})})}function Wv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=w.useState(!1),[n,a]=w.useState(!1),[o,l]=w.useState(!1),[h,u]=w.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:d=>l(d.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:d=>a(d.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()=>{u(!0);try{await ie.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{u(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const a3=["chat","overview","deliverables"],l3=["chat","overview","announcements","norms","settings"];function c3(s,e){if(s==="chat")return e("page.chatTitle");if(ug.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=fg.find(i=>i.key===s);return r?e(r.labelKey):s}function h3(s){if(s==="chat")return"💬";const e=ug.find(r=>r.key===s);if(e)return e.icon;const t=fg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ma(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Vp=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Rr{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Rr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const d of e)i.add(d.id),n.push(d);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let u=!1;for(const d of t)if(!i.has(d.id)){if(d.sender==="agent"&&!!!(d.isError||d.isStopped||d.emptyReply)){if(r&&d.isStreaming)if(h&&l&&!u){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),u=!0,a.push({...d,id:l.id}),i.add(l.id)}else a.push(d),i.add(d.id);continue}o.push(d)}for(const d of o){if(i.has(d.id))continue;const f=d.rawCreatedAt?Date.parse(d.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,d),i.add(d.id)}for(const d of a)n.push(d);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Vp(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Rr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Rr.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Rr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Vp(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Rr.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Rr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Rr.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Rr.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const st=Rr.NEW_CHAT_ID;function d3(s){const e=w.useRef(new Rr),[t,r]=w.useState(s??[]),[i,n]=w.useState(!1),[a,o]=w.useState([]),l=w.useRef(null),[,h]=w.useState(0),u=w.useCallback(()=>h(R=>R+1),[]),d=w.useCallback(R=>e.current.getStreamSessions(R),[]),f=w.useCallback((R,M)=>{e.current.addStreamSession(R,M)&&u()},[u]),p=w.useCallback((R,M)=>{e.current.removeStreamSession(R,M)&&u()},[u]),v=w.useCallback((R,M)=>e.current.setActiveSession(R,M),[]),b=w.useCallback(R=>e.current.clearActiveSession(R),[]);w.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=w.useCallback((R,M,N)=>{const E=e.current.updateMessages(R,M,N);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=w.useCallback((R,M,N)=>{e.current.updateMessages(R,M,N).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const I=e.current.getMessages(R);I&&e.current.currentConvKey===R&&r([...I])}))},[]),m=w.useCallback((R,M,N)=>{const E=e.current.appendActivity(R,M,N);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=w.useCallback(R=>e.current.getPhase(R),[]),y=w.useCallback(R=>e.current.beginLoad(R),[]),k=w.useCallback(R=>{e.current.beginStream(R)},[]),C=w.useCallback(R=>{e.current.endStream(R)},[]),P=w.useCallback((R,M)=>{e.current.abortStream(R,M)&&u(),e.current.currentConvKey===R&&(n(!1),o([]))},[u]),_=w.useCallback((R,M)=>{e.current.resetConv(R,M),e.current.deleteBuffer(R)},[]),T=w.useCallback(async(R,M,N)=>{e.current.loadingSession=R,e.current.beginLoad(M);try{const E=await N(),I=e.current.applyLoadResult(M,R,E.messages);return I.displayChanged&&I.newMessages&&r(I.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===M&&e.current.getPhase(M)!=="streaming"&&(r([]),e.current.completeLoad(M)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:d,saveSessionToCache:(R,M)=>e.current.saveToCache(),restoreSessionFromCache:(R,M)=>{const N=e.current.restoreFromCache(R,M);return r(N??[]),N},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,M)=>{const N=e.current.updateMessages(R,()=>M);N.displayChanged&&N.newMessages&&r(N.newMessages)}}}function $f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function Xv(){const s=new Uint8Array(12);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(s);else for(let t=0;t<s.length;t++)s[t]=Math.floor(Math.random()*256);let e="";for(const t of s)e+=t.toString(16).padStart(2,"0");return`cm_${e}`}function u3(s){const e=w.useRef(new Map),t=w.useRef(new Map),r=ke=>{if(ke)for(const[_e,H]of e.current)H===ke&&e.current.delete(_e)},i=ke=>{if(ke)for(const[_e,H]of t.current)H===ke&&t.current.delete(_e)},n=ke=>{const _e=e.current.get(ke);_e&&(_e.abort(),e.current.delete(ke));const H=t.current.get(ke);H&&(H.abort(),t.current.delete(ke))},a=ke=>{const _e=e.current.get(st);_e&&e.current.size===1&&(e.current.delete(st),e.current.set(ke,_e))},o=w.useRef(new Map),l=w.useRef(new Set),h=w.useRef(null),u=w.useRef(new Map),d=w.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:M,decrementSending:N,loadAndDisplay:E,sessionSwitchSeqRef:I,setSending:V,setActivities:U,setInput:W,setChatContext:ce,setPendingImages:j,setMentionDropdown:B,setChatReplyTo:X,setActiveSessionId:Z,setStoredActiveSession:K,setOpenSessionTabs:le,setSessions:J,setLoadingChat:G,setWindowBounds:q,makeConvKey:A,makeDmChannel:ee,addRecentMsgId:F,resumeChatScrollFollow:ae,loadSessions:re}=s,{t:fe}=s,Le=w.useCallback(async(ke,_e)=>{const H=I.current,Ue=g.current===_e&&(b(_e)?.length??0)===0;Ue&&G(!0);try{const{count:Ze,hasMore:Je,oldestCursor:mt}=await E(ke,_e,async()=>{const lt=await ie.sessions.getMessages(ke,50);return{messages:lt.messages.map(ah).filter(gt=>gt.sender!=="agent"||gt.text||gt.segments&&gt.segments.length>0||gt.isStreaming),hasMore:lt.hasMore,oldestCursor:lt.messages[0]?new Date(lt.messages[0].createdAt).toISOString():null}});return q(ke,{hasMore:Je,oldestCursor:mt}),Ze}finally{Ue&&g.current===_e&&I.current===H&&G(!1)}},[E,b,I]),we=()=>{const ke=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(ke){const _e=$f(f.current.activeSessionId,st);_e.kind==="cancel"&&ie.agents.cancelProcessing(ke,_e.target).catch(()=>{})}n(f.current.activeSessionId??st),ke&&f.current.activeSessionId&&f.current.activeSessionId!==st&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Me=w.useCallback(async(ke,_e,H)=>{if(!ke||!_e||_e===st||l.current.has(_e))return;let Ue=null;try{const Ze=e.current.get(_e);if(Ze&&!Ze.signal.aborted&&T(H)?.has(_e)){g.current===H&&V(!0);return}const Je=()=>{XC({liveSessions:T(H),sessionId:_e,placeholderId:st})&&(P(H,_e),g.current===H&&(V(!1),O(H,pe=>fu(pe),_e)))},mt=`${ke}:${_e}`,lt=o.current.get(mt)??0;if(Date.now()-lt<1500)return;o.current.set(mt,Date.now());let Tt;const gt=await ie.sessions.streamStatus(ke,_e);gt.messageId&&(Tt=gt.messageId);const _t=b(H)??[],Ee=gt.status==="streaming",kt=zC(_t,{expectedMessageId:gt.messageId,allowCurrentTurnPartial:Ee}),ds=!!gt.active&&(gt.status==="done"||gt.status==="error")&&!!kt?.isStreaming;if(o0({aborted:!1,sawTerminal:ds,serverStatus:a0(gt.status)})==="finalize"){Je();return}o.current.set(mt,Date.now());for(const pe of t.current.values())pe.abort();t.current.clear(),Ue=new AbortController,t.current.set(_e,Ue),y(H),V(!0),_(H,_e);const Et=kt&&!kt.isError&&kt.sender==="agent"?_t.findIndex(pe=>pe.id===kt.id):-1,Ot=Et>=0?_t[Et]:void 0,Wt=qC(gt);if(!Ot&&!Wt){Je();return}const Ae=Ot?Ot.id:Wt;if(!Ot)O(H,pe=>[...pe,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],_e);else{const pe=(Ot.segments??[]).filter(ye=>ye.type==="tool").map(ye=>ye.status==="stopped"||ye.status==="running"?{...ye,status:"running"}:ye);O(H,ye=>ye.map(xe=>xe.id===Ae?{...xe,text:"",isStreaming:!0,isStopped:!1,segments:pe,committedSegments:void 0}:xe),_e)}const Lt=pe=>{g.current===H&&(d.current=Date.now(),m(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(se=>se.id===Ae):-1,He=ze>=0?ze:xe.map((se,je)=>({m:se,j:je})).reverse().find(se=>se.m.sender==="agent"&&se.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];return xe[He]={...qe,text:(qe.text??"")+pe,segments:MO(qe.segments??[],pe),isStreaming:!0},xe},_e))},it=pe=>{g.current===H&&(d.current=Date.now(),m(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(se=>se.id===Ae):-1,He=ze>=0?ze:xe.map((se,je)=>({m:se,j:je})).reverse().find(se=>se.m.sender==="agent"&&se.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];return xe[He]={...qe,segments:LO(qe.segments??[],pe),isStreaming:!0},xe},_e))},At=pe=>{if(g.current===H&&(d.current=Date.now(),pe.phase!=="heartbeat")){if((pe.phase==="start"||pe.phase==="end")&&x(H,{...pe,phase:pe.phase,ts:Date.now()},_e),pe.phase==="start"){const ye=`${pe.tool}_${Date.now()}`,xe=new Date().toISOString(),ze=He=>{const qe=[...He];for(let se=qe.length-1;se>=0;se--){const je=qe[se];if(je.type==="tool"&&je.tool===pe.tool&&(je.status==="running"||je.status==="stopped"))return qe[se]={...je,status:"running",args:pe.arguments??je.args},qe}return qe.push({type:"tool",key:ye,tool:pe.tool,status:"running",args:pe.arguments,createdAt:xe}),qe};O(H,He=>{const qe=[...He],se=Ae?qe.findIndex(Te=>Te.id===Ae):-1;if(se<0)return He;const je=ze(qe[se].segments??[]),Pe=qe[se].committedSegments,be=Pe&&ze(Pe);return qe[se]={...qe[se],segments:je,committedSegments:be,isStreaming:!0},qe},_e)}else if(pe.phase==="end"){const ye=new Date().toISOString(),xe=ze=>{const He=[...ze];for(let qe=He.length-1;qe>=0;qe--){const se=He[qe];if(se.type==="tool"&&se.tool===pe.tool&&(se.status==="running"||se.status==="stopped")){He[qe]={...se,status:pe.success===!1?"error":"done",args:pe.arguments??se.args,result:pe.result,error:pe.error,durationMs:pe.durationMs,liveOutput:void 0,createdAt:ye};break}}return He};O(H,ze=>{const He=[...ze],qe=Ae?He.findIndex(be=>be.id===Ae):-1;if(qe<0)return ze;const se=xe(He[qe].segments??[]),je=He[qe].committedSegments,Pe=je&&xe(je);return He[qe]={...He[qe],segments:se,committedSegments:Pe,isStreaming:!0},He},_e)}else if(pe.phase==="subagent_progress"&&pe.subagentEvent){const ye=xe=>{const ze=[...xe];for(let He=ze.length-1;He>=0;He--){const qe=ze[He];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){ze[He]={...qe,status:"running",subagentLogs:NO(qe.subagentLogs,pe.subagentEvent)};break}}return ze};m(H,xe=>{const ze=[...xe],He=Ae?ze.findIndex(Pe=>Pe.id===Ae):-1;if(He<0)return xe;const qe=ye(ze[He].segments??[]),se=ze[He].committedSegments,je=se&&ye(se);return ze[He]={...ze[He],segments:qe,committedSegments:je,isStreaming:!0},ze},_e)}}},Qt=pe=>{g.current===H&&(d.current=Date.now(),O(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(qe=>qe.id===Ae):-1;if(ze<0)return ye;const He=[...xe[ze].committedSegments??[]];if(pe.type==="thinking_commit")He.push({type:"text",content:"",thinking:pe.content,createdAt:pe.createdAt});else if(pe.type==="text_commit")He.push({type:"text",content:pe.content,createdAt:pe.createdAt});else return ye;return xe[ze]={...xe[ze],committedSegments:He,isStreaming:!0},xe},_e))},es=pe=>{if(g.current!==H)return;d.current=Date.now();const ye=(pe.segments??[]).map((xe,ze)=>xe.type==="tool"?{type:"tool",key:`${xe.tool}_${ze}`,tool:xe.tool??"tool",status:xe.status==="error"?"error":xe.status==="running"||xe.status==="stopped"?"running":"done",args:xe.arguments,result:xe.result,error:xe.error,durationMs:xe.durationMs,createdAt:xe.createdAt,...xe.subagentLogs?.length?{subagentLogs:xe.subagentLogs}:{}}:{type:"text",content:xe.content??"",thinking:xe.thinking,createdAt:xe.createdAt});O(H,xe=>{const ze=[...xe],He=Ae?ze.findIndex(qe=>qe.id===Ae):-1;return He<0?xe:(ze[He]={...ze[He],text:pe.content||ze[He].text,segments:ye,committedSegments:ye,isStreaming:!0,isStopped:!1},ze)},_e);for(const xe of ye)xe.type==="tool"&&x(H,{tool:xe.tool,phase:xe.status==="running"||xe.status==="stopped"?"start":"end",success:xe.status!=="error",arguments:xe.args,result:xe.result,error:xe.error,durationMs:xe.durationMs,ts:Date.now()},_e)},de=8;let ge=null;const me=pe=>{g.current===H&&O(H,ye=>{const xe=ye.map((He,qe)=>({m:He,j:qe})).reverse().find(He=>He.m.sender==="agent"&&He.m.isStreaming)?.j??-1;if(xe<0||ye[xe].reconnecting===pe)return ye;const ze=[...ye];return ze[xe]={...ze[xe],reconnecting:pe},ze},_e)};for(let pe=1;pe<=de;pe++){if(Ue.signal.aborted)return;try{ge=await ie.sessions.reattachStream(ke,_e,{onChunk:Lt,onThinking:it,onActivity:At,onCommit:Qt,onSnapshot:es},Ue.signal,0)}catch(xe){if(Ue.signal.aborted)throw xe;ge=null}if(!ge||!ge.attached){ge=null;break}if(ge.terminal)break;me(!0);const ye=await ie.sessions.streamStatus(ke,_e).catch(()=>null);if(ye?.messageId&&(Tt=ye.messageId),!ye||!ye.active||ye.status==="not_found"||ye.status==="idle"){me(!1),ge=null;break}await new Promise(xe=>setTimeout(xe,Math.min(800*pe,4e3))),me(!1)}if(!ge){k(H),P(H,_e),g.current===H&&(V(!1),Tt&&Ae&&O(H,pe=>ka(pe,Ae,Tt),_e),Le(_e,H).catch(()=>{}).finally(()=>{O(H,pe=>fu(pe,"done"),_e)})),i(Ue);return}if(g.current===H){let pe;O(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(je=>je.id===Ae):-1,He=ze>=0?ze:xe.map((je,Pe)=>({m:je,j:Pe})).reverse().find(je=>je.m.sender==="agent"&&je.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];if(!qe.isStreaming)return ye;pe=qe.id;const se=ge.segments?.length?DO(ge.segments,qe.segments):void 0;return xe[He]={...qe,text:ge.content||qe.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...se?{segments:se,committedSegments:se}:{}},xe},_e),pe&&O(H,ye=>ka(ye,pe,ge.messageId),_e),V(!1)}k(H),P(H,_e),i(Ue)}catch(Ze){const Je=Ue?[...t.current.values()].includes(Ue):!1;i(Ue),k(H);const mt=l.current.has(_e);if(mt&&P(H,_e),g.current===H&&(V(!1),Je&&mt&&O(H,lt=>fu(lt),_e)),Ze instanceof Error&&Ze.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),$e=w.useCallback(async(ke,_e)=>{const H=f.current,Ue=Z2({text:H.input,chips:H.chatContext??[]}),Ze=ke?ke.trim():Ue.text,Je=ke?ke.trim():Ue.titleSource,mt=ke?void 0:Ue.chips.length>0?Ue.chips:void 0;if(!Ze&&H.pendingImages.length===0||H.chatMode==="direct"&&!H.selectedAgent)return;ae();const lt=Date.now(),Tt=h.current;if(!_e?.isRetry&&!_e?.isResume&&Ze&&Tt&&Tt.text===Ze&&lt-Tt.at<1500)return;if(h.current={text:Ze,at:lt},_e?.isResume){const Et=_e.sessionIdOverride??H.activeSessionId??"";if(lt-(u.current.get(Et)??0)<2e3)return;u.current.set(Et,lt)}if(H.sending&&H.chatMode==="direct"){if(ZC({liveSessions:T(g.current),sendSessionId:H.activeSessionId})){const Ot=g.current;if([...b(Ot)??[]].reverse().find(it=>it.sender==="user")?.text===Ze&&!_e?.isRetry&&!_e?.isResume){n(H.activeSessionId??st);const it=$f(H.activeSessionId,st);return it.kind==="cancel"&&ie.agents.cancelProcessing(H.selectedAgent,it.target).catch(()=>{}),C(Ot,H.activeSessionId),O(Ot,At=>{const Qt=[...At];return Qt.length>0&&Qt[Qt.length-1].sender==="agent"&&Qt.pop(),Qt.length>0&&Qt[Qt.length-1].sender==="user"&&Qt[Qt.length-1].text===Ze&&Qt.pop(),Qt}),await new Promise(At=>setTimeout(At,50)),$e(Ze,{isRetry:!0})}n(H.activeSessionId??st);const Lt=$f(H.activeSessionId,st);Lt.kind==="cancel"&&ie.agents.cancelProcessing(H.selectedAgent,Lt.target).catch(()=>{}),C(Ot,H.activeSessionId),O(Ot,it=>IO(it)),await new Promise(it=>setTimeout(it,50))}}else if(H.sending&&H.chatMode!=="direct"){n(f.current.activeSessionId??g.current);const Et=g.current;C(Et),O(Et,Ot=>IO(Ot)),await new Promise(Ot=>setTimeout(Ot,50))}const gt=H.pendingImages.length>0?H.pendingImages.map(Et=>Et.dataUrl):void 0,_t=H.pendingImages.length>0?H.pendingImages.map(Et=>Et.name):void 0,Ee=A(H.chatMode,H.selectedAgent??"",H.activeChannel??"",H.activeDmUserId),kt=H.chatReplyTo;ke||(W(""),ce([])),j([]),B(!1),X(null);const ds=H.chatMode==="dm";M(Ee);const bt=H.activeSessionId??Ee;if(p.set(bt,[]),g.current===Ee&&!ds&&(V(!0),U([])),H.chatMode==="dm"){const Et=ee(H.authUser?.id??"",H.activeDmUserId),Ot=`opt_${Date.now()}`,Wt={id:Ot,sender:"user",text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};gt?.length&&(Wt.images=gt),kt&&(Wt.replyToId=kt.id,Wt.replyToSender=kt.sender,Wt.replyToText=kt.text),O(Ee,Ae=>[...Ae,Wt]);try{const Ae=await ie.channels.sendMessage(Et,{text:Ze,senderName:H.authUser?.name??fe("page.fallbackYou"),senderId:H.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...gt?.length?{images:gt}:{},..._t?.length?{fileNames:_t}:{}});Ae.userMessage&&F(Ae.userMessage.id),O(Ee,Lt=>{const it=Lt.filter(Qt=>Qt.id!==Ot),At=[];return Ae.userMessage&&At.push(Dn(Ae.userMessage,H.authUser?.id)),At.length>0?[...it,...At]:Lt})}catch(Ae){Bc(Ae)&&Wc(),QO(Ae)&&(W(Ze),j(H.pendingImages)),O(Ee,Lt=>[...Lt.filter(At=>At.id!==Ot),{id:`err_${Date.now()}`,sender:"agent",text:fe("page.errorWithMessage",{message:String(Ae)}),time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}])}N(Ee),g.current===Ee&&V(!1)}else if(H.chatMode==="channel"){const Et=`opt_${Date.now()}`,Ot={id:Et,sender:"user",text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};kt&&(Ot.replyToId=kt.id,Ot.replyToSender=kt.sender,Ot.replyToText=kt.text),O(Ee,Ae=>[...Ae,Ot]);const Wt=VC(Ze);H.groupChats.find(Ae=>Ae.channelKey===H.activeChannel);try{const Ae=await ie.channels.sendMessage(H.activeChannel,{text:Ze,senderName:H.authUser?.name??fe("page.fallbackYou"),mentions:Wt,senderId:H.authUser?.id,orgId:"default",replyToId:kt?.id,...gt?.length?{images:gt}:{},..._t?.length?{fileNames:_t}:{}});Ae.userMessage&&F(Ae.userMessage.id),Ae.agentMessage&&F(Ae.agentMessage.id),Ae.agentStopped&&O(Ee,Lt=>[...Lt,{id:`stopped_${Date.now()}`,sender:"agent",text:Ae.notice??fe("page.agentStopped"),time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}]),O(Ee,Lt=>{const it=Lt.filter(Qt=>Qt.id!==Et),At=[];return Ae.userMessage&&At.push(Dn(Ae.userMessage,H.authUser?.id)),Ae.agentMessage&&At.push(Dn(Ae.agentMessage,H.authUser?.id)),At.length>0?[...it,...At]:Lt})}catch(Ae){Bc(Ae)&&Wc();const Lt=QO(Ae);Lt&&(W(Ze),j(H.pendingImages));const it=oh(Ae,fe)||fe("page.errorWithMessage",{message:String(Ae)});O(Ee,At=>[...Lt?At.filter(es=>es.id!==Et):At,{id:`err_${Date.now()}`,sender:"agent",text:it,time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}])}N(Ee),g.current===Ee&&V(!1)}else{y(Ee);const Et=_e?.isResume?b(Ee)??[]:[],Ot=_e?.isResume?FC(Et):-1,Wt=Ot>=0?Et[Ot].id:void 0,Ae=Wt??Xv(),Lt=Xv();let it=_e?.sessionIdOverride??(H.activeSessionId===st?null:H.activeSessionId??null);if(_e?.isResume){const se=new Date().toISOString();O(Ee,je=>{if(Wt){const Pe=je.findIndex(be=>be.id===Wt);if(Pe>=0)return je.map((be,Te)=>Te===Pe?{...be,isStreaming:!0,isStopped:!1,isError:!1}:be)}return[...je,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:se,segments:[],isStreaming:!0}]},it)}else{const se=new Date().toISOString(),je=UC({id:Lt,text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:se,chips:mt,images:gt,replyTo:kt});O(Ee,Pe=>[...Pe,je,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:se,segments:[],isStreaming:!0}],it)}const At=se=>{d.current=Date.now(),m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=Pe[be];return Pe[be]={...Te,text:(Te.text??"")+se,segments:MO(Te.segments??[],se)},Pe},it)},Qt=se=>{d.current=Date.now(),m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=Pe[be];return Pe[be]={...Te,segments:LO(Te.segments??[],se)},Pe},it)},es=se=>{if(d.current=Date.now(),se.type==="session_start"&&se.sessionId){const je=it;if(it=se.sessionId,l.current.delete(se.sessionId),je&&je!==se.sessionId&&(P(Ee,je),H.selectedAgent&&je===st&&(ls.applyLocalOptimistic(H.selectedAgent,je,!1),ls.applyLocalOptimistic(H.selectedAgent,se.sessionId,!0))),_(Ee,se.sessionId),se.userMessageId&&!_e?.isResume&&O(Ee,Pe=>Pe.map(be=>be.id===Lt?{...be,id:se.userMessageId}:be),se.sessionId),g.current===Ee){const Pe=H.activeSessionId;(!Pe||Pe===st||Pe===se.sessionId)&&(Z(se.sessionId),R(Ee,se.sessionId),a(se.sessionId),H.selectedAgent&&K(H.selectedAgent,se.sessionId),le(be=>be.some(Te=>Te.id===st)?be.map(Te=>Te.id===st?{...Te,id:se.sessionId}:Te):be.some(Te=>Te.id===se.sessionId)?be:[...be,{id:se.sessionId,agentId:H.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=[...Pe[be].committedSegments??[]];return se.type==="thinking_commit"?Te.push({type:"text",content:"",thinking:se.content,createdAt:se.createdAt}):Te.push({type:"text",content:se.content,createdAt:se.createdAt}),Pe[be]={...Pe[be],committedSegments:Te},Pe},it)},de=se=>{d.current=Date.now(),se.phase!=="heartbeat"&&((se.phase==="start"||se.phase==="end")&&x(Ee,{...se,phase:se.phase,ts:Date.now()},it),se.phase==="start"?O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(ut=>ut.id===Ae);if(be<0)return je;const Te=[...Pe[be].segments??[]];let Fe=!1;if(se.arguments)for(let ut=Te.length-1;ut>=0;ut--){const xt=Te[ut];if(xt.type==="tool"&&xt.tool===se.tool&&xt.status==="running"){Te[ut]={...xt,args:se.arguments},Fe=!0;break}}const nt=`${se.tool}_${Date.now()}`,Ct=new Date().toISOString();Fe||Te.push({type:"tool",key:nt,tool:se.tool,status:"running",args:se.arguments,createdAt:Ct});const pt=[...Pe[be].committedSegments??[]];return se.arguments!==void 0&&pt.push({type:"tool",key:nt,tool:se.tool,status:"running",args:se.arguments,createdAt:Ct}),Pe[be]={...Pe[be],segments:Te,committedSegments:pt},Pe},it):se.phase==="output"?m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=[...Pe[be].segments??[]];for(let Fe=Te.length-1;Fe>=0;Fe--){const nt=Te[Fe];if(nt.type==="tool"&&nt.tool===se.tool&&nt.status==="running"){Te[Fe]={...nt,liveOutput:GC(nt.liveOutput,se.output??"")};break}}return Pe[be]={...Pe[be],segments:Te},Pe},it):se.phase==="subagent_progress"&&se.subagentEvent?m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Ct=>Ct.id===Ae);if(be<0)return je;const Te=Ct=>{const pt=[...Ct];for(let ut=pt.length-1;ut>=0;ut--){const xt=pt[ut];if(xt.type==="tool"&&(xt.tool==="spawn_subagent"||xt.tool==="spawn_subagents")&&xt.status==="running"){pt[ut]={...xt,subagentLogs:NO(xt.subagentLogs,se.subagentEvent)};break}}return pt},Fe=Te(Pe[be].segments??[]),nt=Te(Pe[be].committedSegments??[]);return Pe[be]={...Pe[be],segments:Fe,committedSegments:nt},Pe},it):O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(pt=>pt.id===Ae);if(be<0)return je;const Te=new Date().toISOString(),Fe=[...Pe[be].segments??[]];let nt;for(let pt=Fe.length-1;pt>=0;pt--){const ut=Fe[pt];if(ut.type==="tool"&&ut.tool===se.tool&&ut.status==="running"){nt=ut.subagentLogs,Fe[pt]={...ut,status:se.success===!1?"error":"done",args:se.arguments,result:se.result,error:se.error,durationMs:se.durationMs,liveOutput:void 0,createdAt:Te};break}}const Ct=[...Pe[be].committedSegments??[]];for(let pt=Ct.length-1;pt>=0;pt--){const ut=Ct[pt];if(ut.type==="tool"&&ut.tool===se.tool&&ut.status==="running"){Ct[pt]={...ut,status:se.success===!1?"error":"done",args:se.arguments,result:se.result,error:se.error,durationMs:se.durationMs,liveOutput:void 0,createdAt:Te,subagentLogs:nt??ut.subagentLogs};break}}return Pe[be]={...Pe[be],segments:Fe,committedSegments:Ct},Pe},it))},ge=new AbortController;e.current.set(f.current.activeSessionId??st,ge);const me=it,pe=me;pe&&l.current.delete(pe),pe&&_(Ee,pe),H.selectedAgent&&ls.applyLocalOptimistic(H.selectedAgent,pe??st,!0);try{d.current=Date.now();const se=await ie.agents.messageStream(H.selectedAgent,Ze,{onChunk:At,onThinking:Qt,onActivity:de,onCommit:es},{signal:ge.signal,images:gt,sessionId:me,isRetry:_e?.isRetry,isResume:_e?.isResume,fileNames:_t,replyTo:kt,titleSource:Je,chips:mt,userMessageId:Lt,assistantMessageId:Ae});if(g.current===Ee){if(se.merged&&O(Ee,Pe=>Pe.filter(be=>be.id!==Ae&&be.id!==Lt),it),!se.merged&&se.segments?.length&&O(Ee,Pe=>{const be=[...Pe],Te=be.findIndex(pt=>pt.id===Ae);if(Te<0)return Pe;const Fe=DO(se.segments,be[Te].segments);let nt=se.content||be[Te].text;nt||(nt=Fe.filter(pt=>pt.type==="text").map(pt=>pt.content).join(""));const Ct=se.emptyReply===!0;return be[Te]={...be[Te],text:nt,segments:Fe,committedSegments:Fe,isStopped:se.cancelled||be[Te].isStopped,emptyReply:se.emptyReply||Ct||void 0,isError:se.emptyReply||Ct?!0:be[Te].isError},be},it),!se.merged&&!se.segments?.length&&O(Ee,Pe=>{const be=[...Pe],Te=be.findIndex(xt=>xt.id===Ae);if(Te<0)return Pe;const Fe=be[Te],nt=Fe.committedSegments??[],pt=nt.filter(xt=>xt.type==="text"&&!!xt.content).map(xt=>xt.content).join("")||se.content||Fe.text,ut=se.emptyReply===!0;return(nt.length>0||pt||se.cancelled||se.emptyReply||ut)&&(be[Te]={...Fe,text:pt,segments:nt.length>0?nt:Fe.segments,isStopped:se.cancelled||Fe.isStopped,emptyReply:se.emptyReply||ut||void 0,isError:se.emptyReply||ut?!0:Fe.isError}),be},it),se.sessionId){Z(be=>!be||be===st||be===se.sessionId?se.sessionId:be);const Pe=v.get(Ee);(!Pe||Pe===st||Pe===se.sessionId)&&(R(Ee,se.sessionId),a(se.sessionId)),le(be=>be.some(Te=>Te.id===st)?be.map(Te=>Te.id===st?{...Te,id:se.sessionId}:Te):be.some(Te=>Te.id===se.sessionId)?be:[...be,{id:se.sessionId,agentId:H.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}re(H.selectedAgent).then(Pe=>{if(g.current===Ee&&(J(Pe),se.sessionId)){const be=Pe.find(Te=>Te.id===se.sessionId);be&&le(Te=>Te.some(nt=>nt.id===be.id)?Te.map(nt=>nt.id===be.id?be:nt):[be,...Te.filter(nt=>nt.id!==st)])}});const je=se.sessionId??(pe&&pe!==st?pe:null);if(!ge.signal.aborted&&!se.merged&&(se.softDisconnected??se.segments===void 0)&&H.chatMode==="direct"&&H.selectedAgent&&je){const Pe=H.selectedAgent;let be=!1,Te;for(let Fe=0;Fe<4&&!be&&(Fe>0&&await new Promise(nt=>setTimeout(nt,350*Fe)),!ge.signal.aborted);Fe+=1)try{const nt=await ie.sessions.streamStatus(Pe,je);if(nt.messageId&&(Te=nt.messageId),o0({aborted:ge.signal.aborted,sawTerminal:!1,serverStatus:a0(nt.status)})==="reattach"){O(Ee,pt=>pt.map(ut=>ut.id===Ae?{...ut,isStreaming:!0,isStopped:!1,segments:(ut.segments??[]).map(xt=>xt.type==="tool"&&(xt.status==="stopped"||xt.status==="running")?{...xt,status:"running"}:xt)}:ut),je),N(Ee),r(ge),_(Ee,je),k(Ee),Me(Pe,je,Ee),be=!0;return}break}catch{}if(!be&&!ge.signal.aborted){Te&&Ae&&O(Ee,Fe=>ka(Fe,Ae,Te),je);try{if(await Le(je,Ee)>0){N(Ee),r(ge),k(Ee);return}}catch{}}}}!se.merged&&(it||g.current===Ee)&&O(Ee,je=>ka(je,Ae,se.messageId),it)}catch(se){const je=se?.sessionId;je&&H.chatMode==="direct"&&g.current===Ee&&(Z(je),R(Ee,je),a(je),le(be=>be.map(Te=>Te.id===st?{...Te,id:je}:Te)),re(H.selectedAgent).then(be=>{if(g.current!==Ee)return;J(be);const Te=be.find(Fe=>Fe.id===je);Te&&le(Fe=>Fe.some(Ct=>Ct.id===Te.id)?Fe.map(Ct=>Ct.id===Te.id?Te:Ct):[Te,...Fe])})),Bc(se)&&Wc();const Pe=oh(se,fe);Pe?O(Ee,be=>{const Te=[...be],Fe=Te.findIndex(nt=>nt.id===Ae);return Fe>=0&&(Te[Fe]={...Te[Fe],text:Pe,isError:!0}),Te},it):O(Ee,be=>{const Te=[...be],Fe=Te.findIndex(nt=>nt.id===Ae);if(Fe>=0){const nt=BO(Te[Fe],"stopped");if(nt===null)return be.filter(Ct=>Ct.id!==Ae);Te[Fe]=nt}return Te},it)}O(Ee,se=>HC(se,Ae),it),ge.signal.aborted&&O(Ee,se=>{const je=[...se],Pe=je.findIndex(be=>be.id===Ae);if(Pe>=0){const be=BO(je[Pe],"stopped");if(be===null)return se.filter(Te=>Te.id!==Ae);je[Pe]=be}return je},it);const xe=(b(Ee)??[]).find(se=>se.id===Ae),ze=H.activeSessionId&&H.activeSessionId!==st?H.activeSessionId:null,He=xe?YC(xe):!1;xe&&!He&&H.chatMode==="direct"&&ze&&!ge.signal.aborted&&await(async(je,Pe)=>{for(let be=0;be<je;be++){const Te=TC(be,{baseMs:Pe,maxMs:8e3,maxAttempts:je});await new Promise(Fe=>setTimeout(Fe,Te));try{const nt=(await ie.sessions.getMessages(ze,2)).messages.find(Ct=>Ct.role==="assistant");if(nt?.content){const Ct=ah(nt);O(Ee,pt=>{const ut=[...pt],xt=ut.findIndex(Yn=>Yn.id===Ae);return xt>=0&&(ut[xt]={...ut[xt],text:Ct.text,segments:Ct.segments}),ut},it),O(Ee,pt=>ka(pt,Ae,Ct.id),it);return}}catch{}}})(5,2e3);const qe=N(Ee);P(Ee,it??st),H.selectedAgent&&ls.applyLocalOptimistic(H.selectedAgent,it??st,!1),k(Ee),[...e.current.values()].includes(ge)||e.current.size===0?(r(ge),p.delete(it??Ee),g.current===Ee&&(V(qe>0),qe===0&&U([]))):p.delete(it??Ee)}},[x,y,P,g,N,k,M,re,b,V,_,f,O,m]);return{send:$e,stopSending:we,tryReattachActiveStream:Me,loadSessionMessages:Le}}function f3({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=yt("team"),[n,a]=w.useState(!1),[o,l]=w.useState("agent"),[h,u]=w.useState(""),[d,f]=w.useState(!1),[p,v]=w.useState([]),[b,g]=w.useState(null),O=w.useRef(null),m=w.useCallback(async()=>{f(!0);try{const _=await QC(),T=_.providers?.markus;if(T?.configured&&T.enabled!==!1&&(!T.models||T.models.length===0))try{const E=await fetch("/api/models/live/markus",{credentials:"include"});if(E.ok){const I=await E.json();I.models?.length&&(T.models=I.models)}}catch{}const R=[];for(const[E,I]of Object.entries(_.providers??{})){if(!I.configured||I.enabled===!1)continue;const V=(I.models??[]).filter(S2).map(U=>({id:U.id,name:U.name}));V.length!==0&&R.push({provider:E,displayName:I.displayName??E,models:V})}R.sort((E,I)=>E.displayName.localeCompare(I.displayName)),v(R);const M=E=>!E?.provider||!E.model?!1:!!R.find(V=>V.provider===E.provider)?.models.some(V=>V.id===E.model);let N=null;if(_.routingDefaultModel?.provider&&_.routingDefaultModel?.model)N={provider:_.routingDefaultModel.provider,model:_.routingDefaultModel.model};else if(_.defaultProvider){const E=_.providers?.[_.defaultProvider];E?.model&&(N={provider:_.defaultProvider,model:E.model})}if(N&&!M(N)){const E=R.find(V=>V.provider==="markus"),I=E?.models[0]?{provider:"markus",model:E.models[0].id}:R[0]?.models[0]?{provider:R[0].provider,model:R[0].models[0].id}:null;I?(N=I,ie.settings.updateRouting({defaultProvider:I.provider,routingDefaultModel:I}).then(()=>Kv()).catch(()=>{})):N=null}g(N)}catch{v([])}finally{f(!1)}},[]);w.useEffect(()=>{m()},[m]),w.useEffect(()=>{n&&(l("agent"),u(""),m())},[n,m]),w.useEffect(()=>{if(!n)return;const _=T=>{O.current?.contains(T.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=w.useMemo(()=>{const _=h.trim().toLowerCase();return p.map(T=>({...T,models:_?T.models.filter(R=>R.id.toLowerCase().includes(_)||(R.name?.toLowerCase().includes(_)??!1)||T.displayName.toLowerCase().includes(_)||T.provider.toLowerCase().includes(_)):T.models})).filter(T=>T.models.length>0)},[p,h]),y=w.useCallback(_=>!_?.provider||!_.model?!1:p.length===0?!0:!!p.find(R=>R.provider===_.provider)?.models.some(R=>R.id===_.model),[p]);w.useEffect(()=>{if(!s||p.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const T=p.find(R=>R.provider==="markus");return T?.models[0]?{provider:"markus",model:T.models[0].id}:p[0]?.models[0]?{provider:p[0].provider,model:p[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!0})},[s,p,b,y,e]);const k=s&&y(s)?s:b,P=(k?.model?k.model.includes("/")?k.model.split("/").pop():k.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-[110px] md: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:k?`${k.provider}: ${k.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:P}),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:_=>u(_.target.value),placeholder:i("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-primary 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(ZO,{checked:o==="global",onChange:()=>l("global"),label:i("chatModel.applyGlobal",{defaultValue:"Apply to global"}),size:"sm",disabled:!t})]}),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(ZO,{checked:o==="agent",onChange:()=>l("agent"),label:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"}),size:"sm",disabled:!t})]}),!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:[d&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!d&&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"})}),!d&&x.length>0&&c.jsx("div",{className:"px-3 pb-1 text-[10px] text-fg-tertiary",children:i("chatModel.chatOnlyHint",{defaultValue:"Only models with a chat interface are listed"})}),!d&&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(T=>{const R=k?.provider===_.provider&&k?.model===T.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:T.id},o),o==="global"&&g({provider:_.provider,model:T.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-primary transition-colors ${R?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:T.id}),R&&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}:${T.id}`)})]},_.provider))]})]})]})}async function zv(s,e,t,r){if(e==="agent"){if(!t)return;await ie.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}});return}t&&r?.resetCurrentAgent!==!1&&await ie.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),await ie.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}}),Kv()}const qv="markus_team_sidebars_c";function Fp(s,e){return s.id===st?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Zv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):Fp(s,e)}const Up=new Set;function p3(){return window.location.hash}function m3(s){return Up.add(s),()=>{Up.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Up.forEach(s=>s()));function L3({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=yt(["team","common"]),a=w.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Gp(Ht.TEAM),[l,h]=w.useState(r?.agents??[]),[u,d]=w.useState(r?.humans??[]),[f,p]=w.useState(!r),v=Yp(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),g=w.useSyncExternalStore(m3,p3),O=v&&(g.startsWith(`#${Ht.TEAM}/`)||g.startsWith("#chat/")),m=v&&g.match(/^#team\/t\/(.+)$/),x=v?m?"team":O?"chat":"roster":"roster",y=m?m[1]:null;w.useEffect(()=>($O(v&&x==="chat"),()=>$O(!1)),[v,x]),w.useEffect(()=>(jO(Ht.TEAM,v&&x!=="roster"?1:0),()=>jO(Ht.TEAM,0)),[v,x]);const k=w.useCallback(()=>{window.location.hash=`${Ht.TEAM}/d`},[]),C=w.useCallback(S=>{window.location.hash=`${Ht.TEAM}/t/${S}`},[]);w.useEffect(()=>{if(!v)return;const S=()=>{qi(T.current)&&_("chat")};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[v]);const[P,_]=w.useState("chat"),T=w.useRef("chat");T.current=P;const R=RO({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[M,N]=w.useState(()=>{try{return localStorage.getItem(qv)==="1"}catch{return!1}}),E=w.useCallback(S=>{N(S);try{localStorage.setItem(qv,S?"1":"0")}catch{}},[]),I=Zo(),V=I?.leftCollapsed??!1,U=I?.rightPanel??null,W=I?.rightPanelTabs??[],ce=I?.activeRightPanelTabId??null,j=I?.rightPanelFullscreen??!1,B=U?"2xl:pr-8":"2xl:pr-[280px]",X=I?.setHostAvailable,Z=I?.collapseRightPanelOnly??I?.toggleRightPanel,K=I?.openRightPanel,le=400,J=320,G=6,[q,A]=w.useState(typeof window<"u"?window.innerWidth:1440),[ee,F]=w.useState("auto"),ae=w.useRef(V);w.useEffect(()=>{ae.current!==V&&(ae.current=V,N(V))},[V]);const re=I?.keyboardPane??"content",fe=w.useRef(!1),Le=w.useRef(re);w.useEffect(()=>{if(t||v||!o)return;const S=Le.current;Le.current=re,(re==="l1"||re==="l2")&&S!==re&&M&&(N(!1),I?.setLeftCollapsed(!1))},[re,t,v,o,M,I]),w.useEffect(()=>{if(t||v||!o)return;const S=Q=>{const $=I?.keyboardPane??"content";if($==="l0"||$==="l1"||$==="l2"||Q.metaKey||Q.ctrlKey||Q.altKey)return;if(Q.target instanceof HTMLElement){const Y=Q.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||Q.target.isContentEditable||Q.target.closest(".xterm"))return}const D=Q.key.length===1?Q.key.toLowerCase():Q.key;D!=="h"&&D!=="ArrowLeft"||(Q.preventDefault(),M&&(E(!1),I?.setLeftCollapsed(!1)),I?.setKeyboardPane(fe.current?"l2":"l1"))};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,v,o,I,M,E]),w.useEffect(()=>{if(X)return X(o&&!v),()=>X(!1)},[o,v,X]),w.useEffect(()=>t||v||!o?void 0:St.on("ui:right_panel",Q=>{const $=Q.payload;if($.action==="collapse"){Z?.();return}if($.action!=="open"||!$.panel||!K)return;const D=$.panel;if(D.kind==="url"&&D.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;K({kind:"url",url:D.url,title:D.title||D.url,browserId:Y});return}if(D.kind==="file"&&D.path){K({kind:"file",path:D.path,title:D.title});return}if(D.kind==="terminal"){const Y=D.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;K({kind:"terminal",terminalId:Y,title:D.title||"Terminal",cwd:D.cwd});return}D.kind==="deliverable"&&D.deliverableId&&ie.deliverables.get(D.deliverableId).then(Y=>{Y.deliverable&&K({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,Z,K]);const we=w.useCallback((S,Q)=>{const $=ud.current,D=Q??Ss.current?.selectionStart??$.text.length,Y=rm({text:$.text,chips:$.chips},S,D);Or(Y.draft.text),pn(Y.draft.chips),requestAnimationFrame(()=>{const te=Ss.current;te&&(te.focus(),te.setSelectionRange(Y.caret,Y.caret))})},[]),Me=w.useCallback(S=>{if(!S)return;let Q=0;const $=m2(S,()=>`ctx_${Date.now()}_${++Q}`);if($.length===0)return;const D=ud.current,Y=F2({text:D.text,chips:D.chips},$);Or(Y.draft.text),pn(Y.draft.chips),requestAnimationFrame(()=>{const te=Ss.current;te&&(te.focus(),te.setSelectionRange(Y.caret,Y.caret))})},[]),$e=w.useRef(null),[ke,_e]=w.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),H=RO({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Ue=w.useRef(null),[Ze,Je]=w.useState(!1),[mt,lt]=w.useState(!1),Tt=w.useCallback(()=>{Ze?lt(S=>!S):_e(S=>{const Q=!S;try{localStorage.setItem("markus_team_panel_visible",String(Q))}catch{}return Q})},[Ze]);w.useEffect(()=>{if(v)return;const S=Ue.current;if(!S)return;const Q=new ResizeObserver(([$])=>{if(!$)return;const D=$.contentRect.width;if(A(D),!t){const Y=D-R.width-H.width;Je(Y<400)}});return Q.observe(S),()=>Q.disconnect()},[v,t,R.width,H.width]);const gt=ke&&!Ze&&!mt,_t=M?0:R.width+G+(gt?H.width+G:0),Ee=Math.max(0,q-_t-G-8),kt=Math.min(le,Math.floor(Ee*.4)),ds=Math.max(0,Ee-kt),bt=Math.min(Math.round(Ee/2),ds),Ot=Math.max(0,Math.min(ee==="auto"?bt:ee,ds)),Wt=w.useRef(!1);w.useEffect(()=>{const S=(I?.rightPanel??null)!==null;S&&!Wt.current&&(N(!0),F("auto")),Wt.current=S},[I?.rightPanel]);const Ae=w.useRef(Ot);Ae.current=Ot;const Lt=w.useRef(ds);Lt.current=ds;const it=w.useCallback(S=>{S.preventDefault();const Q=S.clientX,$=Ae.current,D=te=>{const ne=$+(Q-te.clientX),Qe=Lt.current,De=Math.min(J,Qe);F(Math.max(De,Math.min(Qe,ne)))},Y=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",D),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);w.useEffect(()=>{if(!mt)return;const S=Q=>{Q.target.closest("[data-l2-floating]")||lt(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[mt]);const[At,Qt]=w.useState(null),[es,de]=w.useState(!1),ge=w.useRef(null);w.useEffect(()=>{if(!es)return;const S=$=>{ge.current&&!ge.current.contains($.target)&&de(!1)},Q=$=>{$.key==="Escape"&&de(!1)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",Q)}},[es]);const[me,pe]=w.useState(),[ye,xe]=w.useState(),[ze,He]=w.useState(),[qe,se]=w.useState(!1),[je,Pe]=w.useState(""),[be,Te]=w.useState(!1),[Fe,nt]=w.useState(""),Ct=w.useRef(null),pt=w.useRef(null),ut=w.useCallback((S,Q)=>{const $=S?nh[S]:void 0,D=$?"overview":S;xe($),pe(D),He(Q),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(D??"overview")},[v]);w.useCallback(S=>{S==="profile"?ut():qi(T.current)?history.back():_("chat")},[ut]);const xt=w.useCallback((S,Q)=>{$t("direct"),Ns(S),v&&k(),ut(Q?.tab,Q?.highlightMailboxId),Qt(null)},[v,k,ut]),Yn=w.useCallback((S,Q)=>{const $=l.find(D=>D.name.toLowerCase()===S.toLowerCase());if($){const D=Q.target.getBoundingClientRect();Qt({agentId:$.id,top:D.bottom,left:D.left})}},[l]),Vs=w.useMemo(()=>l.map(S=>S.name),[l]),[he,$t]=w.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[Se,Ns]=w.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[ft,Ds]=w.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Xt,ji]=w.useState(""),jl=500,ln=w.useRef(new Set),hd=S=>{if(ln.current.add(S),ln.current.size>jl){const Q=Math.floor(jl*.2),$=ln.current.values();for(let D=0;D<Q;D++){const Y=$.next().value;Y&&ln.current.delete(Y)}}},cn=w.useMemo(()=>{if(r?.channelMessages){const S=r.activeChannel??"custom:general";return r.channelMessages.filter(Q=>Q.channel===S).map(Q=>Dn(Q))}},[]),{manager:It,messages:rs,setMessages:$s,sending:cs,setSending:Ri,activities:hn,setActivities:dn,activeSessionBuffer:un,actBuffers:Gn,sessionTabsBuffer:Go,readConvMsgs:Fs,writeConvMsgs:sr,setActiveSession:z,currentConvKeyRef:oe,updateConvMsgs:Oe,updateConvMsgsRaf:We,appendConvActivity:Ge,beginLoad:et,beginStream:ot,endStream:jt,resetConv:at,abortStream:Os,loadAndDisplay:xs,incrementSending:rr,decrementSending:li,isSendingFor:Wr,setStreamSession:gr,clearStreamSession:us,getStreamSession:Xr,saveSessionToCache:dd,restoreSessionFromCache:Yt}=d3(cn),[qt,Or]=w.useState(""),[fn,Rl]=w.useState(null),[xr,pn]=w.useState([]),ud=w.useRef({text:"",chips:[]});ud.current={text:qt,chips:xr};const[El,Al]=w.useState(!!r?.streamLastMessage),mn=w.useRef(null),q_=400;w.useEffect(()=>(cs?(mn.current&&(clearTimeout(mn.current),mn.current=null),Al(!0)):El&&(mn.current=setTimeout(()=>{Al(!1),mn.current=null},q_)),()=>{mn.current&&clearTimeout(mn.current)}),[cs]);const fd=w.useRef({fullText:"",timers:[]});w.useEffect(()=>{if(!t||!r?.streamLastMessage||rs.length===0)return;const S=rs[rs.length-1];if(!S||S.sender!=="agent")return;const Q=S.text;fd.current.fullText=Q;const $=fd.current.timers;function D(){let te=0;$s(Qe=>Qe.map((De,ve)=>ve===Qe.length-1?{...De,text:""}:De)),Al(!0);const ne=setInterval(()=>{if(te+=1+Math.floor(Math.random()*2),te>=Q.length){clearInterval(ne),$s(ve=>ve.map((Ce,Be)=>Be===ve.length-1?{...Ce,text:Q}:Ce));const Qe=setTimeout(()=>Al(!1),800);$.push(Qe);const De=setTimeout(D,6e3);$.push(De)}else $s(Qe=>Qe.map((De,ve)=>ve===Qe.length-1?{...De,text:Q.slice(0,te)}:De))},30);$.push(ne)}const Y=setTimeout(D,1500);return $.push(Y),()=>{$.forEach(te=>clearTimeout(te)),fd.current.timers=[]}},[]);const[Z_,pg]=w.useState(!1),[pd,mg]=w.useState(!1),[V_,gg]=w.useState(!1);w.useEffect(()=>{if(!pd){gg(!1);return}const S=setTimeout(()=>gg(!0),250);return()=>clearTimeout(S)},[pd]);const[gn,zr]=w.useState(!0),[F_,md]=w.useState(!0),gd=w.useRef(0),[ir,Ml]=w.useState([]),[Og,xg]=w.useState(null),Od=w.useRef(null),Ss=w.useRef(null),[U_,Ei]=w.useState(null);w.useEffect(()=>{if(!Se){Ei(null);return}let S=!1;return ie.agents.get(Se).then(Q=>{if(S)return;const $=Q.effectiveModel;Ei($?.provider&&$?.model?{provider:$.provider,model:$.model}:null)}).catch(()=>{S||Ei(null)}),()=>{S=!0}},[Se]);const xd=w.useRef(!1),Ko=w.useCallback(()=>{const S=Ss.current;if(!S)return;const Q=xd.current,$=Q?36:52,D=qO(Q);S.style.height="auto";const Y=Math.max($,Math.min(S.scrollHeight,D));S.style.height=`${Y}px`,S.style.overflowY=Y>=D?"auto":"hidden"},[]);w.useEffect(()=>{const S=requestAnimationFrame(()=>Ko());return()=>cancelAnimationFrame(S)},[qt,ir.length,Ko]);const bd=S=>{try{const Q=localStorage.getItem(`markus_closed_tabs_${S}`);return Q?new Set(JSON.parse(Q)):new Set}catch{return new Set}},H_=(S,Q)=>{const $=bd(S);$.add(Q);try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...$]))}catch{}},Y_=(S,Q)=>{const $=bd(S);if($.delete(Q))try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...$]))}catch{}},bg=S=>{try{return localStorage.getItem(`markus_active_session_${S}`)}catch{return null}},Jo=(S,Q)=>{if(S)try{Q&&Q!==st?localStorage.setItem(`markus_active_session_${S}`,Q):localStorage.removeItem(`markus_active_session_${S}`)}catch{}},[Qr,Ai]=w.useState([]),[G_,Ll]=w.useState(0),[vg,Nl]=w.useState(1),[Dl,Il]=w.useState(!1),[Bl,yg]=w.useState(!1),[Ke,Mi]=w.useState(null),[ea,On]=w.useState(!1),[Sg,xn]=w.useState(!1),[vd,wg]=w.useState(null),[yd,Sd]=w.useState(""),[_g,wd]=w.useState([]),[bn,Wl]=w.useState(null),[K_,kg]=w.useState(null),[ta,_d]=w.useState([]),[vn,sa]=w.useState(null),[J_,Cg]=w.useState(null),Pg=w.useRef(new Set),[Tg,kd]=w.useState([]),[$r,ra]=w.useState(null),Li=$r?$r.items[$r.index]??null:null,[ek,Qg]=w.useState(null),[$g,Cd]=w.useState([]),[Is,tk]=w.useState([]),Us=S=>{tk(Q=>{const $=typeof S=="function"?S(Q):S,D=new Set,Y=$.filter(te=>D.has(te.id)?!1:(D.add(te.id),!0));return Y.some(te=>te.isMain)?[...Y.filter(te=>te.isMain),...Y.filter(te=>!te.isMain)]:Y})},jg=w.useRef(null);w.useEffect(()=>{if(!Ke)return;const S=jg.current;if(!S)return;const Q=S.querySelector(`[data-session-tab-id="${CSS.escape(Ke)}"]`);if(!Q)return;const $=requestAnimationFrame(()=>{Q.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($)},[Ke,Is.length]);const Xl=w.useRef(null),Pd=w.useRef(null),[ws,ia]=w.useState(r?.groupChats??[]),Td=w.useRef(ws);Td.current=ws;const Rg=w.useRef(null),[Qd,_s]=w.useState(!1),[$d,Kn]=w.useState(!1),[zl,jd]=w.useState(""),[sk,na]=w.useState(-1),[rk,ql]=w.useState([]),[ik,Eg]=w.useState(!1),Rd=w.useRef(void 0),[js,Ag]=w.useState(r?.teams??[]),[Ed,nk]=w.useState(!!r),[ok,ak]=w.useState([]),[Ad,Mg]=w.useState([]),[lk,ck]=w.useState(null),[x3,b3]=w.useState(!1),[v3,y3]=w.useState(""),[Jn,oa]=w.useState(!1),Zl=w.useRef(null),[Lg,hk]=w.useState(""),[aa,eo]=w.useState(0),[to,Vl]=w.useState(!1),[Ng,dk]=w.useState(""),[Md,la]=w.useState(0),[Ld,uk]=w.useState([]),Dg=w.useRef(!1),Nd=w.useCallback(()=>{Dg.current||(Dg.current=!0,(async()=>{try{const{skills:S}=await ie.skills.list();uk(S.map(Q=>({name:Q.name,description:Q.description??Q.name})))}catch{}})())},[]);w.useEffect(()=>{Nd()},[Nd]);const yn=Ng?Ld.filter(S=>S.name.toLowerCase().includes(Ng.toLowerCase())):Ld,[fk,pk]=w.useState([]),Ig=w.useRef(!1),mk=w.useCallback(()=>{Ig.current||(Ig.current=!0,(async()=>{const S=[];try{const[Q,$,D,Y,te]=await Promise.all([ie.projects.list().catch(()=>({projects:[]})),ie.requirements.list({lean:!0}).catch(()=>({requirements:[]})),ie.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),ie.deliverables.search({limit:100}).catch(()=>({results:[]})),ie.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const ne of Q.projects)S.push({id:ne.id,name:ne.name,entityType:"project",role:ne.status});for(const ne of $.requirements)S.push({id:ne.id,name:ne.title,entityType:"requirement",role:ne.priority});for(const ne of D.tasks)S.push({id:ne.id,name:ne.title,entityType:"task",role:ne.status});for(const ne of Y.results)S.push({id:ne.id,name:ne.title,entityType:"deliverable",role:ne.type});for(const ne of te.teams)try{const Qe=await ie.workflows.list(ne.id);for(const De of Qe.workflows)S.push({id:De.name,name:De.displayName||De.name,entityType:"workflow",role:`v${De.version}`})}catch{}}catch{}pk(S)})())},[]),is=he==="channel"?ws.find(S=>S.channelKey===ft)?.teamId:void 0,gk=w.useRef(null),qr=w.useRef(null),Bg=w.useRef(void 0),ca=w.useCallback((S,Q)=>{Mi(Q),S&&(Q===null?It.clearActiveSession(S):It.setActiveSession(S,Q))},[Mi,It]),Wg=w.useMemo(()=>Ma(he,Se,ft,Xt),[he,Se,ft,Xt]);lh();const ha=ls.isStreaming(Ke),Ok=ls.liveBubbleId(Ke),Sn=w.useMemo(()=>go(Wg,Ke),[Wg,Ke]),Bs=w.useRef(Sn);Bs.current=Sn;const[da,xk]=w.useState(Sn);if(w.useEffect(()=>{Ca.save(da,{text:qt,images:ir,context:xr,replyTo:fn})},[qt,da,ir,xr,fn]),da!==Sn){const S={text:qt,images:ir,context:xr,replyTo:fn};if(qt!==Ca.peek(da).text)Ca.save(Sn,S);else{Ca.save(da,S);const Q=Ca.get(Sn);Or(Q.text),Ml(Q.images),pn(Q.context),Rl(Q.replyTo)}xk(Sn)}const bs=w.useRef(null),Dd=w.useRef(null),ci=w.useRef(null),Id=w.useRef(null),Fl=w.useRef(0),Ul=w.useRef([]),so=w.useRef(null),Xg=w.useRef([]),Bd=w.useRef(void 0),Hl=w.useRef(null),wn=w.useCallback(()=>It.getActiveSession(oe.current)??oe.current,[It]),Ni=w.useCallback((S,Q)=>{S&&(It.setWindowBounds(S,Q),S===wn()&&pg(Q.hasMore))},[It,wn]);w.useEffect(()=>{pg(It.getWindowBounds(wn()).hasMore)},[It,wn,he,Se,ft,Xt,Ke]),w.useEffect(()=>{if(!ea)return;const S=Q=>{Pd.current&&!Pd.current.contains(Q.target)&&Xl.current&&!Xl.current.contains(Q.target)&&On(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[ea]);const Yl=(S,Q)=>{if(!Q||S===Q)return`notes:${S}`;const[$,D]=[S,Q].sort();return`dm:${$}:${D}`};w.useEffect(()=>{localStorage.setItem("markus_chat_mode",he)},[he]),w.useEffect(()=>{localStorage.setItem("markus_chat_agent",Se)},[Se]),w.useEffect(()=>{localStorage.setItem("markus_chat_channel",ft)},[ft]),w.useEffect(()=>{let S=!1;if(t||!Se||he!=="direct"){Ei(null);return}return ie.agents.get(Se).then(Q=>{if(S)return;const $=Q.config?.llmConfig;Ei($?.modelMode==="custom"&&$.primary&&$.defaultModel?{provider:$.primary,model:$.defaultModel}:null)}).catch(()=>{S||Ei(null)}),()=>{S=!0}},[Se,he,t]);const{counts:Wd,sessionAgentMap:ua,markRead:Xd,markReadMany:zg,setActiveKey:bk,clearActiveKeys:vk}=$C({enabled:!t}),Gl=w.useMemo(()=>{const S={};for(const[Q,$]of Object.entries(Wd))Q.startsWith("channel:")&&(S[Q.slice(8)]=$);return S},[Wd]),zd=jC(ua,Wd);w.useEffect(()=>{let S=0;for(const Q of zd.values())S+=Q;for(const Q of Object.values(Gl))S+=Q;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:S}}))},[zd,Gl]);const Kl=zd,yk=w.useCallback(async S=>{const Q=[];for(const[$,D]of Object.entries(ua))D===S&&Q.push(`session:${$}`);await zg(Q)},[ua,zg]);w.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(he==="direct"&&Se&&yk(Se),he==="channel"&&ft)Xd(`channel:${ft}`);else if(he==="direct"&&Ke)Xd(`session:${Ke}`);else if(he==="dm"&&Xt){const $=`dm:${[e?.id,Xt].sort().join(":")}`;Xd(`channel:${$}`)}const Q=[];if(he==="direct"&&Ke){Q.push(`session:${Ke}`);for(const[$,D]of Object.entries(ua))D===Se&&Q.push(`session:${$}`)}else he==="channel"&&ft?Q.push(`channel:${ft}`):he==="dm"&&Xt&&e?.id&&Q.push(`channel:dm:${[e.id,Xt].sort().join(":")}`);for(const $ of Q)bk($);return()=>{vk(Q)}},[t,he,ft,Ke,Xt,Se,x,P,ua]);const nr=w.useCallback(()=>ie.agents.list().then(S=>h(S.agents)).catch(()=>{}),[]),Sk=w.useCallback((S,Q)=>{S&&h($=>$.map(D=>D.id===S?{...D,avatarUrl:Q}:D))},[]),Hs=w.useCallback(()=>ie.teams.list().then(S=>{Ag(S.teams),nk(!0)}).catch(()=>{}),[]),ro=w.useCallback(()=>ie.groupChats.list().then(S=>ia(S.chats)).catch(()=>{}),[]),wk=w.useMemo(()=>pu(nr,3e3),[nr]),Jl=w.useMemo(()=>pu(Hs,5e3),[Hs]),qd=w.useMemo(()=>pu(ro,3e3),[ro]),fa=w.useCallback(()=>{ie.users.list(e?.orgId).then(S=>d(S.users)).catch(()=>{})},[e?.orgId]);w.useEffect(()=>{v&&(x!=="team"||!y||WO(y,js.map(S=>S.id),Ed)==="missing"&&(window.location.hash=Ht.TEAM))},[v,x,y,js,Ed]),w.useEffect(()=>{t||(Promise.all([nr(),Hs()]).finally(()=>p(!1)),fa(),ie.tasks.list().then(S=>Mg(S.tasks)).catch(()=>{}),ie.externalAgents.list().then(S=>ak(S.agents)).catch(()=>{}),ro())},[t,fa]),w.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),d(r.humans??[]),Ag(r.teams??[]),ia(r.groupChats??[]),r.channelMessages)){const S=r.activeChannel??"custom:general";$s(r.channelMessages.filter(Q=>Q.channel===S).map(Q=>Dn(Q)))}},[t,r]),w.useEffect(()=>{_P()},[]),w.useEffect(()=>{if(t||!o)return;const S=()=>{const te=Se,ne=Is.map(Qe=>Qe.id).filter(Qe=>Qe!==st);Ke&&Ke!==st&&!ne.includes(Ke)&&ne.push(Ke),te&&ne.length>0&&kP(te,ne)};let Q=null;const $=()=>{Q||(Q=setInterval(S,6e4))},D=()=>{Q&&clearInterval(Q),Q=null},Y=()=>{document.hidden?D():(S(),$())};return document.addEventListener("visibilitychange",Y),document.hidden||$(),S(),()=>{D(),document.removeEventListener("visibilitychange",Y)}},[t,o,Is,Se,Ke]),w.useEffect(()=>{if(t||!o)return;nr(),Hs();const S=setInterval(nr,3e4),Q=setInterval(Hs,6e4),$=St.on("agent:update",Be=>{const Ye=Be?.payload;if(Ye?.agentId){const ct=Ye.status,Gt=Ye.currentActivity;h(os=>os.map(Ut=>{if(Ut.id!==Ye.agentId)return Ut;const yr={...Ut};return ct&&(yr.status=ct),Gt!==void 0&&(yr.currentActivity=Gt),yr}))}wk(),Jl()}),D=St.on("team:update",()=>{Jl(),qd()}),Y=St.on("agent:removed",Jl),te=St.on("chat:group_created",()=>{ro(),Hs(),nr()}),ne=St.on("chat:group_updated",qd),Qe=St.on("chat:group_deleted",()=>{qd(),Jl()}),De=St.on("task:update",Be=>{const Ye=Be?.payload;Ye?.taskId&&Mg(ct=>ct.map(Gt=>Gt.id===Ye.taskId?{...Gt,status:Ye.status??Gt.status}:Gt))}),ve=St.on("approval:resolved",Be=>{const Ye=Be?.payload?.approvalId;Ye&&(Wl(ct=>ct&&ct.id===Ye?null:ct),sa(ct=>ct&&ct.id===Ye?null:ct))}),Ce=()=>{nr(),Hs(),fa()};return window.addEventListener("markus:data-changed",Ce),()=>{clearInterval(S),clearInterval(Q),$(),D(),Y(),te(),ne(),Qe(),De(),ve(),window.removeEventListener("markus:data-changed",Ce)}},[t,o,fa]),w.useEffect(()=>{if(t)return;const S=ve=>{const Ce=ve.detail;if(NC(Ce.page)===Ht.TEAM){if(Ce.params?.agentId&&(Ce.params.profileTab?xt(Ce.params.agentId,{tab:Ce.params.profileTab}):($t("direct"),Ns(Ce.params.agentId),_("chat"),v&&k(),Ce.params.sessionId?$e.current={agentId:Ce.params.agentId,sessionId:Ce.params.sessionId,chips:Ce.params.chatChips??null}:Ce.params.preferMain==="1"&&(ci.current={mode:"direct",agentId:Ce.params.agentId,sessionId:null,preferMain:!0}))),Ce.params?.selectAgent&&($t("direct"),Ns(Ce.params.selectAgent),_("chat"),v&&k()),Ce.params?.openDeliverable){const Be=Ce.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Ar.navigate(Ht.DELIVERABLES,{openDeliverable:Be}):K&&ie.deliverables.get(Be).then(Ye=>{Ye.deliverable&&K({kind:"deliverable",deliverable:Ye.deliverable})}).catch(()=>{})}if(Ce.params?.prefillMessage){const Be=Ce.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Ce.params?.autoSend==="true"?setTimeout(()=>Bg.current?.(Be),300):(Or(Be),setTimeout(()=>{const Ye=Ss.current;Ye&&(Ye.focus(),Ye.setSelectionRange(Ye.value.length,Ye.value.length))},100))}if(Ce.params?.chatChips){const Be=Ce.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ce.params.sessionId||Me(Be)}if(Ce.params?.dm&&($t("dm"),ji(Ce.params.dm),_("chat"),v&&k()),Ce.params?.channel&&($t("channel"),Ds(Ce.params.channel),_("chat"),v&&k()),Ce.params?.selectTeam){const Be=Ce.params.selectTeam;if(v)C(Be);else{const Ye=Td.current.find(ct=>ct.type==="team"&&ct.teamId===Be);$t("channel"),Ds(Ye?.channelKey??`group:${Be}`),_("chat"),_s(!1),_e(!0)}}Ce.params?.openHire}},Q=localStorage.getItem("markus_nav_agentId");if(Q){localStorage.removeItem("markus_nav_agentId");const ve=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),$t("direct"),Ns(Q),ve?xt(Q,{tab:ve}):(_("chat"),v&&k())}const $=localStorage.getItem("markus_nav_dm");$&&(localStorage.removeItem("markus_nav_dm"),$t("dm"),ji($),_("chat"),v&&k());const D=localStorage.getItem("markus_nav_channel");D&&(localStorage.removeItem("markus_nav_channel"),$t("channel"),Ds(D),_("chat"),v&&k());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Or(Y),setTimeout(()=>{const ve=Ss.current;ve&&(ve.focus(),ve.setSelectionRange(ve.value.length,ve.value.length))},150));const te=localStorage.getItem("markus_nav_chatChips");te&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),Me(te));const ne=localStorage.getItem("markus_nav_openDeliverable");ne&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Ar.navigate(Ht.DELIVERABLES,{openDeliverable:ne}):K&&ie.deliverables.get(ne).then(ve=>{ve.deliverable&&K({kind:"deliverable",deliverable:ve.deliverable})}).catch(()=>{}));const Qe=localStorage.getItem("markus_nav_selectAgent");Qe&&(localStorage.removeItem("markus_nav_selectAgent"),$t("direct"),Ns(Qe),_("chat"),v&&k());const De=localStorage.getItem("markus_nav_selectTeam");if(De)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(De);else{const ve=Td.current.find(Ce=>Ce.type==="team"&&Ce.teamId===De);$t("channel"),Ds(ve?.channelKey??`group:${De}`),_("chat"),_s(!1),_e(!0)}return window.addEventListener("markus:navigate",S),()=>window.removeEventListener("markus:navigate",S)},[t]),w.useEffect(()=>{const S=Rg.current;if(!S)return;const Q=ws.find($=>$.type==="team"&&$.teamId===S);Rg.current=null,$t("channel"),Ds(Q?.channelKey??`group:${S}`),_("chat"),_s(!1),_e(!0)},[ws,js]),w.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||Se&&l.some($=>$.id===Se))return;const S=localStorage.getItem("markus_nav_after_remove");if(S&&(localStorage.removeItem("markus_nav_after_remove"),S.startsWith("channel:"))){$t("channel"),Ds(S.slice(8)),_("chat");return}const Q=l.find($=>!$.teamId&&$.role?.toLowerCase()==="secretary")??l.find($=>$.role?.toLowerCase()==="secretary")??l.find($=>$.name?.toLowerCase().includes("secretary"));Q?($t("direct"),Ns(Q.id),_("chat")):l.length>0&&($t("direct"),Ns(l[0].id),_("chat"))},[l,Se]);const io=w.useRef(!1),_n=w.useRef(!1),pa=w.useRef(0),Zd=w.useRef("none"),Vd=w.useRef(0),ec=w.useRef(0),hi=w.useRef(null),Fd=w.useRef(null),qg=w.useRef([]),Ud=w.useRef(0),[_k,kn]=w.useState(!1),no=w.useRef(0),[Zg,ma]=w.useState(0),oo=w.useCallback(()=>performance.now()<pa.current,[]),Di=w.useCallback(()=>oP({takeover:_n.current,gestureActive:oo()}),[oo]),or=w.useCallback(()=>{_n.current=!1,pa.current=0,Zd.current="none",Ud.current=0,ec.current+=1,io.current=!1,kn(!1),no.current=0,ma(0)},[]),Zr=w.useCallback(()=>{_n.current||(_n.current=!0,ec.current+=1,io.current=!1,hi.current!==null&&(cancelAnimationFrame(hi.current),hi.current=null),kn(!0))},[]),tc=w.useCallback(S=>{pa.current=performance.now()+Ou,S!=="none"&&(Zd.current=S);const Q=qr.current;aP(S,!!Q&&KO(Q))&&Zr()},[Zr]),sc=w.useCallback(S=>{const Q=qr.current;if(!Q)return;const $=Q.scrollTop-Vd.current;Vd.current=Q.scrollTop;const D=nP({takeover:_n.current,gestureActive:oo(),gestureDirection:Zd.current,scrollable:KO(Q),distance:Xc(Q),deltaScrollTop:$,programmatic:S?.programmatic??io.current,intentPending:bs.current!==null});D==="handover"?Zr():D==="resume"?or():D==="follow"?(kn(!1),no.current=0,ma(0)):_n.current&&kn(!0)},[oo,Zr,or]);w.useEffect(()=>{const S=qr.current;if(!S)return;let Q=null;const $=Ce=>{tc(eP(Ce.deltaX,Ce.deltaY))},D=Ce=>{Q=Ce.touches[0]?.clientY??null,pa.current=performance.now()+Ou},Y=Ce=>{const Be=Ce.touches[0]?.clientY;if(Be==null)return;const Ye=iP(Q,Be);Q=Be,tc(Ye)},te=()=>{Q=null},ne=Ce=>{Kp(Ce.target)||tc(rP(Ce.key))},Qe=Ce=>{const Be=S.getBoundingClientRect();Ce.clientX-Be.left<S.clientWidth||(pa.current=performance.now()+Ou)},De=()=>{sc()};S.addEventListener("wheel",$,{passive:!0}),S.addEventListener("touchstart",D,{passive:!0}),S.addEventListener("touchmove",Y,{passive:!0}),S.addEventListener("touchend",te,{passive:!0}),S.addEventListener("pointerdown",Qe,{passive:!0}),S.addEventListener("scroll",De,{passive:!0}),document.addEventListener("keydown",ne);const ve=typeof ResizeObserver<"u"?new ResizeObserver(()=>sc()):null;return ve?.observe(S),Vd.current=S.scrollTop,sc(),()=>{S.removeEventListener("wheel",$),S.removeEventListener("touchstart",D),S.removeEventListener("touchmove",Y),S.removeEventListener("touchend",te),S.removeEventListener("pointerdown",Qe),S.removeEventListener("scroll",De),document.removeEventListener("keydown",ne),ve?.disconnect()}},[x,sc,tc]);const Hd=w.useMemo(()=>new Set($g),[$g]),ns=w.useMemo(()=>{const S=he==="channel"?rs:rs.filter(D=>!D.isActivityLog),Q=Hd.size===0?S:S.filter(D=>!(D.isNotification&&Hd.has(D.id))),$=t&&El?Q.length-1:-1;return Q.filter((D,Y)=>KC(D,Y===$||!!D.isStreaming&&ha))},[rs,he,Hd,ha,t,El]);w.useEffect(()=>{xd.current=P==="chat"&&ns.length>0,Ko()},[P,ns.length,Ko]);const ao=A2({count:ns.length,getScrollElement:()=>qr.current,getItemKey:S=>ns[S]?.id??S,estimateSize:S=>{const Q=ns[S];return Q?Q.segments&&Q.segments.length>0?300:Q.text.length>500?200:120:120},overscan:8});ao.shouldAdjustScrollPositionOnItemSizeChange=(S,Q,$)=>mu()||bs.current?.priority==="jump"?!1:S.start<($.scrollOffset??0);const ar=w.useCallback((S="instant")=>{if(!Di()||performance.now()<Ud.current)return;const Q=qr.current;if(!Q)return;const $=++ec.current,D=()=>$===ec.current&&Di();if(S==="smooth"){Ud.current=performance.now()+K2,Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"});return}hi.current!==null&&(cancelAnimationFrame(hi.current),hi.current=null),io.current=!0;let Y=0;const te=()=>{if(hi.current=null,!D()){io.current=!1;return}if(Q.scrollTop=Q.scrollHeight,Y+=1,Y<G2&&Xc(Q)>1){hi.current=requestAnimationFrame(te);return}io.current=!1};Q.scrollTop=Q.scrollHeight,hi.current=requestAnimationFrame(te)},[Di]),Cn=w.useCallback(S=>{const Q=qr.current;!Q||!S||Q.scrollHeight<=Q.clientHeight||t0.save(S,cP(e0(Q),Q))},[]),Pn=w.useCallback(()=>{Fl.current+=1;for(const S of Ul.current)clearTimeout(S);Ul.current=[]},[]),lo=w.useCallback(()=>{bs.current=null,Pn()},[Pn]),Vg=w.useCallback(()=>{or(),lo(),Fd.current!==null&&cancelAnimationFrame(Fd.current);for(const S of qg.current)clearTimeout(S);ar("instant"),Fd.current=requestAnimationFrame(()=>ar("instant")),qg.current=[60,160,320].map(S=>setTimeout(()=>ar("instant"),S))},[or,lo,ar]),Yd=w.useCallback(S=>{const Q=bs.current;if(!Q||Q.key!==S)return!0;if(Bs.current!==S||Q.priority!=="prepend"&&oo())return bs.current=null,!0;const $=qr.current;if(!$)return!0;if(mu())return!1;const{anchor:D}=Q;if(D.kind==="bottom"){xu(Q.priority)&&or(),$.scrollTop=$.scrollHeight;const Ye=Xc($)<=1,ct=i0(Ye,Q.prevSettled);return Q.prevSettled=Ye,ct?(bs.current=null,!0):!1}const Y=gP(Q.at,performance.now()),te=uP(e0($),$,D.id,D.delta),ne=te===null&&!Y&&(Fs(Q.bufferId)??[]).some(Ye=>Ye.id===D.id),Qe=te!==null&&Math.abs(te)<=1,De=i0(Qe,Q.prevSettled),ve=te===null&&!ne,Ce=It.getWindowBounds(Q.bufferId).hasMore,Be=OP({priority:Q.priority,rendered:te!==null,stale:Y,stable:De,absent:ve,canLoadMore:Ce});switch(Q.prevSettled=te!==null?Qe:null,xu(Q.priority)&&Be!=="release-bottom"&&Be!=="release-hold"&&Zr(),Be){case"apply":return zi("intent:apply",{id:D.id,priority:Q.priority,correction:te}),bs.current=null,!0;case"refine":return te!==null&&Math.abs(te)>1&&($.scrollTop+=te),te!==null&&Math.abs(te)>8&&zi("intent:refine",{id:D.id,priority:Q.priority,correction:te}),!1;case"release-bottom":return zi("intent:release-bottom",{id:D.id,priority:Q.priority}),bs.current=null,xu(Q.priority)&&or(),$.scrollTop=$.scrollHeight,!0;case"release-hold":return zi("intent:release-hold",{id:D.id,priority:Q.priority,stale:Y,absent:ve,canLoadMore:Ce,bufferId:Q.bufferId}),bs.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:Q.priority,anchor:D}),!0;default:{const Ye=Xg.current.findIndex(ct=>ct.id===D.id);if(Ye>=0){const ct=ao.getOffsetForIndex(Ye,"start");ct&&($.scrollTop=ct[0]+D.delta)}else Bd.current?.();return!1}}},[ao,oo,Zr,or,Fs]),rc=w.useCallback(()=>{const S=bs.current;if(!S)return;const Q=S.key;Pn();const $=Fl.current,D=te=>{Ul.current.push(setTimeout(()=>{$===Fl.current&&bs.current?.key===Q&&(Yd(Q)||D(r0))},te))},Y=[0,60,160,320,560,900];Y.forEach((te,ne)=>{const Qe=ne===Y.length-1,De=()=>{if($!==Fl.current)return;!Yd(Q)&&Qe&&D(r0)};te===0?requestAnimationFrame(De):Ul.current.push(setTimeout(De,te))})},[Yd,Pn]),co=w.useCallback((S,Q,$="restore",D)=>{if(!S)return!1;const Y=bs.current;return pP(Y,{key:S,priority:$})?(bs.current={key:S,bufferId:D??wn(),anchor:Q,at:performance.now(),priority:$,prevSettled:null},rc(),!0):!1},[wn,rc]),ga=w.useCallback(S=>{S&&co(S,t0.get(S)??{kind:"bottom"})},[co]),kk=w.useCallback(()=>{bs.current||(so.current!==null&&clearTimeout(so.current),so.current=setTimeout(()=>{so.current=null,Cn(Bs.current)},200))},[Cn]);Xg.current=ns,w.useLayoutEffect(()=>()=>{Cn(Bs.current),Pn(),so.current!==null&&clearTimeout(so.current)},[Cn,Pn]);const Oa=w.useMemo(()=>yI(ns,zl),[ns,zl]);w.useEffect(()=>{na(-1)},[zl]);const ic=w.useCallback(S=>{const Q=()=>{const Y=document.getElementById(`msg-${S}`);return Y?(Y.classList.remove("chat-find-hit"),Y.offsetWidth,Y.classList.add("chat-find-hit"),window.setTimeout(()=>Y.classList.remove("chat-find-hit"),1600),!0):!1};let $=0;const D=()=>{Q()||$++>=8||window.requestAnimationFrame(D)};D()},[]),Fg=w.useCallback(async(S,Q)=>{lo(),Zr();const $=Bs.current,D=oe.current,Y=()=>(Fs(D)??[]).some(ne=>ne.id===S);let te=Y();if(!te&&$){const ne=It.getActiveSession(D)??D,Qe=await wI({targetId:S,has:Y,targetCreatedAt:Q,fetchPage:async ve=>{if(!ne||ne===st)return{messages:[],hasMore:!1};const Ce=await ie.sessions.getMessages(ne,50,ve);return{messages:Ce.messages,hasMore:Ce.hasMore}}}),De=SI(Qe.messages,S);De.length>0&&(sr(D,De.map(ah)),Ni(ne,{hasMore:Qe.hasMore,oldestCursor:De[0]?new Date(De[0].createdAt).toISOString():null})),te=Qe.found||Y(),zi("jump:collected",{messageId:S,found:Qe.found,kept:De.length,exhausted:Qe.exhausted})}if(zi("jump:located",{messageId:S,loaded:te,key:$,nowKey:Bs.current}),!($&&Bs.current!==$)){if(te&&$){co($,JO(S),"jump",wn()),zi("jump:scheduled",{messageId:S,key:$}),ic(S);return}$&&(zi("jump:fallback-bottom",{messageId:S,key:$}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:S}),or(),ar("instant"))}},[lo,Zr,co,ic,Fs,It,sr,Ni,or,ar]),Ck=w.useCallback(S=>{const Q=Oa.matches[S];Q&&(na(S),lo(),Zr(),Bs.current&&co(Bs.current,JO(Q.messageId),"jump"),ic(Q.messageId))},[Oa.matches,lo,Zr,co,ic]);w.useEffect(()=>{if(P!=="chat"||t)return;const S=Q=>{Q.key.toLowerCase()!=="f"||Q.altKey||Q.shiftKey||!(b?Q.metaKey&&!Q.ctrlKey:Q.ctrlKey&&!Q.metaKey)||(Q.preventDefault(),Kn(!0))};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[P,t,b]);const Ug=w.useRef(o);w.useEffect(()=>{Ug.current=o},[o]),w.useLayoutEffect(()=>{const S=Dd.current;if(S&&(Dd.current=null,!bs.current&&S.key===Bs.current)){const Q=qr.current,$=Q?Q.scrollHeight-S.scrollHeight:0;Q&&$>0&&(Q.scrollTop+=$,Q.dispatchEvent(new Event("scroll")))}if(bs.current){rc();return}Ug.current&&Di()&&(mu()||ar())},[rs,ar,Di,rc]);const Hg=w.useRef(P);w.useEffect(()=>{const S=Hg.current!=="chat";Hg.current=P,P==="chat"&&S&&ga(Bs.current)},[P,cs,ar,Di,ga]);const Yg=w.useRef(B);w.useEffect(()=>{if(Yg.current===B||(Yg.current=B,P!=="chat")||ns.length===0||cs||gn||!Di())return;const S=[],Q=requestAnimationFrame(()=>ar("instant"));for(const $ of[60,160,320])S.push(setTimeout(()=>ar("instant"),$));return()=>{cancelAnimationFrame(Q);for(const $ of S)clearTimeout($)}},[B,P,ns.length,cs,gn,ar,Di]);const nc=w.useCallback(async(S,Q,$)=>{const D=Q??`ch:${S}`;!$?.quiet&&oe.current===D&&zr(!0);try{const Y=await ie.channels.getMessages(S,50),te=Y.messages.map(ne=>Dn(ne,e?.id));sr(D,te),Ni(D,{hasMore:Y.hasMore,oldestCursor:Y.messages[0]?new Date(Y.messages[0].createdAt).toISOString():null}),oe.current===D&&$s(te)}catch{oe.current===D&&$s([])}finally{!$?.quiet&&oe.current===D&&zr(!1)}},[Ni]),Gd=w.useCallback(async S=>{if(!S)return Ai([]),Ll(0),Nl(1),Il(!1),md(!1),[];md(!0);try{const Q=await ie.sessions.listByAgent(S,20,1);return Ai(Q.sessions),Ll(Q.total??Q.sessions.length),Nl(Q.page??1),Il(!!Q.hasMore),Q.sessions}catch{return Ai([]),Ll(0),Nl(1),Il(!1),[]}finally{md(!1)}},[]),Gg=w.useRef({chatContext:[],input:"",pendingImages:[],chatMode:he,selectedAgent:Se,activeSessionId:Ke,activeDmUserId:Xt,authUser:e,activeChannel:ft,groupChats:ws,agents:l,humans:u,sending:cs,chatReplyTo:null});Gg.current={chatContext:xr,input:qt,pendingImages:ir,chatMode:he,selectedAgent:Se,activeSessionId:Ke,activeDmUserId:Xt,authUser:e,activeChannel:ft,groupChats:ws,agents:l,humans:u,sending:cs,chatReplyTo:fn};const Pk=u3({stateRef:Gg,actBuffers:Gn,activeSessionBuffer:un,readConvMsgs:Fs,currentConvKeyRef:oe,updateConvMsgs:Oe,updateConvMsgsRaf:We,appendConvActivity:Ge,beginStream:ot,endStream:jt,abortStream:Os,clearStreamSession:us,setStreamSession:gr,getStreamSession:Xr,setActiveSession:z,incrementSending:rr,decrementSending:li,loadAndDisplay:xs,sessionSwitchSeqRef:gd,setSending:Ri,setActivities:dn,setInput:Or,setChatContext:pn,setPendingImages:Ml,setMentionDropdown:oa,setChatReplyTo:Rl,setActiveSessionId:Mi,setStoredActiveSession:Jo,setOpenSessionTabs:Us,setSessions:Ai,setLoadingChat:zr,setWindowBounds:Ni,makeConvKey:Ma,makeDmChannel:Yl,addRecentMsgId:hd,resumeChatScrollFollow:or,loadSessions:Gd,t:i}),{send:ho,stopSending:Tk,tryReattachActiveStream:uo,loadSessionMessages:Kd}=Pk;Bg.current=ho;const Kg=w.useCallback(()=>{Vg(),ho()},[Vg,ho]),Jg=w.useRef(uo);Jg.current=uo;const Qk=lh();w.useEffect(()=>{if(!o||t||he!=="direct"||!Se)return;const S=Ke;!S||S===st||ls.isStreaming(S)&&Jg.current(Se,S,oe.current)},[o,t,he,Se,Ke,Qk]);const $k=w.useCallback(async()=>{if(Bl||!Se||!Dl)return;yg(!0);const S=vg+1,Q=Se;try{const $=await ie.sessions.listByAgent(Q,20,S);Ai(D=>{const Y=new Set(D.map(ne=>ne.id)),te=[...D,...$.sessions.filter(ne=>!Y.has(ne.id))];return Ll($.total??te.length),te}),Nl(S),Il(!!$.hasMore)}catch{}yg(!1)},[Bl,Dl,vg,Se]),eO=w.useCallback(S=>{wg(S.id),Sd((S.isMain?"":S.title)||"")},[]),xa=w.useCallback(()=>{wg(null),Sd("")},[]),tO=w.useCallback(async S=>{const Q=yd.trim();if(!Q){xa();return}try{const D=(await ie.sessions.renameTitle(S.id,Q))?.session?.title??Q;Ai(Y=>Y.map(te=>te.id===S.id?{...te,title:D}:te)),Us(Y=>Y.map(te=>te.id===S.id?{...te,title:D}:te))}catch{}xa()},[yd,xa]),sO=w.useCallback(async()=>{if(Hl.current)return Hl.current;const S=oe.current,Q=It.getActiveSession(S)??S,$=It.getWindowBounds(Q),D=$.oldestCursor;if(!$.hasMore||!D)return 0;const Y=Q&&Q!==st?Q:null,ne=(async()=>{mg(!0);try{const Qe=Bs.current;let De=[],ve=!1,Ce=null;if(he==="channel"||he==="dm"){const Ut=he==="dm"?Yl(e?.id??"",Xt):ft,yr=await ie.channels.getMessages(Ut,50,D);De=yr.messages.map(lr=>Dn(lr,e?.id)),ve=yr.hasMore,Ce=yr.messages[0]?new Date(yr.messages[0].createdAt).toISOString():null}else if(Y){const Ut=await ie.sessions.getMessages(Y,50,D);De=Ut.messages.map(ah),ve=Ut.hasMore,Ce=Ut.messages[0]?new Date(Ut.messages[0].createdAt).toISOString():null}else return 0;if(De.length===0)return Ni(Q,{hasMore:ve,oldestCursor:D}),0;if(oe.current!==S||Bs.current!==Qe)return 0;const Be=qr.current,Ye=Be?Be.scrollHeight:null,ct=Fs(S)??[],Gt=new Set(De.map(Ut=>Ut.id));let os=[...De,...ct.filter(Ut=>!Gt.has(Ut.id))];return os.length>500&&(os=os.slice(-500)),sr(S,os),Ni(Q,{hasMore:ve,oldestCursor:Ce}),Ye!==null&&(Dd.current={key:Bs.current,scrollHeight:Ye}),$s(os),De.length}catch{return 0}finally{mg(!1)}})();Hl.current=ne;try{return await ne}finally{Hl.current=null}},[he,ft,e?.id,Xt,Fs,sr,It,Ni]);Bd.current=sO;const Jd=w.useRef(!1),jk=w.useCallback(S=>{kk(),!Jd.current&&(Jd.current=!0,requestAnimationFrame(()=>{Jd.current=!1,S.target.scrollTop<100&&Bd.current?.()}))},[]);w.useEffect(()=>{if(t)return;const S=Ma(he,Se,ft,Xt),Q=oe.current;oe.current=S,Q&&Q!==S&&(Go.set(Q,Is),Ke&&Vp(Q)&&z(Q,Ke),Cn(go(Q,Ke))),Q!==S&&(or(),kn(!1),no.current=0,ma(0),Kn(!1),jd(""),na(-1));const $=Fs(S),D=Go.get(S),Y=un.get(S)??(Se?bg(Se)??void 0:void 0),te=Xr(S),ne=Y??Ke,Qe=he!=="direct"?Wr(S):l0(te,ne),De=ne??S,ve=Gn.get(De)??[];dn(Qe?ve:[]),Ri(Qe),he==="direct"&&Se&&Gd(Se),D&&D.length>0&&Us(D),On(!1);const Ce=CP(ci.current,{chatMode:he,agentId:Se});if($!==void 0&&$.length>0)if(Qe||It.completeLoad(S),zr(!1),$s($),Y!==void 0&&(ca(S,Y),ga(go(S,Y))),(!D||D.length===0)&&Us([]),he==="channel"||he==="dm"){const Ye=he==="dm"?Yl(e?.id??"",Xt):ft;nc(Ye,S)}else he==="direct"&&Se&&Y&&Y!==st&&!Ce&&(Qe?uo(Se,Y,S):Kd(Y,S).then(()=>{oe.current===S&&Se&&uo(Se,Y,S)}));else if(et(S),zr(!0),$s([]),sr(S,[]),he==="channel"||he==="dm"){const Ye=he==="dm"?Yl(e?.id??"",Xt):ft;nc(Ye,S),(!D||D.length===0)&&Us([])}else he==="direct"&&Se?Gd(Se).then(Ye=>{if(oe.current===S)if(Ye.length>0){const ct=Ye.find(Ws=>Ws.isMain),Gt=bd(Se),os=ct?[ct,...Ye.filter(Ws=>!Ws.isMain&&!Gt.has(Ws.id)).slice(0,4)]:Ye.filter(Ws=>!Gt.has(Ws.id)).slice(0,5);let Ut=D&&D.length>0?D:os;const yr=bg(Se),lr=Y!==void 0?Y:yr??ct?.id??Ut[0].id;if(lr&&lr!==st&&!Ut.some(Ws=>Ws.id===lr)){const Ws=Ye.find(Vr=>Vr.id===lr);Ws&&(Ut=[...Ut,Ws])}const ui=lr&&Ut.some(Ws=>Ws.id===lr)?lr:Ut[0].id,Bi=ci.current;if(Bi&&Bi.mode==="direct"&&Bi.agentId===Se&&(Bi.sessionId||Bi.preferMain)){Us(Ut);return}ca(S,ui),ga(go(S,ui)),Jo(Se,ui),Us(Ut),Kd(ui,S).then(()=>{oe.current===S&&Se&&uo(Se,ui,S)})}else ca(S,null),zr(!1),(!D||D.length===0)&&Us([])}).catch(()=>{oe.current===S&&zr(!1)}):zr(!1)},[t,he,Se,ft,Xt,n.language,i]),w.useEffect(()=>t?void 0:St.on("chat:message",Q=>{const $=Q.payload,D=$.channel??"";if(!D)return;const Y=$.senderType??"agent",te=$.text??$.message??"",ne=$.senderId??$.agentId??"",Qe=$.senderName??$.agentId??i("page.fallbackAgent"),De=$.metadata,ve=$.messageId??$.id??"";if(ve&&ln.current.has(ve))return;const Ce=Y==="human"&&ne===(e?.id??""),Be={id:ve||`ws_${Date.now()}_${ne}`,sender:Ce?"user":"agent",text:te,time:new Date().toLocaleTimeString(),rawCreatedAt:Q.timestamp??new Date().toISOString(),agentName:Ce?void 0:Qe,agentId:Ce?void 0:ne,replyToId:$.replyToId??void 0,replyToSender:$.replyToSender??void 0,replyToText:$.replyToText??void 0};if(De&&Y==="agent"){const ct=[];if(De.thinking?.length&&ct.push({type:"text",content:"",thinking:De.thinking.join(`
80
+ `)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Ar.navigate(Ht.TEAM,{agentId:s,prefillMessage:j})},M=async U=>{if(y?.file===U){k(null);return}try{const W=await ie.agents.roleDiff(s,U);W.agentContent!=null&&W.templateContent!=null&&k({file:U,agent:W.agentContent,template:W.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 N={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=U=>{const W=N[U];return W?e(`agent:profilePage.filesTab.fileLabels.${W}`):U},I=m?.hasTemplate&&!m.isUpToDate,V=a?T.some(U=>U.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[I&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(U=>U.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(ps,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(U=>{const W=T.some(ce=>ce.file===U.name);return c.jsxs("button",{onClick:()=>P(U.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===U.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[U.name,W&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},U.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[V&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>M(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-on-brand 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")})]})]}),u&&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:`${u}/${a}`,children:[u,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${u}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default 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:()=>{ie.system.openPath(u)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx(XI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(ZI,{content:t.find(U=>U.name===a)?.content??"",editContent:l,setEditContent:U=>{h(U),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(zh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function ZI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=w.useState(!1),o=w.useRef(null);return w.useEffect(()=>{n&&o.current?.focus()},[n]),w.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(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(DI,{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 VI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function FI({tools:s}){const{t:e}=yt(["agent","common"]),t=RI(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(ps,{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=WC(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=VI(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(PC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function UI({agent:s}){const{t:e}=yt(["agent","common"]),t=s.proficiency??{},[r,i]=w.useState(null),[n,a]=w.useState(null),[o,l]=w.useState(!1),h=s.availableSkills??[],u=s.skillWarnings?.missing??[],d=new Map;for(const O of h){const m=O.category||"custom";d.has(m)||d.set(m,[]),d.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...d.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[u.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:u.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:u.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(ps,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(zh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function HI({tools:s,agent:e}){const{t}=yt(["agent","common"]),[r,i]=w.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(FI,{tools:s}):c.jsx(UI,{agent:e})]})}function YI({agentId:s}){const{t:e}=yt(["agent","common"]),[t,r]=w.useState(null),[i,n]=w.useState(!0),[a,o]=w.useState("longterm"),[l,h]=w.useState(""),[u,d]=w.useState(""),[f,p]=w.useState(!1),[v,b]=w.useState(null),[g,O]=w.useState(null),m=z_(()=>ie.agents.getMemorySession(s,g??"").then(T=>T.messages),{enabled:g!==null,deps:[s,g]}),x=w.useCallback(()=>{n(!0),ie.agents.getMemory(s).then(T=>{r(T),h(T.recentDailyLogs??""),d(T.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);w.useEffect(()=>{x()},[x]);const y=async()=>{p(!0),await ie.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),x()},k=async()=>{p(!0),await ie.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),u).catch(()=>{}),p(!1),x()},C=l!==(t?.recentDailyLogs??""),P=u!==(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 _=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:_.map(T=>c.jsx("button",{onClick:()=>o(T.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===T.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:T.label},T.key))}),a==="entries"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(zh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((T,R)=>{const M=v===R;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(M?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 ${T.type==="fact"?"bg-blue-500/15 text-blue-600":T.type==="task"?"bg-green-500/15 text-green-600":T.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:T.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${M?"":"line-clamp-2"}`,children:T.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${T.importance>=7?"bg-red-500/15 text-red-500":T.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",T.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(T.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:M?"▲":"▼"})]})]}),M&&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:T.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"),": ",T.type]}),T.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",T.importance]}),c.jsx("span",{children:new Date(T.timestamp).toLocaleString()})]})]})]},R)})})}),a==="sessions"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(zh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(T=>{const R=g===T.id,M=()=>{O(R?null:T.id)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:M,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:T.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[T.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(T.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:m.view.loading?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.view.error?c.jsx(Yv,{variant:"inline",subject:"会话消息",error:m.resource.error??"读取失败",notEquals:"这个会话没有消息",onRetry:m.reload}):m.view.empty?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const N=m.resource.items,E=new Map;for(const I of N)I.role==="tool"&&I.toolCallId&&E.set(I.toolCallId,I.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:N.filter(I=>I.role!=="tool").map((I,V)=>c.jsxs("div",{className:"px-3 py-2",children:[(I.role==="user"||I.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 ${I.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${I.role}`,{defaultValue:I.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx(vi,{content:I.content,className:"text-xs text-fg-secondary"})})]}),I.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[I.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(vi,{content:I.content,className:"text-xs text-fg-secondary"})})]}),I.toolCalls&&I.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:I.toolCalls.map(U=>{let W;try{W=JSON.parse(U.arguments)}catch{}const ce={tool:U.name,status:"done",args:W,result:E.get(U.id)};return c.jsx(BC,{entry:{type:"tool",info:ce}},U.id)})})]})]},V))})})()})]},T.id)})})}),a==="daily"&&c.jsx(ps,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:C?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:y,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:T=>h(T.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(ps,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:P?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>d(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:k,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:u,onChange:T=>d(T.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 GI({agentId:s,initialData:e}){const{t}=yt(["agent","common"]),[r,i]=w.useState(e??null),[n,a]=w.useState(!e),[o,l]=w.useState([]),[h,u]=w.useState(null),[d,f]=w.useState(!1),[p,v]=w.useState(null),[b,g]=w.useState(null),O=w.useRef(null);w.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=w.useCallback(()=>Promise.all([ie.agents.getHeartbeat(s).then(i).catch(()=>{}),ie.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);w.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),w.useEffect(()=>St.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await ie.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await ie.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(ps,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:d||!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(d?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ys,{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(JI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ys,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ys,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(ps,{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(vi,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>u(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Xh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(ps,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:d,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(d?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function KI({taskId:s,isLive:e}){const{t}=yt("agent"),[r,i]=w.useState([]),[n,a]=w.useState(""),[o,l]=w.useState(!0);if(w.useEffect(()=>{l(!0),a(""),ie.tasks.getLogs(s).then(u=>{i(u.logs),l(!1)}).catch(()=>l(!1))},[s]),w.useEffect(()=>{if(!e)return;const u=St.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),d=St.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{u(),d()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(u=>CC(u));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Jv,{entries:h,isStreaming:e,streamingText:n})})}function Xh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=yt("agent"),[i,n]=w.useState([]),[a,o]=w.useState(!0);if(w.useEffect(()=>{o(!0),ie.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),w.useEffect(()=>t?St.on("agent:activity_log",u=>{const d=u.payload;if(d.agentId!==s||d.activityId!==e)return;const f={seq:d.seq,type:d.type,content:d.content,metadata:d.metadata,createdAt:d.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>kC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Jv,{entries:l,isStreaming:t})})}function ps({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 Xs({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 Ys({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 jv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Rv=5,Ev=1440;function JI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=yt(["agent","common"]),[i,n]=w.useState(!1),[a,o]=w.useState(null),[l,h]=w.useState(!1),[u,d]=w.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await ie.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(u));if(!Number.isFinite(m)||m<Rv||m>Ev){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=jv.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)}),jv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Rv,max:Ev,value:u,onChange:m=>d(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function zh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Av(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 Mv={0:"0",1:"1",2:"2",3:"3",4:"4"},Lv={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},e3={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"},t3={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},s3=["all","interaction","task","notification","system"],r3={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"},i3={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 Qf(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 Nv(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 u=o[1],d=o[2],f=jf(u,e),p=jf(d,e),v=i3[d]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=kv(r),o=Qf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=kv(r),o=Qf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=Qf(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 n3({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=yt(["agent","common","team"]),[n,a]=w.useState(null),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState("all"),[p,v]=w.useState("all"),[b,g]=w.useState(e??null),[O,m]=w.useState(e??null),[x,y]=w.useState(!1),[k,C]=w.useState(!1),[P,_]=w.useState(!0),[T,R]=w.useState(null),M=50,N=3,[E,I]=w.useState(null),V=w.useCallback(async(J=!0)=>{J&&u(!0);try{const G=d==="all"?void 0:d,q=p==="all"?void 0:p,[A,ee]=await Promise.all([ie.agents.getMindState(s),ie.agents.getMailbox(s,{limit:M,category:G,status:q})]);a(A),l(ee),_((ee.history?.length??0)>=M)}catch{}u(!1)},[s,d,p]),U=w.useCallback(async J=>{I(J);try{await ie.agents.dropMailboxItem(s,J,"operator"),await V()}catch{}finally{I(null)}},[s,V]),W=w.useCallback(async()=>{if(!o)return;const J=d==="all"?void 0:d,G=p==="all"?void 0:p;try{const q=await ie.agents.getMailbox(s,{limit:M,offset:o.history.length,category:J,status:G});l(A=>A?{...A,history:[...A.history,...q.history]}:q),_((q.history?.length??0)>=M)}catch{}},[s,o,d,p]),ce=w.useCallback(async()=>{try{await ie.agents.recoverStaleMailbox(s)}catch{}await V()},[s,V]);w.useEffect(()=>{g(e??null),m(e??null),V()},[V,e]);const j=w.useRef(!1);if(w.useEffect(()=>{if(!O||h)return;if(o?.history?.some(G=>G.id===O)){j.current=!1;const G=document.getElementById(`mbx-${O}`);if(G){setTimeout(()=>G.scrollIntoView({behavior:"smooth",block:"center"}),100);const q=setTimeout(()=>m(null),3e3);return()=>clearTimeout(q)}}else P&&!j.current&&(j.current=!0,(async()=>{let G=o?.history??[],q=P;for(;q;)try{const A=await ie.agents.getMailbox(s,{limit:M,offset:G.length}),ee=[...G,...A.history];G=ee,q=(A.history?.length??0)>=M;const F=A.history.some(ae=>ae.id===O);if(l(ae=>ae?{...ae,history:ee}:A),_(q),F||!q)break}catch{break}j.current=!1})())},[O,h,o,P,s]),w.useEffect(()=>{let J=null;const G=A=>{A.payload?.agentId===s&&(J&&clearTimeout(J),J=setTimeout(()=>{J=null,V(!1)},500))},q=[St.on("agent:mailbox",G),St.on("agent:decision",G),St.on("agent:attention",G),St.on("agent:focus",G),St.on("agent:update",G),St.on("agent:triage",G)];return()=>{J&&clearTimeout(J),q.forEach(A=>A())}},[s,V]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const B=n?.mailboxDepth??n?.queuedItems?.length??0,X=Zh(t).running,Z=(()=>{const J=n?.attentionState??"idle";return J==="deciding"||J==="idle"&&B>0?"deciding":J!=="idle"&&!n?.currentFocus?"idle":J})(),K=Z==="idle"&&o?.history?.some(J=>J.status==="processing"),le=(n?.attentionState??"idle")==="idle"&&B>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:[X?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${t3[Z]??"bg-gray-500/20 text-gray-500"}`,children:_C(Z,i)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),X?n?.currentFocus?(()=>{const J=Nv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Dc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:J.title}),J.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:J.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():le?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:B,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):Z==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:B})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{V()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),X&&K&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ce()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const J=n.queuedItems,G=J.length>N,q=G&&!x?J.slice(0,N):J,A=J.reduce((ee,F)=>(ee[F.sourceType]=(ee[F.sourceType]??0)+1,ee),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:J.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([ee,F])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Dc(ee)," ",F]},ee))})]}),c.jsxs("div",{className:"space-y-1",children:[q.map((ee,F)=>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:F+1}),c.jsx("span",{className:"text-sm",children:Dc(ee.sourceType)}),c.jsx("span",{className:`text-[10px] ${Lv[ee.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Mv[ee.priority]??ee.priority}`,{defaultValue:`P${ee.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:ee.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(ee.queuedAt).toLocaleTimeString()})]},ee.id)),G&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:J.length-N})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const J=LI(n.notebook,k);return c.jsx("section",{className:"bg-surface-elevated rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-muted leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:X_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[J.visible.map(G=>{const q=NI(G.updatedAt),A=i(`agent:profilePage.relative.${q.unit==="seconds"?"secondsAgo":q.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:q.count,hours:q.count}),ee=G.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-overlay 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:G.key}),c.jsxs("span",{className:`text-[10px] ${ee}`,children:["[",G.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:G.text.length>500?G.text.slice(0,500)+"…":G.text})]},G.key)}),J.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:J.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-elevated rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Xh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const G=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,q=XP(n.lastTriage);return c.jsx("section",{className:`bg-surface-elevated rounded-lg border p-3 transition-opacity ${G?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!G,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${q.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-overlay text-fg-tertiary"}`,children:q.isBatch?i("agent:profilePage.mind.batchSize",{count:q.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:s3.map(J=>{const G=o?.sourceTypeCounts,q=J==="all"?G?Object.values(G).reduce((A,ee)=>A+ee,0):void 0:G?($I[J]??[]).reduce((A,ee)=>A+(G[ee]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(J),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${d===J?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[i(`agent:profilePage.mind.categoryFilters.${J}`),q!=null&&q>0&&c.jsx("span",{className:"ml-1 opacity-60",children:q})]},J)})})]}),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(J=>{const G=o?.statusCounts,q=J.key==="all"?G?Object.values(G).reduce((A,ee)=>A+ee,0):void 0:G?.[J.key];return c.jsxs("button",{onClick:()=>v(J.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===J.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[J.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${J.dot}`}),i(`agent:profilePage.mind.statusFilters.${J.key}`),q!=null&&q>0&&c.jsx("span",{className:"ml-1 opacity-60",children:q})]},J.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(J=>{const G=b===J.id,q=Dc(J.sourceType),A=Nv(J,i),ee=AI({itemStatus:J.status,agentRunning:X,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:J.id}),F=J.metadata?.senderName,ae=J.metadata?.senderRole,re=O===J.id;return c.jsxs("div",{id:`mbx-${J.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${re?"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-overlay/50 transition-colors rounded-lg",onClick:()=>g(G?null:J.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:G?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${ee==="stale"?"bg-amber-400/70":r3[J.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:q}),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 ${G?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${Lv[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Mv[J.priority]??J.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${G?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(J.queuedAt).toLocaleString()}),J.completedAt&&c.jsxs("span",{children:["→ ",new Date(J.completedAt).toLocaleTimeString()]}),J.activity&&c.jsxs(c.Fragment,{children:[J.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Zp(J.activity.totalTokens)})}),J.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:J.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-overlay px-1.5 py-0.5 rounded shrink-0",children:J.sourceType}),r&&EI({agentRunning:X,itemId:J.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:J.status})&&c.jsxs("button",{onClick:fe=>{fe.stopPropagation(),R(J.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),G&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[F&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:F}),ae&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",ae,")"]})]}),J.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(J.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:J.payload.content}),J.decisions&&J.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:J.decisions.map(fe=>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 ${e3[fe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:fe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:fe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(fe.createdAt).toLocaleTimeString()})]},fe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===J.id,onClick:()=>{U(J.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),J.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:J.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${J.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:J.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),J.activity.type==="task"&&J.payload?.taskId?c.jsx(KI,{taskId:J.payload.taskId,isLive:!J.activity.endedAt}):c.jsx(Xh,{agentId:s,activityId:J.activity.id,isLive:!J.activity.endedAt})]}):ee==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):ee==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):J.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},J.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:W,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Hn,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const J=T;R(null),ie.agents.cancelProcessing(s,{itemId:J}).then(()=>{let G=0;const q=()=>{G+=1,V(),G<8&&window.setTimeout(q,750)};q()}).catch(()=>{V()})},onCancel:()=>R(null)})]})}function Dv({agentId:s}){const{t:e}=yt(["agent","common"]),t=Zo(),r=z_(()=>ie.deliverables.search({agentId:s,limit:200}).then(l=>l.results),{deps:[s]}),i=r.resource.items,n=r.view.loading,a=r.reload,o=w.useCallback(l=>{if(WP(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:l});return}Ar.navigate(Ht.DELIVERABLES,{openDeliverable:l.id})},[t]);return w.useEffect(()=>{const l=St.on("deliverable:created",()=>a()),h=St.on("deliverable:updated",()=>a()),u=St.on("deliverable:removed",()=>a());return()=>{l(),h(),u()}},[a]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(l=>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"})]},l))}):r.view.error?c.jsx(Yv,{variant:"inline",subject:"交付物",error:r.resource.error??"读取失败",notEquals:"这个 agent 没有任何交付物",onRetry:a}):i.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:i.length})}),i.map(l=>{const h=wC[l.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=TO[l.status]??TO.active;return c.jsxs("button",{onClick:()=>o(l),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 ${h.color}`,children:h.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:l.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:l.status})]}),l.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:l.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(l.createdAt).toLocaleDateString()}),l.tags.length>0&&c.jsx("span",{children:l.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"})})]},l.id)})]})})}const o3=w.lazy(()=>Gv(()=>import("./MarkdownMessage-DVfFMzM9.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),fg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Iv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Bv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=yt("team"),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState(!0),[p,v]=w.useState(null),[b,g]=w.useState("overview"),O=r&&i?i:b,[m,x]=w.useState(""),[y,k]=w.useState(""),[C,P]=w.useState(!1),[_,T]=w.useState(!1),[R,M]=w.useState(""),[N,E]=w.useState(""),I=w.useRef(null),V=w.useRef(null),U=w.useRef(null),W=w.useRef(null),[ce,j]=w.useState(!1),[B,X]=w.useState(!1),[Z,K]=w.useState(""),[le,J]=w.useState(""),[G,q]=w.useState(!1),[A,ee]=w.useState([]),F=w.useRef(null),ae=w.useCallback(async()=>{try{const Ue=(await ie.teams.list()).teams.find(Je=>Je.id===s);Ue&&l(Ue);const Ze=await ie.teams.status(s);ee(Ze.agents)}catch{}finally{u(!1)}},[s]),re=w.useCallback(async()=>{f(!0);try{const H=await ie.teams.getFile(s,"ANNOUNCEMENT.md");x(H.content)}catch{x("")}try{const H=await ie.teams.getFile(s,"NORMS.md");k(H.content)}catch{k("")}finally{f(!1)}},[s]);w.useEffect(()=>{g("overview"),ae(),re()},[s,ae,re]),w.useEffect(()=>{C&&V.current&&V.current.focus()},[C]),w.useEffect(()=>{_&&W.current&&W.current.focus()},[_]);const fe=async(H,Ue)=>{j(!0);try{await ie.teams.updateFile(s,H,Ue),H==="ANNOUNCEMENT.md"?(x(Ue),P(!1)):(k(Ue),T(!1))}catch{}j(!1)},Le=async()=>{Z.trim()&&(await ie.teams.update(s,{name:Z.trim()}),X(!1),ae())},we=async()=>{await ie.teams.update(s,{description:le}),q(!1),ae()};if(!o)return h?c.jsx(ey,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(u2,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Me=o.members.find(H=>H.agentRole==="manager"),$e=A.filter(H=>H.status!=="offline").length,ke=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${ke?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${ke?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Me?.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(H=>{const Ue=A.find(mt=>mt.id===H.id),Ze=Iv[Ue?.status??"offline"]??"bg-gray-500",Je=H.type==="agent";return c.jsxs("div",{onClick:()=>Je&&n?.(H.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Je&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(As,{name:H.name,avatarUrl:H.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:H.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Ue?.status??"offline"}),H.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:[H.role," · ",H.type]})]}),Je&&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"})})]},H.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:M,editing:C,setEditing:P,textareaRef:V,contentRef:I,saving:ce,onSave:()=>fe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),O==="norms"&&c.jsx(Ic,{content:y,draft:N,setDraft:E,editing:_,setEditing:T,textareaRef:W,contentRef:U,saving:ce,onSave:()=>fe("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),B?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:F,value:Z,onChange:H=>K(H.target.value),onKeyDown:H=>H.key==="Enter"&&Le(),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:Le,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>X(!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:()=>{K(o.name),X(!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"}),G?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:le,onChange:H=>J(H.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>q(!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:()=>{J(o.description??""),q(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Wv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const _e=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${_e?"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-on-brand 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:[$e," 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:H}=await ie.teams.getFilesMap(o.id),Ue=o.members.filter(Je=>Je.type==="agent"),Ze={type:"team",name:Hv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Ue.map(Je=>({name:Je.name,roleName:Je.role,role:Je.agentRole??"worker",count:1,skills:[]}))}};await em.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ze,files:H}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(H){v({title:"Hub",message:`Failed to publish: ${H}`,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:fg.map(H=>c.jsxs("button",{onClick:()=>g(H.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===H.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[H.icon," ",a(H.labelKey)]},H.key))})]}),c.jsxs("div",{className:`${_e?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Me?.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(H=>{const Ue=A.find(mt=>mt.id===H.id),Ze=Iv[Ue?.status??"offline"]??"bg-gray-500",Je=H.type==="agent";return c.jsxs("div",{onClick:()=>Je&&n?.(H.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Je&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(As,{name:H.name,avatarUrl:H.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:H.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Ue?.status??"offline"}),H.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:[H.role," · ",H.type]})]}),Je&&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"})})]},H.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Ic,{content:m,draft:R,setDraft:M,editing:C,setEditing:P,textareaRef:V,contentRef:I,saving:ce,onSave:()=>fe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),b==="norms"&&c.jsx(Ic,{content:y,draft:N,setDraft:E,editing:_,setEditing:T,textareaRef:W,contentRef:U,saving:ce,onSave:()=>fe("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),B?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:F,value:Z,onChange:H=>K(H.target.value),onKeyDown:H=>H.key==="Enter"&&Le(),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:Le,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>X(!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:()=>{K(o.name),X(!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"}),G?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:le,onChange:H=>J(H.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:"Save"}),c.jsx("button",{onClick:()=>q(!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:()=>{J(o.description??""),q(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Wv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Hn,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Ic({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:u,loading:d}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:d&&!s.trim()?c.jsx(ty,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(o3,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:u})})}function Wv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=w.useState(!1),[n,a]=w.useState(!1),[o,l]=w.useState(!1),[h,u]=w.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:d=>l(d.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:d=>a(d.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()=>{u(!0);try{await ie.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{u(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const a3=["chat","overview","deliverables"],l3=["chat","overview","announcements","norms","settings"];function c3(s,e){if(s==="chat")return e("page.chatTitle");if(ug.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=fg.find(i=>i.key===s);return r?e(r.labelKey):s}function h3(s){if(s==="chat")return"💬";const e=ug.find(r=>r.key===s);if(e)return e.icon;const t=fg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ma(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Vp=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Rr{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Rr.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const d of e)i.add(d.id),n.push(d);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let u=!1;for(const d of t)if(!i.has(d.id)){if(d.sender==="agent"&&!!!(d.isError||d.isStopped||d.emptyReply)){if(r&&d.isStreaming)if(h&&l&&!u){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),u=!0,a.push({...d,id:l.id}),i.add(l.id)}else a.push(d),i.add(d.id);continue}o.push(d)}for(const d of o){if(i.has(d.id))continue;const f=d.rawCreatedAt?Date.parse(d.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,d),i.add(d.id)}for(const d of a)n.push(d);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Vp(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Rr.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Rr.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Rr.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Vp(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Rr.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Rr.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Rr.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Rr.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const st=Rr.NEW_CHAT_ID;function d3(s){const e=w.useRef(new Rr),[t,r]=w.useState(s??[]),[i,n]=w.useState(!1),[a,o]=w.useState([]),l=w.useRef(null),[,h]=w.useState(0),u=w.useCallback(()=>h(R=>R+1),[]),d=w.useCallback(R=>e.current.getStreamSessions(R),[]),f=w.useCallback((R,M)=>{e.current.addStreamSession(R,M)&&u()},[u]),p=w.useCallback((R,M)=>{e.current.removeStreamSession(R,M)&&u()},[u]),v=w.useCallback((R,M)=>e.current.setActiveSession(R,M),[]),b=w.useCallback(R=>e.current.clearActiveSession(R),[]);w.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=w.useCallback((R,M,N)=>{const E=e.current.updateMessages(R,M,N);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=w.useCallback((R,M,N)=>{e.current.updateMessages(R,M,N).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const I=e.current.getMessages(R);I&&e.current.currentConvKey===R&&r([...I])}))},[]),m=w.useCallback((R,M,N)=>{const E=e.current.appendActivity(R,M,N);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=w.useCallback(R=>e.current.getPhase(R),[]),y=w.useCallback(R=>e.current.beginLoad(R),[]),k=w.useCallback(R=>{e.current.beginStream(R)},[]),C=w.useCallback(R=>{e.current.endStream(R)},[]),P=w.useCallback((R,M)=>{e.current.abortStream(R,M)&&u(),e.current.currentConvKey===R&&(n(!1),o([]))},[u]),_=w.useCallback((R,M)=>{e.current.resetConv(R,M),e.current.deleteBuffer(R)},[]),T=w.useCallback(async(R,M,N)=>{e.current.loadingSession=R,e.current.beginLoad(M);try{const E=await N(),I=e.current.applyLoadResult(M,R,E.messages);return I.displayChanged&&I.newMessages&&r(I.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===M&&e.current.getPhase(M)!=="streaming"&&(r([]),e.current.completeLoad(M)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:d,saveSessionToCache:(R,M)=>e.current.saveToCache(),restoreSessionFromCache:(R,M)=>{const N=e.current.restoreFromCache(R,M);return r(N??[]),N},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,M)=>{const N=e.current.updateMessages(R,()=>M);N.displayChanged&&N.newMessages&&r(N.newMessages)}}}function $f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function Xv(){const s=new Uint8Array(12);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(s);else for(let t=0;t<s.length;t++)s[t]=Math.floor(Math.random()*256);let e="";for(const t of s)e+=t.toString(16).padStart(2,"0");return`cm_${e}`}function u3(s){const e=w.useRef(new Map),t=w.useRef(new Map),r=ke=>{if(ke)for(const[_e,H]of e.current)H===ke&&e.current.delete(_e)},i=ke=>{if(ke)for(const[_e,H]of t.current)H===ke&&t.current.delete(_e)},n=ke=>{const _e=e.current.get(ke);_e&&(_e.abort(),e.current.delete(ke));const H=t.current.get(ke);H&&(H.abort(),t.current.delete(ke))},a=ke=>{const _e=e.current.get(st);_e&&e.current.size===1&&(e.current.delete(st),e.current.set(ke,_e))},o=w.useRef(new Map),l=w.useRef(new Set),h=w.useRef(null),u=w.useRef(new Map),d=w.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:M,decrementSending:N,loadAndDisplay:E,sessionSwitchSeqRef:I,setSending:V,setActivities:U,setInput:W,setChatContext:ce,setPendingImages:j,setMentionDropdown:B,setChatReplyTo:X,setActiveSessionId:Z,setStoredActiveSession:K,setOpenSessionTabs:le,setSessions:J,setLoadingChat:G,setWindowBounds:q,makeConvKey:A,makeDmChannel:ee,addRecentMsgId:F,resumeChatScrollFollow:ae,loadSessions:re}=s,{t:fe}=s,Le=w.useCallback(async(ke,_e)=>{const H=I.current,Ue=g.current===_e&&(b(_e)?.length??0)===0;Ue&&G(!0);try{const{count:Ze,hasMore:Je,oldestCursor:mt}=await E(ke,_e,async()=>{const lt=await ie.sessions.getMessages(ke,50);return{messages:lt.messages.map(ah).filter(gt=>gt.sender!=="agent"||gt.text||gt.segments&&gt.segments.length>0||gt.isStreaming),hasMore:lt.hasMore,oldestCursor:lt.messages[0]?new Date(lt.messages[0].createdAt).toISOString():null}});return q(ke,{hasMore:Je,oldestCursor:mt}),Ze}finally{Ue&&g.current===_e&&I.current===H&&G(!1)}},[E,b,I]),we=()=>{const ke=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(ke){const _e=$f(f.current.activeSessionId,st);_e.kind==="cancel"&&ie.agents.cancelProcessing(ke,_e.target).catch(()=>{})}n(f.current.activeSessionId??st),ke&&f.current.activeSessionId&&f.current.activeSessionId!==st&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Me=w.useCallback(async(ke,_e,H)=>{if(!ke||!_e||_e===st||l.current.has(_e))return;let Ue=null;try{const Ze=e.current.get(_e);if(Ze&&!Ze.signal.aborted&&T(H)?.has(_e)){g.current===H&&V(!0);return}const Je=()=>{XC({liveSessions:T(H),sessionId:_e,placeholderId:st})&&(P(H,_e),g.current===H&&(V(!1),O(H,pe=>fu(pe),_e)))},mt=`${ke}:${_e}`,lt=o.current.get(mt)??0;if(Date.now()-lt<1500)return;o.current.set(mt,Date.now());let Tt;const gt=await ie.sessions.streamStatus(ke,_e);gt.messageId&&(Tt=gt.messageId);const _t=b(H)??[],Ee=gt.status==="streaming",kt=zC(_t,{expectedMessageId:gt.messageId,allowCurrentTurnPartial:Ee}),ds=!!gt.active&&(gt.status==="done"||gt.status==="error")&&!!kt?.isStreaming;if(o0({aborted:!1,sawTerminal:ds,serverStatus:a0(gt.status)})==="finalize"){Je();return}o.current.set(mt,Date.now());for(const pe of t.current.values())pe.abort();t.current.clear(),Ue=new AbortController,t.current.set(_e,Ue),y(H),V(!0),_(H,_e);const Et=kt&&!kt.isError&&kt.sender==="agent"?_t.findIndex(pe=>pe.id===kt.id):-1,Ot=Et>=0?_t[Et]:void 0,Wt=qC(gt);if(!Ot&&!Wt){Je();return}const Ae=Ot?Ot.id:Wt;if(!Ot)O(H,pe=>[...pe,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],_e);else{const pe=(Ot.segments??[]).filter(ye=>ye.type==="tool").map(ye=>ye.status==="stopped"||ye.status==="running"?{...ye,status:"running"}:ye);O(H,ye=>ye.map(xe=>xe.id===Ae?{...xe,text:"",isStreaming:!0,isStopped:!1,segments:pe,committedSegments:void 0}:xe),_e)}const Lt=pe=>{g.current===H&&(d.current=Date.now(),m(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(se=>se.id===Ae):-1,He=ze>=0?ze:xe.map((se,je)=>({m:se,j:je})).reverse().find(se=>se.m.sender==="agent"&&se.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];return xe[He]={...qe,text:(qe.text??"")+pe,segments:MO(qe.segments??[],pe),isStreaming:!0},xe},_e))},it=pe=>{g.current===H&&(d.current=Date.now(),m(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(se=>se.id===Ae):-1,He=ze>=0?ze:xe.map((se,je)=>({m:se,j:je})).reverse().find(se=>se.m.sender==="agent"&&se.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];return xe[He]={...qe,segments:LO(qe.segments??[],pe),isStreaming:!0},xe},_e))},At=pe=>{if(g.current===H&&(d.current=Date.now(),pe.phase!=="heartbeat")){if((pe.phase==="start"||pe.phase==="end")&&x(H,{...pe,phase:pe.phase,ts:Date.now()},_e),pe.phase==="start"){const ye=`${pe.tool}_${Date.now()}`,xe=new Date().toISOString(),ze=He=>{const qe=[...He];for(let se=qe.length-1;se>=0;se--){const je=qe[se];if(je.type==="tool"&&je.tool===pe.tool&&(je.status==="running"||je.status==="stopped"))return qe[se]={...je,status:"running",args:pe.arguments??je.args},qe}return qe.push({type:"tool",key:ye,tool:pe.tool,status:"running",args:pe.arguments,createdAt:xe}),qe};O(H,He=>{const qe=[...He],se=Ae?qe.findIndex(Te=>Te.id===Ae):-1;if(se<0)return He;const je=ze(qe[se].segments??[]),Pe=qe[se].committedSegments,be=Pe&&ze(Pe);return qe[se]={...qe[se],segments:je,committedSegments:be,isStreaming:!0},qe},_e)}else if(pe.phase==="end"){const ye=new Date().toISOString(),xe=ze=>{const He=[...ze];for(let qe=He.length-1;qe>=0;qe--){const se=He[qe];if(se.type==="tool"&&se.tool===pe.tool&&(se.status==="running"||se.status==="stopped")){He[qe]={...se,status:pe.success===!1?"error":"done",args:pe.arguments??se.args,result:pe.result,error:pe.error,durationMs:pe.durationMs,liveOutput:void 0,createdAt:ye};break}}return He};O(H,ze=>{const He=[...ze],qe=Ae?He.findIndex(be=>be.id===Ae):-1;if(qe<0)return ze;const se=xe(He[qe].segments??[]),je=He[qe].committedSegments,Pe=je&&xe(je);return He[qe]={...He[qe],segments:se,committedSegments:Pe,isStreaming:!0},He},_e)}else if(pe.phase==="subagent_progress"&&pe.subagentEvent){const ye=xe=>{const ze=[...xe];for(let He=ze.length-1;He>=0;He--){const qe=ze[He];if(qe.type==="tool"&&(qe.tool==="spawn_subagent"||qe.tool==="spawn_subagents")&&(qe.status==="running"||qe.status==="stopped")){ze[He]={...qe,status:"running",subagentLogs:NO(qe.subagentLogs,pe.subagentEvent)};break}}return ze};m(H,xe=>{const ze=[...xe],He=Ae?ze.findIndex(Pe=>Pe.id===Ae):-1;if(He<0)return xe;const qe=ye(ze[He].segments??[]),se=ze[He].committedSegments,je=se&&ye(se);return ze[He]={...ze[He],segments:qe,committedSegments:je,isStreaming:!0},ze},_e)}}},Qt=pe=>{g.current===H&&(d.current=Date.now(),O(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(qe=>qe.id===Ae):-1;if(ze<0)return ye;const He=[...xe[ze].committedSegments??[]];if(pe.type==="thinking_commit")He.push({type:"text",content:"",thinking:pe.content,createdAt:pe.createdAt});else if(pe.type==="text_commit")He.push({type:"text",content:pe.content,createdAt:pe.createdAt});else return ye;return xe[ze]={...xe[ze],committedSegments:He,isStreaming:!0},xe},_e))},es=pe=>{if(g.current!==H)return;d.current=Date.now();const ye=(pe.segments??[]).map((xe,ze)=>xe.type==="tool"?{type:"tool",key:`${xe.tool}_${ze}`,tool:xe.tool??"tool",status:xe.status==="error"?"error":xe.status==="running"||xe.status==="stopped"?"running":"done",args:xe.arguments,result:xe.result,error:xe.error,durationMs:xe.durationMs,createdAt:xe.createdAt,...xe.subagentLogs?.length?{subagentLogs:xe.subagentLogs}:{}}:{type:"text",content:xe.content??"",thinking:xe.thinking,createdAt:xe.createdAt});O(H,xe=>{const ze=[...xe],He=Ae?ze.findIndex(qe=>qe.id===Ae):-1;return He<0?xe:(ze[He]={...ze[He],text:pe.content||ze[He].text,segments:ye,committedSegments:ye,isStreaming:!0,isStopped:!1},ze)},_e);for(const xe of ye)xe.type==="tool"&&x(H,{tool:xe.tool,phase:xe.status==="running"||xe.status==="stopped"?"start":"end",success:xe.status!=="error",arguments:xe.args,result:xe.result,error:xe.error,durationMs:xe.durationMs,ts:Date.now()},_e)},de=8;let ge=null;const me=pe=>{g.current===H&&O(H,ye=>{const xe=ye.map((He,qe)=>({m:He,j:qe})).reverse().find(He=>He.m.sender==="agent"&&He.m.isStreaming)?.j??-1;if(xe<0||ye[xe].reconnecting===pe)return ye;const ze=[...ye];return ze[xe]={...ze[xe],reconnecting:pe},ze},_e)};for(let pe=1;pe<=de;pe++){if(Ue.signal.aborted)return;try{ge=await ie.sessions.reattachStream(ke,_e,{onChunk:Lt,onThinking:it,onActivity:At,onCommit:Qt,onSnapshot:es},Ue.signal,0)}catch(xe){if(Ue.signal.aborted)throw xe;ge=null}if(!ge||!ge.attached){ge=null;break}if(ge.terminal)break;me(!0);const ye=await ie.sessions.streamStatus(ke,_e).catch(()=>null);if(ye?.messageId&&(Tt=ye.messageId),!ye||!ye.active||ye.status==="not_found"||ye.status==="idle"){me(!1),ge=null;break}await new Promise(xe=>setTimeout(xe,Math.min(800*pe,4e3))),me(!1)}if(!ge){k(H),P(H,_e),g.current===H&&(V(!1),Tt&&Ae&&O(H,pe=>ka(pe,Ae,Tt),_e),Le(_e,H).catch(()=>{}).finally(()=>{O(H,pe=>fu(pe,"done"),_e)})),i(Ue);return}if(g.current===H){let pe;O(H,ye=>{const xe=[...ye],ze=Ae?xe.findIndex(je=>je.id===Ae):-1,He=ze>=0?ze:xe.map((je,Pe)=>({m:je,j:Pe})).reverse().find(je=>je.m.sender==="agent"&&je.m.isStreaming)?.j??-1;if(He<0)return ye;const qe=xe[He];if(!qe.isStreaming)return ye;pe=qe.id;const se=ge.segments?.length?DO(ge.segments,qe.segments):void 0;return xe[He]={...qe,text:ge.content||qe.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...se?{segments:se,committedSegments:se}:{}},xe},_e),pe&&O(H,ye=>ka(ye,pe,ge.messageId),_e),V(!1)}k(H),P(H,_e),i(Ue)}catch(Ze){const Je=Ue?[...t.current.values()].includes(Ue):!1;i(Ue),k(H);const mt=l.current.has(_e);if(mt&&P(H,_e),g.current===H&&(V(!1),Je&&mt&&O(H,lt=>fu(lt),_e)),Ze instanceof Error&&Ze.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),$e=w.useCallback(async(ke,_e)=>{const H=f.current,Ue=Z2({text:H.input,chips:H.chatContext??[]}),Ze=ke?ke.trim():Ue.text,Je=ke?ke.trim():Ue.titleSource,mt=ke?void 0:Ue.chips.length>0?Ue.chips:void 0;if(!Ze&&H.pendingImages.length===0||H.chatMode==="direct"&&!H.selectedAgent)return;ae();const lt=Date.now(),Tt=h.current;if(!_e?.isRetry&&!_e?.isResume&&Ze&&Tt&&Tt.text===Ze&&lt-Tt.at<1500)return;if(h.current={text:Ze,at:lt},_e?.isResume){const Et=_e.sessionIdOverride??H.activeSessionId??"";if(lt-(u.current.get(Et)??0)<2e3)return;u.current.set(Et,lt)}if(H.sending&&H.chatMode==="direct"){if(ZC({liveSessions:T(g.current),sendSessionId:H.activeSessionId})){const Ot=g.current;if([...b(Ot)??[]].reverse().find(it=>it.sender==="user")?.text===Ze&&!_e?.isRetry&&!_e?.isResume){n(H.activeSessionId??st);const it=$f(H.activeSessionId,st);return it.kind==="cancel"&&ie.agents.cancelProcessing(H.selectedAgent,it.target).catch(()=>{}),C(Ot,H.activeSessionId),O(Ot,At=>{const Qt=[...At];return Qt.length>0&&Qt[Qt.length-1].sender==="agent"&&Qt.pop(),Qt.length>0&&Qt[Qt.length-1].sender==="user"&&Qt[Qt.length-1].text===Ze&&Qt.pop(),Qt}),await new Promise(At=>setTimeout(At,50)),$e(Ze,{isRetry:!0})}n(H.activeSessionId??st);const Lt=$f(H.activeSessionId,st);Lt.kind==="cancel"&&ie.agents.cancelProcessing(H.selectedAgent,Lt.target).catch(()=>{}),C(Ot,H.activeSessionId),O(Ot,it=>IO(it)),await new Promise(it=>setTimeout(it,50))}}else if(H.sending&&H.chatMode!=="direct"){n(f.current.activeSessionId??g.current);const Et=g.current;C(Et),O(Et,Ot=>IO(Ot)),await new Promise(Ot=>setTimeout(Ot,50))}const gt=H.pendingImages.length>0?H.pendingImages.map(Et=>Et.dataUrl):void 0,_t=H.pendingImages.length>0?H.pendingImages.map(Et=>Et.name):void 0,Ee=A(H.chatMode,H.selectedAgent??"",H.activeChannel??"",H.activeDmUserId),kt=H.chatReplyTo;ke||(W(""),ce([])),j([]),B(!1),X(null);const ds=H.chatMode==="dm";M(Ee);const bt=H.activeSessionId??Ee;if(p.set(bt,[]),g.current===Ee&&!ds&&(V(!0),U([])),H.chatMode==="dm"){const Et=ee(H.authUser?.id??"",H.activeDmUserId),Ot=`opt_${Date.now()}`,Wt={id:Ot,sender:"user",text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};gt?.length&&(Wt.images=gt),kt&&(Wt.replyToId=kt.id,Wt.replyToSender=kt.sender,Wt.replyToText=kt.text),O(Ee,Ae=>[...Ae,Wt]);try{const Ae=await ie.channels.sendMessage(Et,{text:Ze,senderName:H.authUser?.name??fe("page.fallbackYou"),senderId:H.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...gt?.length?{images:gt}:{},..._t?.length?{fileNames:_t}:{}});Ae.userMessage&&F(Ae.userMessage.id),O(Ee,Lt=>{const it=Lt.filter(Qt=>Qt.id!==Ot),At=[];return Ae.userMessage&&At.push(Dn(Ae.userMessage,H.authUser?.id)),At.length>0?[...it,...At]:Lt})}catch(Ae){Bc(Ae)&&Wc(),QO(Ae)&&(W(Ze),j(H.pendingImages)),O(Ee,Lt=>[...Lt.filter(At=>At.id!==Ot),{id:`err_${Date.now()}`,sender:"agent",text:fe("page.errorWithMessage",{message:String(Ae)}),time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}])}N(Ee),g.current===Ee&&V(!1)}else if(H.chatMode==="channel"){const Et=`opt_${Date.now()}`,Ot={id:Et,sender:"user",text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};kt&&(Ot.replyToId=kt.id,Ot.replyToSender=kt.sender,Ot.replyToText=kt.text),O(Ee,Ae=>[...Ae,Ot]);const Wt=VC(Ze);H.groupChats.find(Ae=>Ae.channelKey===H.activeChannel);try{const Ae=await ie.channels.sendMessage(H.activeChannel,{text:Ze,senderName:H.authUser?.name??fe("page.fallbackYou"),mentions:Wt,senderId:H.authUser?.id,orgId:"default",replyToId:kt?.id,...gt?.length?{images:gt}:{},..._t?.length?{fileNames:_t}:{}});Ae.userMessage&&F(Ae.userMessage.id),Ae.agentMessage&&F(Ae.agentMessage.id),Ae.agentStopped&&O(Ee,Lt=>[...Lt,{id:`stopped_${Date.now()}`,sender:"agent",text:Ae.notice??fe("page.agentStopped"),time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}]),O(Ee,Lt=>{const it=Lt.filter(Qt=>Qt.id!==Et),At=[];return Ae.userMessage&&At.push(Dn(Ae.userMessage,H.authUser?.id)),Ae.agentMessage&&At.push(Dn(Ae.agentMessage,H.authUser?.id)),At.length>0?[...it,...At]:Lt})}catch(Ae){Bc(Ae)&&Wc();const Lt=QO(Ae);Lt&&(W(Ze),j(H.pendingImages));const it=oh(Ae,fe)||fe("page.errorWithMessage",{message:String(Ae)});O(Ee,At=>[...Lt?At.filter(es=>es.id!==Et):At,{id:`err_${Date.now()}`,sender:"agent",text:it,time:new Date().toLocaleTimeString(),agentName:fe("page.systemName"),isError:!0}])}N(Ee),g.current===Ee&&V(!1)}else{y(Ee);const Et=_e?.isResume?b(Ee)??[]:[],Ot=_e?.isResume?FC(Et):-1,Wt=Ot>=0?Et[Ot].id:void 0,Ae=Wt??Xv(),Lt=Xv();let it=_e?.sessionIdOverride??(H.activeSessionId===st?null:H.activeSessionId??null);if(_e?.isResume){const se=new Date().toISOString();O(Ee,je=>{if(Wt){const Pe=je.findIndex(be=>be.id===Wt);if(Pe>=0)return je.map((be,Te)=>Te===Pe?{...be,isStreaming:!0,isStopped:!1,isError:!1}:be)}return[...je,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:se,segments:[],isStreaming:!0}]},it)}else{const se=new Date().toISOString(),je=UC({id:Lt,text:Ze,time:new Date().toLocaleTimeString(),rawCreatedAt:se,chips:mt,images:gt,replyTo:kt});O(Ee,Pe=>[...Pe,je,{id:Ae,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:se,segments:[],isStreaming:!0}],it)}const At=se=>{d.current=Date.now(),m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=Pe[be];return Pe[be]={...Te,text:(Te.text??"")+se,segments:MO(Te.segments??[],se)},Pe},it)},Qt=se=>{d.current=Date.now(),m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=Pe[be];return Pe[be]={...Te,segments:LO(Te.segments??[],se)},Pe},it)},es=se=>{if(d.current=Date.now(),se.type==="session_start"&&se.sessionId){const je=it;if(it=se.sessionId,l.current.delete(se.sessionId),je&&je!==se.sessionId&&(P(Ee,je),H.selectedAgent&&je===st&&(ls.applyLocalOptimistic(H.selectedAgent,je,!1),ls.applyLocalOptimistic(H.selectedAgent,se.sessionId,!0))),_(Ee,se.sessionId),se.userMessageId&&!_e?.isResume&&O(Ee,Pe=>Pe.map(be=>be.id===Lt?{...be,id:se.userMessageId}:be),se.sessionId),g.current===Ee){const Pe=H.activeSessionId;(!Pe||Pe===st||Pe===se.sessionId)&&(Z(se.sessionId),R(Ee,se.sessionId),a(se.sessionId),H.selectedAgent&&K(H.selectedAgent,se.sessionId),le(be=>be.some(Te=>Te.id===st)?be.map(Te=>Te.id===st?{...Te,id:se.sessionId}:Te):be.some(Te=>Te.id===se.sessionId)?be:[...be,{id:se.sessionId,agentId:H.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=[...Pe[be].committedSegments??[]];return se.type==="thinking_commit"?Te.push({type:"text",content:"",thinking:se.content,createdAt:se.createdAt}):Te.push({type:"text",content:se.content,createdAt:se.createdAt}),Pe[be]={...Pe[be],committedSegments:Te},Pe},it)},de=se=>{d.current=Date.now(),se.phase!=="heartbeat"&&((se.phase==="start"||se.phase==="end")&&x(Ee,{...se,phase:se.phase,ts:Date.now()},it),se.phase==="start"?O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(ut=>ut.id===Ae);if(be<0)return je;const Te=[...Pe[be].segments??[]];let Fe=!1;if(se.arguments)for(let ut=Te.length-1;ut>=0;ut--){const xt=Te[ut];if(xt.type==="tool"&&xt.tool===se.tool&&xt.status==="running"){Te[ut]={...xt,args:se.arguments},Fe=!0;break}}const nt=`${se.tool}_${Date.now()}`,Ct=new Date().toISOString();Fe||Te.push({type:"tool",key:nt,tool:se.tool,status:"running",args:se.arguments,createdAt:Ct});const pt=[...Pe[be].committedSegments??[]];return se.arguments!==void 0&&pt.push({type:"tool",key:nt,tool:se.tool,status:"running",args:se.arguments,createdAt:Ct}),Pe[be]={...Pe[be],segments:Te,committedSegments:pt},Pe},it):se.phase==="output"?m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Fe=>Fe.id===Ae);if(be<0)return je;const Te=[...Pe[be].segments??[]];for(let Fe=Te.length-1;Fe>=0;Fe--){const nt=Te[Fe];if(nt.type==="tool"&&nt.tool===se.tool&&nt.status==="running"){Te[Fe]={...nt,liveOutput:GC(nt.liveOutput,se.output??"")};break}}return Pe[be]={...Pe[be],segments:Te},Pe},it):se.phase==="subagent_progress"&&se.subagentEvent?m(Ee,je=>{const Pe=[...je],be=Pe.findIndex(Ct=>Ct.id===Ae);if(be<0)return je;const Te=Ct=>{const pt=[...Ct];for(let ut=pt.length-1;ut>=0;ut--){const xt=pt[ut];if(xt.type==="tool"&&(xt.tool==="spawn_subagent"||xt.tool==="spawn_subagents")&&xt.status==="running"){pt[ut]={...xt,subagentLogs:NO(xt.subagentLogs,se.subagentEvent)};break}}return pt},Fe=Te(Pe[be].segments??[]),nt=Te(Pe[be].committedSegments??[]);return Pe[be]={...Pe[be],segments:Fe,committedSegments:nt},Pe},it):O(Ee,je=>{const Pe=[...je],be=Pe.findIndex(pt=>pt.id===Ae);if(be<0)return je;const Te=new Date().toISOString(),Fe=[...Pe[be].segments??[]];let nt;for(let pt=Fe.length-1;pt>=0;pt--){const ut=Fe[pt];if(ut.type==="tool"&&ut.tool===se.tool&&ut.status==="running"){nt=ut.subagentLogs,Fe[pt]={...ut,status:se.success===!1?"error":"done",args:se.arguments,result:se.result,error:se.error,durationMs:se.durationMs,liveOutput:void 0,createdAt:Te};break}}const Ct=[...Pe[be].committedSegments??[]];for(let pt=Ct.length-1;pt>=0;pt--){const ut=Ct[pt];if(ut.type==="tool"&&ut.tool===se.tool&&ut.status==="running"){Ct[pt]={...ut,status:se.success===!1?"error":"done",args:se.arguments,result:se.result,error:se.error,durationMs:se.durationMs,liveOutput:void 0,createdAt:Te,subagentLogs:nt??ut.subagentLogs};break}}return Pe[be]={...Pe[be],segments:Fe,committedSegments:Ct},Pe},it))},ge=new AbortController;e.current.set(f.current.activeSessionId??st,ge);const me=it,pe=me;pe&&l.current.delete(pe),pe&&_(Ee,pe),H.selectedAgent&&ls.applyLocalOptimistic(H.selectedAgent,pe??st,!0);try{d.current=Date.now();const se=await ie.agents.messageStream(H.selectedAgent,Ze,{onChunk:At,onThinking:Qt,onActivity:de,onCommit:es},{signal:ge.signal,images:gt,sessionId:me,isRetry:_e?.isRetry,isResume:_e?.isResume,fileNames:_t,replyTo:kt,titleSource:Je,chips:mt,userMessageId:Lt,assistantMessageId:Ae});if(g.current===Ee){if(se.merged&&O(Ee,Pe=>Pe.filter(be=>be.id!==Ae&&be.id!==Lt),it),!se.merged&&se.segments?.length&&O(Ee,Pe=>{const be=[...Pe],Te=be.findIndex(pt=>pt.id===Ae);if(Te<0)return Pe;const Fe=DO(se.segments,be[Te].segments);let nt=se.content||be[Te].text;nt||(nt=Fe.filter(pt=>pt.type==="text").map(pt=>pt.content).join(""));const Ct=se.emptyReply===!0;return be[Te]={...be[Te],text:nt,segments:Fe,committedSegments:Fe,isStopped:se.cancelled||be[Te].isStopped,emptyReply:se.emptyReply||Ct||void 0,isError:se.emptyReply||Ct?!0:be[Te].isError},be},it),!se.merged&&!se.segments?.length&&O(Ee,Pe=>{const be=[...Pe],Te=be.findIndex(xt=>xt.id===Ae);if(Te<0)return Pe;const Fe=be[Te],nt=Fe.committedSegments??[],pt=nt.filter(xt=>xt.type==="text"&&!!xt.content).map(xt=>xt.content).join("")||se.content||Fe.text,ut=se.emptyReply===!0;return(nt.length>0||pt||se.cancelled||se.emptyReply||ut)&&(be[Te]={...Fe,text:pt,segments:nt.length>0?nt:Fe.segments,isStopped:se.cancelled||Fe.isStopped,emptyReply:se.emptyReply||ut||void 0,isError:se.emptyReply||ut?!0:Fe.isError}),be},it),se.sessionId){Z(be=>!be||be===st||be===se.sessionId?se.sessionId:be);const Pe=v.get(Ee);(!Pe||Pe===st||Pe===se.sessionId)&&(R(Ee,se.sessionId),a(se.sessionId)),le(be=>be.some(Te=>Te.id===st)?be.map(Te=>Te.id===st?{...Te,id:se.sessionId}:Te):be.some(Te=>Te.id===se.sessionId)?be:[...be,{id:se.sessionId,agentId:H.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}re(H.selectedAgent).then(Pe=>{if(g.current===Ee&&(J(Pe),se.sessionId)){const be=Pe.find(Te=>Te.id===se.sessionId);be&&le(Te=>Te.some(nt=>nt.id===be.id)?Te.map(nt=>nt.id===be.id?be:nt):[be,...Te.filter(nt=>nt.id!==st)])}});const je=se.sessionId??(pe&&pe!==st?pe:null);if(!ge.signal.aborted&&!se.merged&&(se.softDisconnected??se.segments===void 0)&&H.chatMode==="direct"&&H.selectedAgent&&je){const Pe=H.selectedAgent;let be=!1,Te;for(let Fe=0;Fe<4&&!be&&(Fe>0&&await new Promise(nt=>setTimeout(nt,350*Fe)),!ge.signal.aborted);Fe+=1)try{const nt=await ie.sessions.streamStatus(Pe,je);if(nt.messageId&&(Te=nt.messageId),o0({aborted:ge.signal.aborted,sawTerminal:!1,serverStatus:a0(nt.status)})==="reattach"){O(Ee,pt=>pt.map(ut=>ut.id===Ae?{...ut,isStreaming:!0,isStopped:!1,segments:(ut.segments??[]).map(xt=>xt.type==="tool"&&(xt.status==="stopped"||xt.status==="running")?{...xt,status:"running"}:xt)}:ut),je),N(Ee),r(ge),_(Ee,je),k(Ee),Me(Pe,je,Ee),be=!0;return}break}catch{}if(!be&&!ge.signal.aborted){Te&&Ae&&O(Ee,Fe=>ka(Fe,Ae,Te),je);try{if(await Le(je,Ee)>0){N(Ee),r(ge),k(Ee);return}}catch{}}}}!se.merged&&(it||g.current===Ee)&&O(Ee,je=>ka(je,Ae,se.messageId),it)}catch(se){const je=se?.sessionId;je&&H.chatMode==="direct"&&g.current===Ee&&(Z(je),R(Ee,je),a(je),le(be=>be.map(Te=>Te.id===st?{...Te,id:je}:Te)),re(H.selectedAgent).then(be=>{if(g.current!==Ee)return;J(be);const Te=be.find(Fe=>Fe.id===je);Te&&le(Fe=>Fe.some(Ct=>Ct.id===Te.id)?Fe.map(Ct=>Ct.id===Te.id?Te:Ct):[Te,...Fe])})),Bc(se)&&Wc();const Pe=oh(se,fe);Pe?O(Ee,be=>{const Te=[...be],Fe=Te.findIndex(nt=>nt.id===Ae);return Fe>=0&&(Te[Fe]={...Te[Fe],text:Pe,isError:!0}),Te},it):O(Ee,be=>{const Te=[...be],Fe=Te.findIndex(nt=>nt.id===Ae);if(Fe>=0){const nt=BO(Te[Fe],"stopped");if(nt===null)return be.filter(Ct=>Ct.id!==Ae);Te[Fe]=nt}return Te},it)}O(Ee,se=>HC(se,Ae),it),ge.signal.aborted&&O(Ee,se=>{const je=[...se],Pe=je.findIndex(be=>be.id===Ae);if(Pe>=0){const be=BO(je[Pe],"stopped");if(be===null)return se.filter(Te=>Te.id!==Ae);je[Pe]=be}return je},it);const xe=(b(Ee)??[]).find(se=>se.id===Ae),ze=H.activeSessionId&&H.activeSessionId!==st?H.activeSessionId:null,He=xe?YC(xe):!1;xe&&!He&&H.chatMode==="direct"&&ze&&!ge.signal.aborted&&await(async(je,Pe)=>{for(let be=0;be<je;be++){const Te=TC(be,{baseMs:Pe,maxMs:8e3,maxAttempts:je});await new Promise(Fe=>setTimeout(Fe,Te));try{const nt=(await ie.sessions.getMessages(ze,2)).messages.find(Ct=>Ct.role==="assistant");if(nt?.content){const Ct=ah(nt);O(Ee,pt=>{const ut=[...pt],xt=ut.findIndex(Yn=>Yn.id===Ae);return xt>=0&&(ut[xt]={...ut[xt],text:Ct.text,segments:Ct.segments}),ut},it),O(Ee,pt=>ka(pt,Ae,Ct.id),it);return}}catch{}}})(5,2e3);const qe=N(Ee);P(Ee,it??st),H.selectedAgent&&ls.applyLocalOptimistic(H.selectedAgent,it??st,!1),k(Ee),[...e.current.values()].includes(ge)||e.current.size===0?(r(ge),p.delete(it??Ee),g.current===Ee&&(V(qe>0),qe===0&&U([]))):p.delete(it??Ee)}},[x,y,P,g,N,k,M,re,b,V,_,f,O,m]);return{send:$e,stopSending:we,tryReattachActiveStream:Me,loadSessionMessages:Le}}function f3({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=yt("team"),[n,a]=w.useState(!1),[o,l]=w.useState("agent"),[h,u]=w.useState(""),[d,f]=w.useState(!1),[p,v]=w.useState([]),[b,g]=w.useState(null),O=w.useRef(null),m=w.useCallback(async()=>{f(!0);try{const _=await QC(),T=_.providers?.markus;if(T?.configured&&T.enabled!==!1&&(!T.models||T.models.length===0))try{const E=await fetch("/api/models/live/markus",{credentials:"include"});if(E.ok){const I=await E.json();I.models?.length&&(T.models=I.models)}}catch{}const R=[];for(const[E,I]of Object.entries(_.providers??{})){if(!I.configured||I.enabled===!1)continue;const V=(I.models??[]).filter(S2).map(U=>({id:U.id,name:U.name}));V.length!==0&&R.push({provider:E,displayName:I.displayName??E,models:V})}R.sort((E,I)=>E.displayName.localeCompare(I.displayName)),v(R);const M=E=>!E?.provider||!E.model?!1:!!R.find(V=>V.provider===E.provider)?.models.some(V=>V.id===E.model);let N=null;if(_.routingDefaultModel?.provider&&_.routingDefaultModel?.model)N={provider:_.routingDefaultModel.provider,model:_.routingDefaultModel.model};else if(_.defaultProvider){const E=_.providers?.[_.defaultProvider];E?.model&&(N={provider:_.defaultProvider,model:E.model})}if(N&&!M(N)){const E=R.find(V=>V.provider==="markus"),I=E?.models[0]?{provider:"markus",model:E.models[0].id}:R[0]?.models[0]?{provider:R[0].provider,model:R[0].models[0].id}:null;I?(N=I,ie.settings.updateRouting({defaultProvider:I.provider,routingDefaultModel:I}).then(()=>Kv()).catch(()=>{})):N=null}g(N)}catch{v([])}finally{f(!1)}},[]);w.useEffect(()=>{m()},[m]),w.useEffect(()=>{n&&(l("agent"),u(""),m())},[n,m]),w.useEffect(()=>{if(!n)return;const _=T=>{O.current?.contains(T.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=w.useMemo(()=>{const _=h.trim().toLowerCase();return p.map(T=>({...T,models:_?T.models.filter(R=>R.id.toLowerCase().includes(_)||(R.name?.toLowerCase().includes(_)??!1)||T.displayName.toLowerCase().includes(_)||T.provider.toLowerCase().includes(_)):T.models})).filter(T=>T.models.length>0)},[p,h]),y=w.useCallback(_=>!_?.provider||!_.model?!1:p.length===0?!0:!!p.find(R=>R.provider===_.provider)?.models.some(R=>R.id===_.model),[p]);w.useEffect(()=>{if(!s||p.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const T=p.find(R=>R.provider==="markus");return T?.models[0]?{provider:"markus",model:T.models[0].id}:p[0]?.models[0]?{provider:p[0].provider,model:p[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!0})},[s,p,b,y,e]);const k=s&&y(s)?s:b,P=(k?.model?k.model.includes("/")?k.model.split("/").pop():k.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-[110px] md: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:k?`${k.provider}: ${k.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:P}),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:_=>u(_.target.value),placeholder:i("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-primary 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(ZO,{checked:o==="global",onChange:()=>l("global"),label:i("chatModel.applyGlobal",{defaultValue:"Apply to global"}),size:"sm",disabled:!t})]}),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(ZO,{checked:o==="agent",onChange:()=>l("agent"),label:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"}),size:"sm",disabled:!t})]}),!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:[d&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!d&&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"})}),!d&&x.length>0&&c.jsx("div",{className:"px-3 pb-1 text-[10px] text-fg-tertiary",children:i("chatModel.chatOnlyHint",{defaultValue:"Only models with a chat interface are listed"})}),!d&&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(T=>{const R=k?.provider===_.provider&&k?.model===T.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:T.id},o),o==="global"&&g({provider:_.provider,model:T.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-primary transition-colors ${R?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:T.id}),R&&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}:${T.id}`)})]},_.provider))]})]})]})}async function zv(s,e,t,r){if(e==="agent"){if(!t)return;await ie.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}});return}t&&r?.resetCurrentAgent!==!1&&await ie.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),await ie.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}}),Kv()}const qv="markus_team_sidebars_c";function Fp(s,e){return s.id===st?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Zv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):Fp(s,e)}const Up=new Set;function p3(){return window.location.hash}function m3(s){return Up.add(s),()=>{Up.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Up.forEach(s=>s()));function L3({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=yt(["team","common"]),a=w.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Gp(Ht.TEAM),[l,h]=w.useState(r?.agents??[]),[u,d]=w.useState(r?.humans??[]),[f,p]=w.useState(!r),v=Yp(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),g=w.useSyncExternalStore(m3,p3),O=v&&(g.startsWith(`#${Ht.TEAM}/`)||g.startsWith("#chat/")),m=v&&g.match(/^#team\/t\/(.+)$/),x=v?m?"team":O?"chat":"roster":"roster",y=m?m[1]:null;w.useEffect(()=>($O(v&&x==="chat"),()=>$O(!1)),[v,x]),w.useEffect(()=>(jO(Ht.TEAM,v&&x!=="roster"?1:0),()=>jO(Ht.TEAM,0)),[v,x]);const k=w.useCallback(()=>{window.location.hash=`${Ht.TEAM}/d`},[]),C=w.useCallback(S=>{window.location.hash=`${Ht.TEAM}/t/${S}`},[]);w.useEffect(()=>{if(!v)return;const S=()=>{qi(T.current)&&_("chat")};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[v]);const[P,_]=w.useState("chat"),T=w.useRef("chat");T.current=P;const R=RO({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[M,N]=w.useState(()=>{try{return localStorage.getItem(qv)==="1"}catch{return!1}}),E=w.useCallback(S=>{N(S);try{localStorage.setItem(qv,S?"1":"0")}catch{}},[]),I=Zo(),V=I?.leftCollapsed??!1,U=I?.rightPanel??null,W=I?.rightPanelTabs??[],ce=I?.activeRightPanelTabId??null,j=I?.rightPanelFullscreen??!1,B=U?"2xl:pr-8":"2xl:pr-[280px]",X=I?.setHostAvailable,Z=I?.collapseRightPanelOnly??I?.toggleRightPanel,K=I?.openRightPanel,le=400,J=320,G=6,[q,A]=w.useState(typeof window<"u"?window.innerWidth:1440),[ee,F]=w.useState("auto"),ae=w.useRef(V);w.useEffect(()=>{ae.current!==V&&(ae.current=V,N(V))},[V]);const re=I?.keyboardPane??"content",fe=w.useRef(!1),Le=w.useRef(re);w.useEffect(()=>{if(t||v||!o)return;const S=Le.current;Le.current=re,(re==="l1"||re==="l2")&&S!==re&&M&&(N(!1),I?.setLeftCollapsed(!1))},[re,t,v,o,M,I]),w.useEffect(()=>{if(t||v||!o)return;const S=Q=>{const $=I?.keyboardPane??"content";if($==="l0"||$==="l1"||$==="l2"||Q.metaKey||Q.ctrlKey||Q.altKey)return;if(Q.target instanceof HTMLElement){const Y=Q.target.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||Q.target.isContentEditable||Q.target.closest(".xterm"))return}const D=Q.key.length===1?Q.key.toLowerCase():Q.key;D!=="h"&&D!=="ArrowLeft"||(Q.preventDefault(),M&&(E(!1),I?.setLeftCollapsed(!1)),I?.setKeyboardPane(fe.current?"l2":"l1"))};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,v,o,I,M,E]),w.useEffect(()=>{if(X)return X(o&&!v),()=>X(!1)},[o,v,X]),w.useEffect(()=>t||v||!o?void 0:St.on("ui:right_panel",Q=>{const $=Q.payload;if($.action==="collapse"){Z?.();return}if($.action!=="open"||!$.panel||!K)return;const D=$.panel;if(D.kind==="url"&&D.url){const Y=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;K({kind:"url",url:D.url,title:D.title||D.url,browserId:Y});return}if(D.kind==="file"&&D.path){K({kind:"file",path:D.path,title:D.title});return}if(D.kind==="terminal"){const Y=D.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;K({kind:"terminal",terminalId:Y,title:D.title||"Terminal",cwd:D.cwd});return}D.kind==="deliverable"&&D.deliverableId&&ie.deliverables.get(D.deliverableId).then(Y=>{Y.deliverable&&K({kind:"deliverable",deliverable:Y.deliverable})}).catch(()=>{})}),[t,v,o,Z,K]);const we=w.useCallback((S,Q)=>{const $=ud.current,D=Q??Ss.current?.selectionStart??$.text.length,Y=rm({text:$.text,chips:$.chips},S,D);Or(Y.draft.text),pn(Y.draft.chips),requestAnimationFrame(()=>{const te=Ss.current;te&&(te.focus(),te.setSelectionRange(Y.caret,Y.caret))})},[]),Me=w.useCallback(S=>{if(!S)return;let Q=0;const $=m2(S,()=>`ctx_${Date.now()}_${++Q}`);if($.length===0)return;const D=ud.current,Y=F2({text:D.text,chips:D.chips},$);Or(Y.draft.text),pn(Y.draft.chips),requestAnimationFrame(()=>{const te=Ss.current;te&&(te.focus(),te.setSelectionRange(Y.caret,Y.caret))})},[]),$e=w.useRef(null),[ke,_e]=w.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),H=RO({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),Ue=w.useRef(null),[Ze,Je]=w.useState(!1),[mt,lt]=w.useState(!1),Tt=w.useCallback(()=>{Ze?lt(S=>!S):_e(S=>{const Q=!S;try{localStorage.setItem("markus_team_panel_visible",String(Q))}catch{}return Q})},[Ze]);w.useEffect(()=>{if(v)return;const S=Ue.current;if(!S)return;const Q=new ResizeObserver(([$])=>{if(!$)return;const D=$.contentRect.width;if(A(D),!t){const Y=D-R.width-H.width;Je(Y<400)}});return Q.observe(S),()=>Q.disconnect()},[v,t,R.width,H.width]);const gt=ke&&!Ze&&!mt,_t=M?0:R.width+G+(gt?H.width+G:0),Ee=Math.max(0,q-_t-G-8),kt=Math.min(le,Math.floor(Ee*.4)),ds=Math.max(0,Ee-kt),bt=Math.min(Math.round(Ee/2),ds),Ot=Math.max(0,Math.min(ee==="auto"?bt:ee,ds)),Wt=w.useRef(!1);w.useEffect(()=>{const S=(I?.rightPanel??null)!==null;S&&!Wt.current&&(N(!0),F("auto")),Wt.current=S},[I?.rightPanel]);const Ae=w.useRef(Ot);Ae.current=Ot;const Lt=w.useRef(ds);Lt.current=ds;const it=w.useCallback(S=>{S.preventDefault();const Q=S.clientX,$=Ae.current,D=te=>{const ne=$+(Q-te.clientX),Qe=Lt.current,De=Math.min(J,Qe);F(Math.max(De,Math.min(Qe,ne)))},Y=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",D),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);w.useEffect(()=>{if(!mt)return;const S=Q=>{Q.target.closest("[data-l2-floating]")||lt(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[mt]);const[At,Qt]=w.useState(null),[es,de]=w.useState(!1),ge=w.useRef(null);w.useEffect(()=>{if(!es)return;const S=$=>{ge.current&&!ge.current.contains($.target)&&de(!1)},Q=$=>{$.key==="Escape"&&de(!1)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",Q)}},[es]);const[me,pe]=w.useState(),[ye,xe]=w.useState(),[ze,He]=w.useState(),[qe,se]=w.useState(!1),[je,Pe]=w.useState(""),[be,Te]=w.useState(!1),[Fe,nt]=w.useState(""),Ct=w.useRef(null),pt=w.useRef(null),ut=w.useCallback((S,Q)=>{const $=S?nh[S]:void 0,D=$?"overview":S;xe($),pe(D),He(Q),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(D??"overview")},[v]);w.useCallback(S=>{S==="profile"?ut():qi(T.current)?history.back():_("chat")},[ut]);const xt=w.useCallback((S,Q)=>{$t("direct"),Ns(S),v&&k(),ut(Q?.tab,Q?.highlightMailboxId),Qt(null)},[v,k,ut]),Yn=w.useCallback((S,Q)=>{const $=l.find(D=>D.name.toLowerCase()===S.toLowerCase());if($){const D=Q.target.getBoundingClientRect();Qt({agentId:$.id,top:D.bottom,left:D.left})}},[l]),Vs=w.useMemo(()=>l.map(S=>S.name),[l]),[he,$t]=w.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[Se,Ns]=w.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[ft,Ds]=w.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Xt,ji]=w.useState(""),jl=500,ln=w.useRef(new Set),hd=S=>{if(ln.current.add(S),ln.current.size>jl){const Q=Math.floor(jl*.2),$=ln.current.values();for(let D=0;D<Q;D++){const Y=$.next().value;Y&&ln.current.delete(Y)}}},cn=w.useMemo(()=>{if(r?.channelMessages){const S=r.activeChannel??"custom:general";return r.channelMessages.filter(Q=>Q.channel===S).map(Q=>Dn(Q))}},[]),{manager:It,messages:rs,setMessages:$s,sending:cs,setSending:Ri,activities:hn,setActivities:dn,activeSessionBuffer:un,actBuffers:Gn,sessionTabsBuffer:Go,readConvMsgs:Fs,writeConvMsgs:sr,setActiveSession:z,currentConvKeyRef:oe,updateConvMsgs:Oe,updateConvMsgsRaf:We,appendConvActivity:Ge,beginLoad:et,beginStream:ot,endStream:jt,resetConv:at,abortStream:Os,loadAndDisplay:xs,incrementSending:rr,decrementSending:li,isSendingFor:Wr,setStreamSession:gr,clearStreamSession:us,getStreamSession:Xr,saveSessionToCache:dd,restoreSessionFromCache:Yt}=d3(cn),[qt,Or]=w.useState(""),[fn,Rl]=w.useState(null),[xr,pn]=w.useState([]),ud=w.useRef({text:"",chips:[]});ud.current={text:qt,chips:xr};const[El,Al]=w.useState(!!r?.streamLastMessage),mn=w.useRef(null),q_=400;w.useEffect(()=>(cs?(mn.current&&(clearTimeout(mn.current),mn.current=null),Al(!0)):El&&(mn.current=setTimeout(()=>{Al(!1),mn.current=null},q_)),()=>{mn.current&&clearTimeout(mn.current)}),[cs]);const fd=w.useRef({fullText:"",timers:[]});w.useEffect(()=>{if(!t||!r?.streamLastMessage||rs.length===0)return;const S=rs[rs.length-1];if(!S||S.sender!=="agent")return;const Q=S.text;fd.current.fullText=Q;const $=fd.current.timers;function D(){let te=0;$s(Qe=>Qe.map((De,ve)=>ve===Qe.length-1?{...De,text:""}:De)),Al(!0);const ne=setInterval(()=>{if(te+=1+Math.floor(Math.random()*2),te>=Q.length){clearInterval(ne),$s(ve=>ve.map((Ce,Be)=>Be===ve.length-1?{...Ce,text:Q}:Ce));const Qe=setTimeout(()=>Al(!1),800);$.push(Qe);const De=setTimeout(D,6e3);$.push(De)}else $s(Qe=>Qe.map((De,ve)=>ve===Qe.length-1?{...De,text:Q.slice(0,te)}:De))},30);$.push(ne)}const Y=setTimeout(D,1500);return $.push(Y),()=>{$.forEach(te=>clearTimeout(te)),fd.current.timers=[]}},[]);const[Z_,pg]=w.useState(!1),[pd,mg]=w.useState(!1),[V_,gg]=w.useState(!1);w.useEffect(()=>{if(!pd){gg(!1);return}const S=setTimeout(()=>gg(!0),250);return()=>clearTimeout(S)},[pd]);const[gn,zr]=w.useState(!0),[F_,md]=w.useState(!0),gd=w.useRef(0),[ir,Ml]=w.useState([]),[Og,xg]=w.useState(null),Od=w.useRef(null),Ss=w.useRef(null),[U_,Ei]=w.useState(null);w.useEffect(()=>{if(!Se){Ei(null);return}let S=!1;return ie.agents.get(Se).then(Q=>{if(S)return;const $=Q.effectiveModel;Ei($?.provider&&$?.model?{provider:$.provider,model:$.model}:null)}).catch(()=>{S||Ei(null)}),()=>{S=!0}},[Se]);const xd=w.useRef(!1),Ko=w.useCallback(()=>{const S=Ss.current;if(!S)return;const Q=xd.current,$=Q?36:52,D=qO(Q);S.style.height="auto";const Y=Math.max($,Math.min(S.scrollHeight,D));S.style.height=`${Y}px`,S.style.overflowY=Y>=D?"auto":"hidden"},[]);w.useEffect(()=>{const S=requestAnimationFrame(()=>Ko());return()=>cancelAnimationFrame(S)},[qt,ir.length,Ko]);const bd=S=>{try{const Q=localStorage.getItem(`markus_closed_tabs_${S}`);return Q?new Set(JSON.parse(Q)):new Set}catch{return new Set}},H_=(S,Q)=>{const $=bd(S);$.add(Q);try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...$]))}catch{}},Y_=(S,Q)=>{const $=bd(S);if($.delete(Q))try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...$]))}catch{}},bg=S=>{try{return localStorage.getItem(`markus_active_session_${S}`)}catch{return null}},Jo=(S,Q)=>{if(S)try{Q&&Q!==st?localStorage.setItem(`markus_active_session_${S}`,Q):localStorage.removeItem(`markus_active_session_${S}`)}catch{}},[Qr,Ai]=w.useState([]),[G_,Ll]=w.useState(0),[vg,Nl]=w.useState(1),[Dl,Il]=w.useState(!1),[Bl,yg]=w.useState(!1),[Ke,Mi]=w.useState(null),[ea,On]=w.useState(!1),[Sg,xn]=w.useState(!1),[vd,wg]=w.useState(null),[yd,Sd]=w.useState(""),[_g,wd]=w.useState([]),[bn,Wl]=w.useState(null),[K_,kg]=w.useState(null),[ta,_d]=w.useState([]),[vn,sa]=w.useState(null),[J_,Cg]=w.useState(null),Pg=w.useRef(new Set),[Tg,kd]=w.useState([]),[$r,ra]=w.useState(null),Li=$r?$r.items[$r.index]??null:null,[ek,Qg]=w.useState(null),[$g,Cd]=w.useState([]),[Is,tk]=w.useState([]),Us=S=>{tk(Q=>{const $=typeof S=="function"?S(Q):S,D=new Set,Y=$.filter(te=>D.has(te.id)?!1:(D.add(te.id),!0));return Y.some(te=>te.isMain)?[...Y.filter(te=>te.isMain),...Y.filter(te=>!te.isMain)]:Y})},jg=w.useRef(null);w.useEffect(()=>{if(!Ke)return;const S=jg.current;if(!S)return;const Q=S.querySelector(`[data-session-tab-id="${CSS.escape(Ke)}"]`);if(!Q)return;const $=requestAnimationFrame(()=>{Q.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($)},[Ke,Is.length]);const Xl=w.useRef(null),Pd=w.useRef(null),[ws,ia]=w.useState(r?.groupChats??[]),Td=w.useRef(ws);Td.current=ws;const Rg=w.useRef(null),[Qd,_s]=w.useState(!1),[$d,Kn]=w.useState(!1),[zl,jd]=w.useState(""),[sk,na]=w.useState(-1),[rk,ql]=w.useState([]),[ik,Eg]=w.useState(!1),Rd=w.useRef(void 0),[js,Ag]=w.useState(r?.teams??[]),[Ed,nk]=w.useState(!!r),[ok,ak]=w.useState([]),[Ad,Mg]=w.useState([]),[lk,ck]=w.useState(null),[x3,b3]=w.useState(!1),[v3,y3]=w.useState(""),[Jn,oa]=w.useState(!1),Zl=w.useRef(null),[Lg,hk]=w.useState(""),[aa,eo]=w.useState(0),[to,Vl]=w.useState(!1),[Ng,dk]=w.useState(""),[Md,la]=w.useState(0),[Ld,uk]=w.useState([]),Dg=w.useRef(!1),Nd=w.useCallback(()=>{Dg.current||(Dg.current=!0,(async()=>{try{const{skills:S}=await ie.skills.list();uk(S.map(Q=>({name:Q.name,description:Q.description??Q.name})))}catch{}})())},[]);w.useEffect(()=>{Nd()},[Nd]);const yn=Ng?Ld.filter(S=>S.name.toLowerCase().includes(Ng.toLowerCase())):Ld,[fk,pk]=w.useState([]),Ig=w.useRef(!1),mk=w.useCallback(()=>{Ig.current||(Ig.current=!0,(async()=>{const S=[];try{const[Q,$,D,Y,te]=await Promise.all([ie.projects.list().catch(()=>({projects:[]})),ie.requirements.list({lean:!0}).catch(()=>({requirements:[]})),ie.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),ie.deliverables.search({limit:100}).catch(()=>({results:[]})),ie.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const ne of Q.projects)S.push({id:ne.id,name:ne.name,entityType:"project",role:ne.status});for(const ne of $.requirements)S.push({id:ne.id,name:ne.title,entityType:"requirement",role:ne.priority});for(const ne of D.tasks)S.push({id:ne.id,name:ne.title,entityType:"task",role:ne.status});for(const ne of Y.results)S.push({id:ne.id,name:ne.title,entityType:"deliverable",role:ne.type});for(const ne of te.teams)try{const Qe=await ie.workflows.list(ne.id);for(const De of Qe.workflows)S.push({id:De.name,name:De.displayName||De.name,entityType:"workflow",role:`v${De.version}`})}catch{}}catch{}pk(S)})())},[]),is=he==="channel"?ws.find(S=>S.channelKey===ft)?.teamId:void 0,gk=w.useRef(null),qr=w.useRef(null),Bg=w.useRef(void 0),ca=w.useCallback((S,Q)=>{Mi(Q),S&&(Q===null?It.clearActiveSession(S):It.setActiveSession(S,Q))},[Mi,It]),Wg=w.useMemo(()=>Ma(he,Se,ft,Xt),[he,Se,ft,Xt]);lh();const ha=ls.isStreaming(Ke),Ok=ls.liveBubbleId(Ke),Sn=w.useMemo(()=>go(Wg,Ke),[Wg,Ke]),Bs=w.useRef(Sn);Bs.current=Sn;const[da,xk]=w.useState(Sn);if(w.useEffect(()=>{Ca.save(da,{text:qt,images:ir,context:xr,replyTo:fn})},[qt,da,ir,xr,fn]),da!==Sn){const S={text:qt,images:ir,context:xr,replyTo:fn};if(qt!==Ca.peek(da).text)Ca.save(Sn,S);else{Ca.save(da,S);const Q=Ca.get(Sn);Or(Q.text),Ml(Q.images),pn(Q.context),Rl(Q.replyTo)}xk(Sn)}const bs=w.useRef(null),Dd=w.useRef(null),ci=w.useRef(null),Id=w.useRef(null),Fl=w.useRef(0),Ul=w.useRef([]),so=w.useRef(null),Xg=w.useRef([]),Bd=w.useRef(void 0),Hl=w.useRef(null),wn=w.useCallback(()=>It.getActiveSession(oe.current)??oe.current,[It]),Ni=w.useCallback((S,Q)=>{S&&(It.setWindowBounds(S,Q),S===wn()&&pg(Q.hasMore))},[It,wn]);w.useEffect(()=>{pg(It.getWindowBounds(wn()).hasMore)},[It,wn,he,Se,ft,Xt,Ke]),w.useEffect(()=>{if(!ea)return;const S=Q=>{Pd.current&&!Pd.current.contains(Q.target)&&Xl.current&&!Xl.current.contains(Q.target)&&On(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[ea]);const Yl=(S,Q)=>{if(!Q||S===Q)return`notes:${S}`;const[$,D]=[S,Q].sort();return`dm:${$}:${D}`};w.useEffect(()=>{localStorage.setItem("markus_chat_mode",he)},[he]),w.useEffect(()=>{localStorage.setItem("markus_chat_agent",Se)},[Se]),w.useEffect(()=>{localStorage.setItem("markus_chat_channel",ft)},[ft]),w.useEffect(()=>{let S=!1;if(t||!Se||he!=="direct"){Ei(null);return}return ie.agents.get(Se).then(Q=>{if(S)return;const $=Q.config?.llmConfig;Ei($?.modelMode==="custom"&&$.primary&&$.defaultModel?{provider:$.primary,model:$.defaultModel}:null)}).catch(()=>{S||Ei(null)}),()=>{S=!0}},[Se,he,t]);const{counts:Wd,sessionAgentMap:ua,markRead:Xd,markReadMany:zg,setActiveKey:bk,clearActiveKeys:vk}=$C({enabled:!t}),Gl=w.useMemo(()=>{const S={};for(const[Q,$]of Object.entries(Wd))Q.startsWith("channel:")&&(S[Q.slice(8)]=$);return S},[Wd]),zd=jC(ua,Wd);w.useEffect(()=>{let S=0;for(const Q of zd.values())S+=Q;for(const Q of Object.values(Gl))S+=Q;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:S}}))},[zd,Gl]);const Kl=zd,yk=w.useCallback(async S=>{const Q=[];for(const[$,D]of Object.entries(ua))D===S&&Q.push(`session:${$}`);await zg(Q)},[ua,zg]);w.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(he==="direct"&&Se&&yk(Se),he==="channel"&&ft)Xd(`channel:${ft}`);else if(he==="direct"&&Ke)Xd(`session:${Ke}`);else if(he==="dm"&&Xt){const $=`dm:${[e?.id,Xt].sort().join(":")}`;Xd(`channel:${$}`)}const Q=[];if(he==="direct"&&Ke){Q.push(`session:${Ke}`);for(const[$,D]of Object.entries(ua))D===Se&&Q.push(`session:${$}`)}else he==="channel"&&ft?Q.push(`channel:${ft}`):he==="dm"&&Xt&&e?.id&&Q.push(`channel:dm:${[e.id,Xt].sort().join(":")}`);for(const $ of Q)bk($);return()=>{vk(Q)}},[t,he,ft,Ke,Xt,Se,x,P,ua]);const nr=w.useCallback(()=>ie.agents.list().then(S=>h(S.agents)).catch(()=>{}),[]),Sk=w.useCallback((S,Q)=>{S&&h($=>$.map(D=>D.id===S?{...D,avatarUrl:Q}:D))},[]),Hs=w.useCallback(()=>ie.teams.list().then(S=>{Ag(S.teams),nk(!0)}).catch(()=>{}),[]),ro=w.useCallback(()=>ie.groupChats.list().then(S=>ia(S.chats)).catch(()=>{}),[]),wk=w.useMemo(()=>pu(nr,3e3),[nr]),Jl=w.useMemo(()=>pu(Hs,5e3),[Hs]),qd=w.useMemo(()=>pu(ro,3e3),[ro]),fa=w.useCallback(()=>{ie.users.list(e?.orgId).then(S=>d(S.users)).catch(()=>{})},[e?.orgId]);w.useEffect(()=>{v&&(x!=="team"||!y||WO(y,js.map(S=>S.id),Ed)==="missing"&&(window.location.hash=Ht.TEAM))},[v,x,y,js,Ed]),w.useEffect(()=>{t||(Promise.all([nr(),Hs()]).finally(()=>p(!1)),fa(),ie.tasks.list().then(S=>Mg(S.tasks)).catch(()=>{}),ie.externalAgents.list().then(S=>ak(S.agents)).catch(()=>{}),ro())},[t,fa]),w.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),d(r.humans??[]),Ag(r.teams??[]),ia(r.groupChats??[]),r.channelMessages)){const S=r.activeChannel??"custom:general";$s(r.channelMessages.filter(Q=>Q.channel===S).map(Q=>Dn(Q)))}},[t,r]),w.useEffect(()=>{_P()},[]),w.useEffect(()=>{if(t||!o)return;const S=()=>{const te=Se,ne=Is.map(Qe=>Qe.id).filter(Qe=>Qe!==st);Ke&&Ke!==st&&!ne.includes(Ke)&&ne.push(Ke),te&&ne.length>0&&kP(te,ne)};let Q=null;const $=()=>{Q||(Q=setInterval(S,6e4))},D=()=>{Q&&clearInterval(Q),Q=null},Y=()=>{document.hidden?D():(S(),$())};return document.addEventListener("visibilitychange",Y),document.hidden||$(),S(),()=>{D(),document.removeEventListener("visibilitychange",Y)}},[t,o,Is,Se,Ke]),w.useEffect(()=>{if(t||!o)return;nr(),Hs();const S=setInterval(nr,3e4),Q=setInterval(Hs,6e4),$=St.on("agent:update",Be=>{const Ye=Be?.payload;if(Ye?.agentId){const ct=Ye.status,Gt=Ye.currentActivity;h(os=>os.map(Ut=>{if(Ut.id!==Ye.agentId)return Ut;const yr={...Ut};return ct&&(yr.status=ct),Gt!==void 0&&(yr.currentActivity=Gt),yr}))}wk(),Jl()}),D=St.on("team:update",()=>{Jl(),qd()}),Y=St.on("agent:removed",Jl),te=St.on("chat:group_created",()=>{ro(),Hs(),nr()}),ne=St.on("chat:group_updated",qd),Qe=St.on("chat:group_deleted",()=>{qd(),Jl()}),De=St.on("task:update",Be=>{const Ye=Be?.payload;Ye?.taskId&&Mg(ct=>ct.map(Gt=>Gt.id===Ye.taskId?{...Gt,status:Ye.status??Gt.status}:Gt))}),ve=St.on("approval:resolved",Be=>{const Ye=Be?.payload?.approvalId;Ye&&(Wl(ct=>ct&&ct.id===Ye?null:ct),sa(ct=>ct&&ct.id===Ye?null:ct))}),Ce=()=>{nr(),Hs(),fa()};return window.addEventListener("markus:data-changed",Ce),()=>{clearInterval(S),clearInterval(Q),$(),D(),Y(),te(),ne(),Qe(),De(),ve(),window.removeEventListener("markus:data-changed",Ce)}},[t,o,fa]),w.useEffect(()=>{if(t)return;const S=ve=>{const Ce=ve.detail;if(NC(Ce.page)===Ht.TEAM){if(Ce.params?.agentId&&(Ce.params.profileTab?xt(Ce.params.agentId,{tab:Ce.params.profileTab}):($t("direct"),Ns(Ce.params.agentId),_("chat"),v&&k(),Ce.params.sessionId?$e.current={agentId:Ce.params.agentId,sessionId:Ce.params.sessionId,chips:Ce.params.chatChips??null}:Ce.params.preferMain==="1"&&(ci.current={mode:"direct",agentId:Ce.params.agentId,sessionId:null,preferMain:!0}))),Ce.params?.selectAgent&&($t("direct"),Ns(Ce.params.selectAgent),_("chat"),v&&k()),Ce.params?.openDeliverable){const Be=Ce.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Ar.navigate(Ht.DELIVERABLES,{openDeliverable:Be}):K&&ie.deliverables.get(Be).then(Ye=>{Ye.deliverable&&K({kind:"deliverable",deliverable:Ye.deliverable})}).catch(()=>{})}if(Ce.params?.prefillMessage){const Be=Ce.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Ce.params?.autoSend==="true"?setTimeout(()=>Bg.current?.(Be),300):(Or(Be),setTimeout(()=>{const Ye=Ss.current;Ye&&(Ye.focus(),Ye.setSelectionRange(Ye.value.length,Ye.value.length))},100))}if(Ce.params?.chatChips){const Be=Ce.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ce.params.sessionId||Me(Be)}if(Ce.params?.dm&&($t("dm"),ji(Ce.params.dm),_("chat"),v&&k()),Ce.params?.channel&&($t("channel"),Ds(Ce.params.channel),_("chat"),v&&k()),Ce.params?.selectTeam){const Be=Ce.params.selectTeam;if(v)C(Be);else{const Ye=Td.current.find(ct=>ct.type==="team"&&ct.teamId===Be);$t("channel"),Ds(Ye?.channelKey??`group:${Be}`),_("chat"),_s(!1),_e(!0)}}Ce.params?.openHire}},Q=localStorage.getItem("markus_nav_agentId");if(Q){localStorage.removeItem("markus_nav_agentId");const ve=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),$t("direct"),Ns(Q),ve?xt(Q,{tab:ve}):(_("chat"),v&&k())}const $=localStorage.getItem("markus_nav_dm");$&&(localStorage.removeItem("markus_nav_dm"),$t("dm"),ji($),_("chat"),v&&k());const D=localStorage.getItem("markus_nav_channel");D&&(localStorage.removeItem("markus_nav_channel"),$t("channel"),Ds(D),_("chat"),v&&k());const Y=localStorage.getItem("markus_nav_prefillMessage");Y&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Or(Y),setTimeout(()=>{const ve=Ss.current;ve&&(ve.focus(),ve.setSelectionRange(ve.value.length,ve.value.length))},150));const te=localStorage.getItem("markus_nav_chatChips");te&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),Me(te));const ne=localStorage.getItem("markus_nav_openDeliverable");ne&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Ar.navigate(Ht.DELIVERABLES,{openDeliverable:ne}):K&&ie.deliverables.get(ne).then(ve=>{ve.deliverable&&K({kind:"deliverable",deliverable:ve.deliverable})}).catch(()=>{}));const Qe=localStorage.getItem("markus_nav_selectAgent");Qe&&(localStorage.removeItem("markus_nav_selectAgent"),$t("direct"),Ns(Qe),_("chat"),v&&k());const De=localStorage.getItem("markus_nav_selectTeam");if(De)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(De);else{const ve=Td.current.find(Ce=>Ce.type==="team"&&Ce.teamId===De);$t("channel"),Ds(ve?.channelKey??`group:${De}`),_("chat"),_s(!1),_e(!0)}return window.addEventListener("markus:navigate",S),()=>window.removeEventListener("markus:navigate",S)},[t]),w.useEffect(()=>{const S=Rg.current;if(!S)return;const Q=ws.find($=>$.type==="team"&&$.teamId===S);Rg.current=null,$t("channel"),Ds(Q?.channelKey??`group:${S}`),_("chat"),_s(!1),_e(!0)},[ws,js]),w.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||Se&&l.some($=>$.id===Se))return;const S=localStorage.getItem("markus_nav_after_remove");if(S&&(localStorage.removeItem("markus_nav_after_remove"),S.startsWith("channel:"))){$t("channel"),Ds(S.slice(8)),_("chat");return}const Q=l.find($=>!$.teamId&&$.role?.toLowerCase()==="secretary")??l.find($=>$.role?.toLowerCase()==="secretary")??l.find($=>$.name?.toLowerCase().includes("secretary"));Q?($t("direct"),Ns(Q.id),_("chat")):l.length>0&&($t("direct"),Ns(l[0].id),_("chat"))},[l,Se]);const io=w.useRef(!1),_n=w.useRef(!1),pa=w.useRef(0),Zd=w.useRef("none"),Vd=w.useRef(0),ec=w.useRef(0),hi=w.useRef(null),Fd=w.useRef(null),qg=w.useRef([]),Ud=w.useRef(0),[_k,kn]=w.useState(!1),no=w.useRef(0),[Zg,ma]=w.useState(0),oo=w.useCallback(()=>performance.now()<pa.current,[]),Di=w.useCallback(()=>oP({takeover:_n.current,gestureActive:oo()}),[oo]),or=w.useCallback(()=>{_n.current=!1,pa.current=0,Zd.current="none",Ud.current=0,ec.current+=1,io.current=!1,kn(!1),no.current=0,ma(0)},[]),Zr=w.useCallback(()=>{_n.current||(_n.current=!0,ec.current+=1,io.current=!1,hi.current!==null&&(cancelAnimationFrame(hi.current),hi.current=null),kn(!0))},[]),tc=w.useCallback(S=>{pa.current=performance.now()+Ou,S!=="none"&&(Zd.current=S);const Q=qr.current;aP(S,!!Q&&KO(Q))&&Zr()},[Zr]),sc=w.useCallback(S=>{const Q=qr.current;if(!Q)return;const $=Q.scrollTop-Vd.current;Vd.current=Q.scrollTop;const D=nP({takeover:_n.current,gestureActive:oo(),gestureDirection:Zd.current,scrollable:KO(Q),distance:Xc(Q),deltaScrollTop:$,programmatic:S?.programmatic??io.current,intentPending:bs.current!==null});D==="handover"?Zr():D==="resume"?or():D==="follow"?(kn(!1),no.current=0,ma(0)):_n.current&&kn(!0)},[oo,Zr,or]);w.useEffect(()=>{const S=qr.current;if(!S)return;let Q=null;const $=Ce=>{tc(eP(Ce.deltaX,Ce.deltaY))},D=Ce=>{Q=Ce.touches[0]?.clientY??null,pa.current=performance.now()+Ou},Y=Ce=>{const Be=Ce.touches[0]?.clientY;if(Be==null)return;const Ye=iP(Q,Be);Q=Be,tc(Ye)},te=()=>{Q=null},ne=Ce=>{Kp(Ce.target)||tc(rP(Ce.key))},Qe=Ce=>{const Be=S.getBoundingClientRect();Ce.clientX-Be.left<S.clientWidth||(pa.current=performance.now()+Ou)},De=()=>{sc()};S.addEventListener("wheel",$,{passive:!0}),S.addEventListener("touchstart",D,{passive:!0}),S.addEventListener("touchmove",Y,{passive:!0}),S.addEventListener("touchend",te,{passive:!0}),S.addEventListener("pointerdown",Qe,{passive:!0}),S.addEventListener("scroll",De,{passive:!0}),document.addEventListener("keydown",ne);const ve=typeof ResizeObserver<"u"?new ResizeObserver(()=>sc()):null;return ve?.observe(S),Vd.current=S.scrollTop,sc(),()=>{S.removeEventListener("wheel",$),S.removeEventListener("touchstart",D),S.removeEventListener("touchmove",Y),S.removeEventListener("touchend",te),S.removeEventListener("pointerdown",Qe),S.removeEventListener("scroll",De),document.removeEventListener("keydown",ne),ve?.disconnect()}},[x,sc,tc]);const Hd=w.useMemo(()=>new Set($g),[$g]),ns=w.useMemo(()=>{const S=he==="channel"?rs:rs.filter(D=>!D.isActivityLog),Q=Hd.size===0?S:S.filter(D=>!(D.isNotification&&Hd.has(D.id))),$=t&&El?Q.length-1:-1;return Q.filter((D,Y)=>KC(D,Y===$||!!D.isStreaming&&ha))},[rs,he,Hd,ha,t,El]);w.useEffect(()=>{xd.current=P==="chat"&&ns.length>0,Ko()},[P,ns.length,Ko]);const ao=A2({count:ns.length,getScrollElement:()=>qr.current,getItemKey:S=>ns[S]?.id??S,estimateSize:S=>{const Q=ns[S];return Q?Q.segments&&Q.segments.length>0?300:Q.text.length>500?200:120:120},overscan:8});ao.shouldAdjustScrollPositionOnItemSizeChange=(S,Q,$)=>mu()||bs.current?.priority==="jump"?!1:S.start<($.scrollOffset??0);const ar=w.useCallback((S="instant")=>{if(!Di()||performance.now()<Ud.current)return;const Q=qr.current;if(!Q)return;const $=++ec.current,D=()=>$===ec.current&&Di();if(S==="smooth"){Ud.current=performance.now()+K2,Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"});return}hi.current!==null&&(cancelAnimationFrame(hi.current),hi.current=null),io.current=!0;let Y=0;const te=()=>{if(hi.current=null,!D()){io.current=!1;return}if(Q.scrollTop=Q.scrollHeight,Y+=1,Y<G2&&Xc(Q)>1){hi.current=requestAnimationFrame(te);return}io.current=!1};Q.scrollTop=Q.scrollHeight,hi.current=requestAnimationFrame(te)},[Di]),Cn=w.useCallback(S=>{const Q=qr.current;!Q||!S||Q.scrollHeight<=Q.clientHeight||t0.save(S,cP(e0(Q),Q))},[]),Pn=w.useCallback(()=>{Fl.current+=1;for(const S of Ul.current)clearTimeout(S);Ul.current=[]},[]),lo=w.useCallback(()=>{bs.current=null,Pn()},[Pn]),Vg=w.useCallback(()=>{or(),lo(),Fd.current!==null&&cancelAnimationFrame(Fd.current);for(const S of qg.current)clearTimeout(S);ar("instant"),Fd.current=requestAnimationFrame(()=>ar("instant")),qg.current=[60,160,320].map(S=>setTimeout(()=>ar("instant"),S))},[or,lo,ar]),Yd=w.useCallback(S=>{const Q=bs.current;if(!Q||Q.key!==S)return!0;if(Bs.current!==S||Q.priority!=="prepend"&&oo())return bs.current=null,!0;const $=qr.current;if(!$)return!0;if(mu())return!1;const{anchor:D}=Q;if(D.kind==="bottom"){xu(Q.priority)&&or(),$.scrollTop=$.scrollHeight;const Ye=Xc($)<=1,ct=i0(Ye,Q.prevSettled);return Q.prevSettled=Ye,ct?(bs.current=null,!0):!1}const Y=gP(Q.at,performance.now()),te=uP(e0($),$,D.id,D.delta),ne=te===null&&!Y&&(Fs(Q.bufferId)??[]).some(Ye=>Ye.id===D.id),Qe=te!==null&&Math.abs(te)<=1,De=i0(Qe,Q.prevSettled),ve=te===null&&!ne,Ce=It.getWindowBounds(Q.bufferId).hasMore,Be=OP({priority:Q.priority,rendered:te!==null,stale:Y,stable:De,absent:ve,canLoadMore:Ce});switch(Q.prevSettled=te!==null?Qe:null,xu(Q.priority)&&Be!=="release-bottom"&&Be!=="release-hold"&&Zr(),Be){case"apply":return zi("intent:apply",{id:D.id,priority:Q.priority,correction:te}),bs.current=null,!0;case"refine":return te!==null&&Math.abs(te)>1&&($.scrollTop+=te),te!==null&&Math.abs(te)>8&&zi("intent:refine",{id:D.id,priority:Q.priority,correction:te}),!1;case"release-bottom":return zi("intent:release-bottom",{id:D.id,priority:Q.priority}),bs.current=null,xu(Q.priority)&&or(),$.scrollTop=$.scrollHeight,!0;case"release-hold":return zi("intent:release-hold",{id:D.id,priority:Q.priority,stale:Y,absent:ve,canLoadMore:Ce,bufferId:Q.bufferId}),bs.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:Q.priority,anchor:D}),!0;default:{const Ye=Xg.current.findIndex(ct=>ct.id===D.id);if(Ye>=0){const ct=ao.getOffsetForIndex(Ye,"start");ct&&($.scrollTop=ct[0]+D.delta)}else Bd.current?.();return!1}}},[ao,oo,Zr,or,Fs]),rc=w.useCallback(()=>{const S=bs.current;if(!S)return;const Q=S.key;Pn();const $=Fl.current,D=te=>{Ul.current.push(setTimeout(()=>{$===Fl.current&&bs.current?.key===Q&&(Yd(Q)||D(r0))},te))},Y=[0,60,160,320,560,900];Y.forEach((te,ne)=>{const Qe=ne===Y.length-1,De=()=>{if($!==Fl.current)return;!Yd(Q)&&Qe&&D(r0)};te===0?requestAnimationFrame(De):Ul.current.push(setTimeout(De,te))})},[Yd,Pn]),co=w.useCallback((S,Q,$="restore",D)=>{if(!S)return!1;const Y=bs.current;return pP(Y,{key:S,priority:$})?(bs.current={key:S,bufferId:D??wn(),anchor:Q,at:performance.now(),priority:$,prevSettled:null},rc(),!0):!1},[wn,rc]),ga=w.useCallback(S=>{S&&co(S,t0.get(S)??{kind:"bottom"})},[co]),kk=w.useCallback(()=>{bs.current||(so.current!==null&&clearTimeout(so.current),so.current=setTimeout(()=>{so.current=null,Cn(Bs.current)},200))},[Cn]);Xg.current=ns,w.useLayoutEffect(()=>()=>{Cn(Bs.current),Pn(),so.current!==null&&clearTimeout(so.current)},[Cn,Pn]);const Oa=w.useMemo(()=>yI(ns,zl),[ns,zl]);w.useEffect(()=>{na(-1)},[zl]);const ic=w.useCallback(S=>{const Q=()=>{const Y=document.getElementById(`msg-${S}`);return Y?(Y.classList.remove("chat-find-hit"),Y.offsetWidth,Y.classList.add("chat-find-hit"),window.setTimeout(()=>Y.classList.remove("chat-find-hit"),1600),!0):!1};let $=0;const D=()=>{Q()||$++>=8||window.requestAnimationFrame(D)};D()},[]),Fg=w.useCallback(async(S,Q)=>{lo(),Zr();const $=Bs.current,D=oe.current,Y=()=>(Fs(D)??[]).some(ne=>ne.id===S);let te=Y();if(!te&&$){const ne=It.getActiveSession(D)??D,Qe=await wI({targetId:S,has:Y,targetCreatedAt:Q,fetchPage:async ve=>{if(!ne||ne===st)return{messages:[],hasMore:!1};const Ce=await ie.sessions.getMessages(ne,50,ve);return{messages:Ce.messages,hasMore:Ce.hasMore}}}),De=SI(Qe.messages,S);De.length>0&&(sr(D,De.map(ah)),Ni(ne,{hasMore:Qe.hasMore,oldestCursor:De[0]?new Date(De[0].createdAt).toISOString():null})),te=Qe.found||Y(),zi("jump:collected",{messageId:S,found:Qe.found,kept:De.length,exhausted:Qe.exhausted})}if(zi("jump:located",{messageId:S,loaded:te,key:$,nowKey:Bs.current}),!($&&Bs.current!==$)){if(te&&$){co($,JO(S),"jump",wn()),zi("jump:scheduled",{messageId:S,key:$}),ic(S);return}$&&(zi("jump:fallback-bottom",{messageId:S,key:$}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:S}),or(),ar("instant"))}},[lo,Zr,co,ic,Fs,It,sr,Ni,or,ar]),Ck=w.useCallback(S=>{const Q=Oa.matches[S];Q&&(na(S),lo(),Zr(),Bs.current&&co(Bs.current,JO(Q.messageId),"jump"),ic(Q.messageId))},[Oa.matches,lo,Zr,co,ic]);w.useEffect(()=>{if(P!=="chat"||t)return;const S=Q=>{Q.key.toLowerCase()!=="f"||Q.altKey||Q.shiftKey||!(b?Q.metaKey&&!Q.ctrlKey:Q.ctrlKey&&!Q.metaKey)||(Q.preventDefault(),Kn(!0))};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[P,t,b]);const Ug=w.useRef(o);w.useEffect(()=>{Ug.current=o},[o]),w.useLayoutEffect(()=>{const S=Dd.current;if(S&&(Dd.current=null,!bs.current&&S.key===Bs.current)){const Q=qr.current,$=Q?Q.scrollHeight-S.scrollHeight:0;Q&&$>0&&(Q.scrollTop+=$,Q.dispatchEvent(new Event("scroll")))}if(bs.current){rc();return}Ug.current&&Di()&&(mu()||ar())},[rs,ar,Di,rc]);const Hg=w.useRef(P);w.useEffect(()=>{const S=Hg.current!=="chat";Hg.current=P,P==="chat"&&S&&ga(Bs.current)},[P,cs,ar,Di,ga]);const Yg=w.useRef(B);w.useEffect(()=>{if(Yg.current===B||(Yg.current=B,P!=="chat")||ns.length===0||cs||gn||!Di())return;const S=[],Q=requestAnimationFrame(()=>ar("instant"));for(const $ of[60,160,320])S.push(setTimeout(()=>ar("instant"),$));return()=>{cancelAnimationFrame(Q);for(const $ of S)clearTimeout($)}},[B,P,ns.length,cs,gn,ar,Di]);const nc=w.useCallback(async(S,Q,$)=>{const D=Q??`ch:${S}`;!$?.quiet&&oe.current===D&&zr(!0);try{const Y=await ie.channels.getMessages(S,50),te=Y.messages.map(ne=>Dn(ne,e?.id));sr(D,te),Ni(D,{hasMore:Y.hasMore,oldestCursor:Y.messages[0]?new Date(Y.messages[0].createdAt).toISOString():null}),oe.current===D&&$s(te)}catch{oe.current===D&&$s([])}finally{!$?.quiet&&oe.current===D&&zr(!1)}},[Ni]),Gd=w.useCallback(async S=>{if(!S)return Ai([]),Ll(0),Nl(1),Il(!1),md(!1),[];md(!0);try{const Q=await ie.sessions.listByAgent(S,20,1);return Ai(Q.sessions),Ll(Q.total??Q.sessions.length),Nl(Q.page??1),Il(!!Q.hasMore),Q.sessions}catch{return Ai([]),Ll(0),Nl(1),Il(!1),[]}finally{md(!1)}},[]),Gg=w.useRef({chatContext:[],input:"",pendingImages:[],chatMode:he,selectedAgent:Se,activeSessionId:Ke,activeDmUserId:Xt,authUser:e,activeChannel:ft,groupChats:ws,agents:l,humans:u,sending:cs,chatReplyTo:null});Gg.current={chatContext:xr,input:qt,pendingImages:ir,chatMode:he,selectedAgent:Se,activeSessionId:Ke,activeDmUserId:Xt,authUser:e,activeChannel:ft,groupChats:ws,agents:l,humans:u,sending:cs,chatReplyTo:fn};const Pk=u3({stateRef:Gg,actBuffers:Gn,activeSessionBuffer:un,readConvMsgs:Fs,currentConvKeyRef:oe,updateConvMsgs:Oe,updateConvMsgsRaf:We,appendConvActivity:Ge,beginStream:ot,endStream:jt,abortStream:Os,clearStreamSession:us,setStreamSession:gr,getStreamSession:Xr,setActiveSession:z,incrementSending:rr,decrementSending:li,loadAndDisplay:xs,sessionSwitchSeqRef:gd,setSending:Ri,setActivities:dn,setInput:Or,setChatContext:pn,setPendingImages:Ml,setMentionDropdown:oa,setChatReplyTo:Rl,setActiveSessionId:Mi,setStoredActiveSession:Jo,setOpenSessionTabs:Us,setSessions:Ai,setLoadingChat:zr,setWindowBounds:Ni,makeConvKey:Ma,makeDmChannel:Yl,addRecentMsgId:hd,resumeChatScrollFollow:or,loadSessions:Gd,t:i}),{send:ho,stopSending:Tk,tryReattachActiveStream:uo,loadSessionMessages:Kd}=Pk;Bg.current=ho;const Kg=w.useCallback(()=>{Vg(),ho()},[Vg,ho]),Jg=w.useRef(uo);Jg.current=uo;const Qk=lh();w.useEffect(()=>{if(!o||t||he!=="direct"||!Se)return;const S=Ke;!S||S===st||ls.isStreaming(S)&&Jg.current(Se,S,oe.current)},[o,t,he,Se,Ke,Qk]);const $k=w.useCallback(async()=>{if(Bl||!Se||!Dl)return;yg(!0);const S=vg+1,Q=Se;try{const $=await ie.sessions.listByAgent(Q,20,S);Ai(D=>{const Y=new Set(D.map(ne=>ne.id)),te=[...D,...$.sessions.filter(ne=>!Y.has(ne.id))];return Ll($.total??te.length),te}),Nl(S),Il(!!$.hasMore)}catch{}yg(!1)},[Bl,Dl,vg,Se]),eO=w.useCallback(S=>{wg(S.id),Sd((S.isMain?"":S.title)||"")},[]),xa=w.useCallback(()=>{wg(null),Sd("")},[]),tO=w.useCallback(async S=>{const Q=yd.trim();if(!Q){xa();return}try{const D=(await ie.sessions.renameTitle(S.id,Q))?.session?.title??Q;Ai(Y=>Y.map(te=>te.id===S.id?{...te,title:D}:te)),Us(Y=>Y.map(te=>te.id===S.id?{...te,title:D}:te))}catch{}xa()},[yd,xa]),sO=w.useCallback(async()=>{if(Hl.current)return Hl.current;const S=oe.current,Q=It.getActiveSession(S)??S,$=It.getWindowBounds(Q),D=$.oldestCursor;if(!$.hasMore||!D)return 0;const Y=Q&&Q!==st?Q:null,ne=(async()=>{mg(!0);try{const Qe=Bs.current;let De=[],ve=!1,Ce=null;if(he==="channel"||he==="dm"){const Ut=he==="dm"?Yl(e?.id??"",Xt):ft,yr=await ie.channels.getMessages(Ut,50,D);De=yr.messages.map(lr=>Dn(lr,e?.id)),ve=yr.hasMore,Ce=yr.messages[0]?new Date(yr.messages[0].createdAt).toISOString():null}else if(Y){const Ut=await ie.sessions.getMessages(Y,50,D);De=Ut.messages.map(ah),ve=Ut.hasMore,Ce=Ut.messages[0]?new Date(Ut.messages[0].createdAt).toISOString():null}else return 0;if(De.length===0)return Ni(Q,{hasMore:ve,oldestCursor:D}),0;if(oe.current!==S||Bs.current!==Qe)return 0;const Be=qr.current,Ye=Be?Be.scrollHeight:null,ct=Fs(S)??[],Gt=new Set(De.map(Ut=>Ut.id));let os=[...De,...ct.filter(Ut=>!Gt.has(Ut.id))];return os.length>500&&(os=os.slice(-500)),sr(S,os),Ni(Q,{hasMore:ve,oldestCursor:Ce}),Ye!==null&&(Dd.current={key:Bs.current,scrollHeight:Ye}),$s(os),De.length}catch{return 0}finally{mg(!1)}})();Hl.current=ne;try{return await ne}finally{Hl.current=null}},[he,ft,e?.id,Xt,Fs,sr,It,Ni]);Bd.current=sO;const Jd=w.useRef(!1),jk=w.useCallback(S=>{kk(),!Jd.current&&(Jd.current=!0,requestAnimationFrame(()=>{Jd.current=!1,S.target.scrollTop<100&&Bd.current?.()}))},[]);w.useEffect(()=>{if(t)return;const S=Ma(he,Se,ft,Xt),Q=oe.current;oe.current=S,Q&&Q!==S&&(Go.set(Q,Is),Ke&&Vp(Q)&&z(Q,Ke),Cn(go(Q,Ke))),Q!==S&&(or(),kn(!1),no.current=0,ma(0),Kn(!1),jd(""),na(-1));const $=Fs(S),D=Go.get(S),Y=un.get(S)??(Se?bg(Se)??void 0:void 0),te=Xr(S),ne=Y??Ke,Qe=he!=="direct"?Wr(S):l0(te,ne),De=ne??S,ve=Gn.get(De)??[];dn(Qe?ve:[]),Ri(Qe),he==="direct"&&Se&&Gd(Se),D&&D.length>0&&Us(D),On(!1);const Ce=CP(ci.current,{chatMode:he,agentId:Se});if($!==void 0&&$.length>0)if(Qe||It.completeLoad(S),zr(!1),$s($),Y!==void 0&&(ca(S,Y),ga(go(S,Y))),(!D||D.length===0)&&Us([]),he==="channel"||he==="dm"){const Ye=he==="dm"?Yl(e?.id??"",Xt):ft;nc(Ye,S)}else he==="direct"&&Se&&Y&&Y!==st&&!Ce&&(Qe?uo(Se,Y,S):Kd(Y,S).then(()=>{oe.current===S&&Se&&uo(Se,Y,S)}));else if(et(S),zr(!0),$s([]),sr(S,[]),he==="channel"||he==="dm"){const Ye=he==="dm"?Yl(e?.id??"",Xt):ft;nc(Ye,S),(!D||D.length===0)&&Us([])}else he==="direct"&&Se?Gd(Se).then(Ye=>{if(oe.current===S)if(Ye.length>0){const ct=Ye.find(Ws=>Ws.isMain),Gt=bd(Se),os=ct?[ct,...Ye.filter(Ws=>!Ws.isMain&&!Gt.has(Ws.id)).slice(0,4)]:Ye.filter(Ws=>!Gt.has(Ws.id)).slice(0,5);let Ut=D&&D.length>0?D:os;const yr=bg(Se),lr=Y!==void 0?Y:yr??ct?.id??Ut[0].id;if(lr&&lr!==st&&!Ut.some(Ws=>Ws.id===lr)){const Ws=Ye.find(Vr=>Vr.id===lr);Ws&&(Ut=[...Ut,Ws])}const ui=lr&&Ut.some(Ws=>Ws.id===lr)?lr:Ut[0].id,Bi=ci.current;if(Bi&&Bi.mode==="direct"&&Bi.agentId===Se&&(Bi.sessionId||Bi.preferMain)){Us(Ut);return}ca(S,ui),ga(go(S,ui)),Jo(Se,ui),Us(Ut),Kd(ui,S).then(()=>{oe.current===S&&Se&&uo(Se,ui,S)})}else ca(S,null),zr(!1),(!D||D.length===0)&&Us([])}).catch(()=>{oe.current===S&&zr(!1)}):zr(!1)},[t,he,Se,ft,Xt,n.language,i]),w.useEffect(()=>t?void 0:St.on("chat:message",Q=>{const $=Q.payload,D=$.channel??"";if(!D)return;const Y=$.senderType??"agent",te=$.text??$.message??"",ne=$.senderId??$.agentId??"",Qe=$.senderName??$.agentId??i("page.fallbackAgent"),De=$.metadata,ve=$.messageId??$.id??"";if(ve&&ln.current.has(ve))return;const Ce=Y==="human"&&ne===(e?.id??""),Be={id:ve||`ws_${Date.now()}_${ne}`,sender:Ce?"user":"agent",text:te,time:new Date().toLocaleTimeString(),rawCreatedAt:Q.timestamp??new Date().toISOString(),agentName:Ce?void 0:Qe,agentId:Ce?void 0:ne,replyToId:$.replyToId??void 0,replyToSender:$.replyToSender??void 0,replyToText:$.replyToText??void 0};if(De&&Y==="agent"){const ct=[];if(De.thinking?.length&&ct.push({type:"text",content:"",thinking:De.thinking.join(`
81
81
 
82
82
  `)}),De.toolCalls?.length)for(let Gt=0;Gt<De.toolCalls.length;Gt++){const os=De.toolCalls[Gt];ct.push({type:"tool",key:`${os.tool}_${Gt}`,tool:os.tool,status:os.status==="error"?"error":"done",args:os.arguments,result:os.result,durationMs:os.durationMs})}ct.length>0&&(ct.push({type:"text",content:te}),Be.segments=ct)}let Ye;if(D.startsWith("notes:"))Ye=`dm:${D.slice(6)}`;else if(D.startsWith("dm:")){const ct=D.slice(3).split(":");Ye=`dm:${ct.find(os=>os!==(e?.id??""))??ct[0]??""}`}else Ye=`ch:${D}`;Oe(Ye,ct=>gu(ct,Be)),Ye===oe.current&&_n.current&&(no.current+=1,ma(no.current),kn(!0))}),[t,Oe,e?.id,ft]);const rO=w.useRef(!1);w.useEffect(()=>t?void 0:St.on("connected",()=>{const Q=!rO.current;rO.current=!0,!Q&&he==="channel"&&ft&&nc(ft,void 0,{quiet:!0})}),[t,he,ft,nc]),w.useEffect(()=>t?void 0:St.on("session:title_updated",Q=>{const $=Q.payload;if(!$)return;const D=$.sessionId,Y=$.title;!D||typeof Y!="string"||(Ai(te=>te.map(ne=>ne.id===D?{...ne,title:Y}:ne)),Us(te=>te.map(ne=>ne.id===D?{...ne,title:Y}:ne)))}),[t]),w.useEffect(()=>t?void 0:St.on("chat:proactive_message",Q=>{const $=Q.payload,D=$.targetUserId;if(D&&D!==e?.id)return;const Y=$.agentId??"",te=$.agentName??i("page.fallbackAgent"),ne=$.message??"",Qe=$.sessionId??"",De=$.messageId??"",ve=$.metadata??{};if(!Y||!ne||ne==="[cancelled]"||ne==="[Stream cancelled]")return;const Ce=ve.role==="user",Be=!Ce&&(!!ve.activityLog||ne.startsWith("[ACTIVITY:")),{cleaned:Ye,priority:ct}=JC(ne),Gt=!Ce&&(!!ve.notifyUser||Ye!==ne),os=Ma("direct",Y,"","");if(Qe&&oe.current===os){const jr=Ke;if(jr&&jr!==st&&jr!==Qe)return}const Ut=!!ve.isMainSession&&!Ce,yr=Qe||Ke,lr=typeof ve.userText=="string"?ve.userText:"",ui=typeof ve.userMessageId=="string"?ve.userMessageId:"",Bi=typeof ve.createdAt=="string"&&ve.createdAt||(typeof Q.timestamp=="string"?Q.timestamp:void 0)||new Date().toISOString(),Ws=(()=>{try{return new Date(Bi).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Vr={id:De||`proactive_${Date.now()}`,sender:Ce?"user":"agent",text:Ye,time:Ws,rawCreatedAt:Bi,...Ce?{}:{agentName:te,agentId:Y,...Gt?{isNotification:!0,notifyPriority:ve.priority??ct}:{},...Be?{isActivityLog:!0,activityType:ve.activityType,outcome:ve.outcome,mailboxItemId:ve.mailboxItemId,taskId:ve.taskId,requirementId:ve.requirementId}:{},...!Be&&ve.taskId?{taskId:ve.taskId}:{},...!Be&&ve.requirementId?{requirementId:ve.requirementId}:{}}};Gt&&Vr.id&&Cd(jr=>jr.includes(Vr.id)?jr:[...jr,Vr.id]),Oe(os,jr=>{if(jr.some(Rn=>Rn.id===Vr.id))return jr;let jn=jr;if(!Ce&&lr&&(jn.some(Wi=>ui&&Wi.id===ui||Wi.sender==="user"&&Wi.text===lr)||(jn=gu(jn,{id:ui||`feishu_user_${Vr.id}`,sender:"user",text:lr,time:new Date().toLocaleTimeString(),rawCreatedAt:Vr.rawCreatedAt}))),Ut)for(let Rn=jn.length-1;Rn>=0;Rn--){const Wi=jn[Rn];if(Wi.sender==="agent"&&Wi.agentId===Y&&Wi.isStopped){const wO=[...jn];return wO[Rn]={...Vr,id:Wi.id},wO}}return gu(jn,Vr)},yr||void 0)}),[t,Oe,i,Ke]),Ad.find(S=>S.id===lk),w.useEffect(()=>{ck(null)},[Se]);const[br,eu]=w.useState(null),[iO,nO]=w.useState(!1),[Rk,oO]=w.useState(null),[Ii,tu]=w.useState(null),Ek=w.useMemo(()=>{for(let S=rs.length-1;S>=0;S--)if(rs[S]?.sender==="agent"&&!rs[S]?.isActivityLog)return rs[S].id;return null},[rs]),Ak=w.useCallback(S=>{const Q=S.segments?S.segments.filter($=>$.type==="text").map($=>$.content).join(`
83
83
  `):S.text;navigator.clipboard.writeText(Q),oO(S.id),setTimeout(()=>oO($=>$===S.id?null:$),2e3)},[]),su=w.useCallback((S,Q,$)=>{const D=oe.current,Y=Fs(D)??rs,te=Y.findIndex(Qe=>Qe.id===S.id);if(te<0)return;const ne=Q&&te>0&&Y[te-1]?.id===Q.id;Oe(D,Qe=>{const De=Qe.findIndex(ve=>ve.id===(ne?Q.id:S.id));return De>=0?Qe.slice(0,De):Qe}),ho($,{isRetry:!0})},[rs,Oe]),Mk=w.useCallback(S=>{const Q=oe.current,$=Fs(Q)??rs,D=$.findIndex(Qe=>Qe.id===S.id);if(D<0)return;let Y=null;for(let Qe=D-1;Qe>=0;Qe--)if($[Qe]?.sender==="user"){Y=$[Qe];break}const te=Y?.text??"";if(!te)return;if(D<$.length-1){const Qe=$.length-1-D;tu({retryMsg:S,userMsg:Y,retryText:te,followCount:Qe});return}su(S,Y,te)},[rs,su]),Lk=w.useCallback(S=>{const Q=oe.current;if((Fs(Q)??rs).findIndex(te=>te.id===S.id)<0)return;Oe(Q,te=>{const ne=[...te],Qe=ne.findIndex(Ce=>Ce.id===S.id);if(Qe<0)return te;const De=ne[Qe],ve=[...De.segments??[]];for(;ve.length>0;){const Ce=ve[ve.length-1];if(Ce.type==="tool"&&(Ce.status==="stopped"||Ce.status==="running"))ve.pop();else if(Ce.type==="text"&&!Ce.content)ve.pop();else break}return ne[Qe]={...De,segments:ve,isStopped:!1,isError:!1},ne});const Y=un.get(Q)??(Ke&&Ke!==st?Ke:null);if(!Y){console.warn("[resume] no session bound to this conversation — resume aborted");return}ho("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0,sessionIdOverride:Y})},[rs,Oe,Ke]),Nk=w.useCallback(S=>{const Q=S.sender==="user"?e?.name??i("page.fallbackYou"):S.agentName??i("page.fallbackAgent");if(Rl({id:S.id,sender:Q,text:S.text}),he==="channel"&&S.sender==="agent"&&S.agentName){const $=`@${S.agentName} `;Or(D=>D.startsWith($)?D:$+D)}Ss.current?.focus()},[e?.name,he,i]),Dk=async S=>{if(!br||!Se||he!=="direct")return;const Q=Ke;if(!(!Q||Q===st)){nO(!0);try{const $=await ie.agents.evolveFromMessage(Se,{parentSessionId:Q,sourceMessageId:br.isStreaming===!0||br.id.startsWith("a_")||br.id.startsWith("u_")?void 0:br.id,sourceText:(br.text||"").slice(0,500)||void 0,userNote:S.trim()||void 0}),D=new Date().toISOString(),Y={id:$.sessionId,agentId:Se,userId:e?.id??null,title:"Remember / Evolution",isMain:!1,metadata:{kind:"evolution",parentSessionId:$.parentSessionId,sourceMessageId:br.id,sourceAgentId:Se,createdFrom:"remember_button"},createdAt:D,lastMessageAt:D};eu(null),Ai(ne=>[Y,...ne.filter(Qe=>Qe.id!==Y.id)]),Us(ne=>ne.some(Qe=>Qe.id===Y.id)?ne:[...ne,Y]),Mi(Y.id);const te=Ma("direct",Se,ft,Xt);at(te,Y.id),Jo(Se,Y.id),$s([]),await ho($.seedPrompt,{sessionIdOverride:$.sessionId})}catch($){console.error("evolve-from-message failed",$)}finally{nO(!1)}}},di=async S=>{const Q=++gd.current,$=Ke,D=oe.current;Cn(go(D,$)),ca(D,S.id),ga(go(D,S.id)),On(!1),or(),kn(!1),no.current=0,ma(0);const Y=Xr(D),ne=l0(Y,S.id);Ri(ne),dn(ne?Gn.get(S.id)??[]:[]),Se&&Jo(Se,S.id),$&&$!==st&&dd(D,$);const Qe=Yt(D,S.id);(!Qe||Qe.length===0)&&S.id!==st&&zr(!0),Us(De=>De.some(ve=>ve.id===S.id)?De:[...De,S]),Se&&Y_(Se,S.id),oe.current!==D&&(oe.current=D);try{await Kd(S.id,D)}finally{gd.current===Q&&zr(!1)}Se&&uo(Se,S.id,D)};w.useEffect(()=>{const S=$e.current;!S||Se!==S.agentId||($e.current=null,(async()=>{try{const{sessions:Q}=await ie.sessions.listByAgent(S.agentId,50),$=Q.find(D=>D.id===S.sessionId);if(!$){S.chips&&Me(S.chips);return}await di($),S.chips&&Me(S.chips)}catch{S.chips&&Me(S.chips)}})())},[Se,di,Me]);const Ik=S=>{if(Us(Q=>Q.filter($=>$.id!==S)),Se&&S!==st&&H_(Se,S),Ke===S){const Q=Is.filter($=>$.id!==S);Q.length>0?di(Q[Q.length-1]):ba()}},aO=w.useCallback(async S=>{if(S.trim().length<2){ql([]);return}Eg(!0);try{const Q=he==="channel"?"channel":he==="direct"?"direct":"all",$=he==="channel"?ft:void 0,{results:D}=await ie.messages.search(S,{scope:Q,channel:$,limit:30});ql(D)}catch{ql([])}Eg(!1)},[he,ft]),Bk=w.useCallback(S=>{jd(S),Rd.current&&clearTimeout(Rd.current),Rd.current=setTimeout(()=>{aO(S)},300)},[aO]),oc=w.useRef(null),Wk=w.useCallback(S=>{if(Kn(!1),jd(""),ql([]),S.source==="channel"&&S.channel){$t("channel"),Ds(S.channel),_("chat"),ci.current={messageId:S.id,mode:"channel",channel:S.channel};return}S.source==="direct"&&S.agentId&&($t("direct"),_("chat"),S.agentId!==Se&&Ns(S.agentId),ci.current={messageId:S.id,mode:"direct",agentId:S.agentId,sessionId:S.sessionId??null,createdAt:S.createdAt})},[Se]);w.useEffect(()=>{const S=ci.current;if(!S)return;const Q=()=>{Id.current=null,ci.current===S&&(ci.current=null,S.messageId&&Fg(S.messageId,S.createdAt))};if(S.mode==="channel"){if(he!=="channel"||ft!==S.channel||gn)return;Q();return}if(he!=="direct"||P!=="chat"||S.agentId&&S.agentId!==Se)return;const $=S.preferMain?(Qr.find(D=>D.isMain)??Is.find(D=>D.isMain))?.id:S.sessionId;if(!(S.preferMain&&!$)){if($&&$!==Ke){if(Id.current===S)return;const D=Qr.find(Y=>Y.id===$)??Is.find(Y=>Y.id===$)??(Qr.length===0?null:void 0);if(D===null)return;Id.current=S,(async()=>{const Y=new Date().toISOString();await di(D??{id:$,agentId:S.agentId??Se??"",userId:null,title:null,createdAt:Y,lastMessageAt:Y}),Q()})();return}gn||Q()}},[he,ft,Se,Ke,Qr,Dl,Is,gn,P,ns,Fg,di]);const ba=()=>{Cn(Bs.current),Pn(),bs.current=null,Mi(st);const S=oe.current;at(S,st),$s([]),On(!1),Us($=>{const D=$.filter(Y=>Y.id!==st);return[{id:st,agentId:Se??"",userId:null,title:i("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...D]});const Q=Se;Q&&ie.sessions.create(Q).then($=>{const D=$?.session;if(!D?.id)return;const Y=D.id;if(oe.current!==S)return;const te=un.get(S);te!==void 0&&te!==st||(ca(S,Y),Jo(Q,Y),Us(ne=>ne.map(Qe=>Qe.id===st?{...Qe,id:Y,title:D.title??Qe.title}:Qe)))}).catch(()=>{})},va=w.useCallback(()=>{t||!o||P==="chat"&&(vd||qe||be||Jn||to||Ii||br||requestAnimationFrame(()=>{const S=Ss.current;S&&!S.disabled&&(S.focus(),S.setSelectionRange(S.value.length,S.value.length))}))},[t,o,P,vd,qe,be,Jn,to,Ii,br]),lO=w.useRef(o),cO=w.useRef(Se),hO=w.useRef(Ke);w.useEffect(()=>{const S=o&&!lO.current,Q=Se!==cO.current,$=Ke!==hO.current;lO.current=o,cO.current=Se,hO.current=Ke,!v&&(S||Q||$)&&va()},[o,Se,Ke,v,va]),w.useEffect(()=>{if(t||!o||v)return;const S=Q=>{if(Ii||br||Jn||to||DC(Q.target))return;const $=c2({key:Q.key,metaKey:Q.metaKey,ctrlKey:Q.ctrlKey,altKey:Q.altKey,shiftKey:Q.shiftKey},b);if($==="new-conversation"){if(he!=="direct"||!Se||P!=="chat")return;const D=Q.target;if(D&&D!==Ss.current&&(D.tagName==="INPUT"||D.tagName==="TEXTAREA"||D.isContentEditable))return;Q.preventDefault(),ba(),va();return}if($==="cycle-session-next"||$==="cycle-session-prev"){if(he!=="direct"||!Se||P!=="chat"||Is.length<2)return;const D=$==="cycle-session-prev"?-1:1,Y=h2(Is.map(ne=>ne.id),Ke,D);if(!Y)return;Q.preventDefault();const te=Is.find(ne=>ne.id===Y);if(!te)return;if(te.id===st){Mi(st);const ne=oe.current;at(ne,st),$s([])}else di(te);va()}};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,o,v,b,he,Se,P,Is,Ke,Jn,to,Ii,br,ba,di,va,Mi,at,$s,oe]);const Xk=S=>{const Q=X2({text:qt,chips:xr},S);Or(Q.text),pn(Q.chips);const $=Ss.current?.selectionStart??S.length,D=S.slice(0,$),Y=D.lastIndexOf("@");if(Y>=0){const te=Y===0?"":D[Y-1];if(Y===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(te)){const Qe=D.slice(Y+1);if(!Qe.includes(" ")&&!Qe.includes(`