@markus-global/cli 0.12.5-rc.0 → 0.12.5-rc.2

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/web-ui/assets/{AsyncState-ByYn1wrM.js → AsyncState-BCS9C43h.js} +1 -1
  2. package/dist/web-ui/assets/{ChatComponents-Bwh8SlUV.js → ChatComponents-B4gMEEQr.js} +1 -1
  3. package/dist/web-ui/assets/{ContentRenderer-GLgoGp2a.js → ContentRenderer-iGJdjFvn.js} +2 -2
  4. package/dist/web-ui/assets/{DeliverableShareModal-CRfnRuR3.js → DeliverableShareModal-CY0_wqDC.js} +1 -1
  5. package/dist/web-ui/assets/{Deliverables-EFsnf6kU.js → Deliverables-oCzunom7.js} +1 -1
  6. package/dist/web-ui/assets/{MarkdownMessage-CaLBeMto.js → MarkdownMessage-B-9NMrYX.js} +1 -1
  7. package/dist/web-ui/assets/{Search-COiaXUNr.js → Search-Badheo3V.js} +1 -1
  8. package/dist/web-ui/assets/{SendToChat-DleryIlc.js → SendToChat-X-3sK9Ph.js} +1 -1
  9. package/dist/web-ui/assets/{Settings-CzY8z2Yh.js → Settings-B05tnigv.js} +1 -1
  10. package/dist/web-ui/assets/{Store-C4VpQCM_.js → Store-B4hpcTFJ.js} +1 -1
  11. package/dist/web-ui/assets/{Switch-ByogYoGH.js → Switch-BgdJa330.js} +1 -1
  12. package/dist/web-ui/assets/{Team-Cutq2J24.js → Team-Dfz_Jkoy.js} +4 -4
  13. package/dist/web-ui/assets/{Work-BO-mz-na.js → Work-DqxE8g_Q.js} +1 -1
  14. package/dist/web-ui/assets/{arc-mYv67jdD.js → arc-Dns31Tc9.js} +1 -1
  15. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Bzpz_1r6.js → architectureDiagram-3BPJPVTR-C0MbQViF.js} +1 -1
  16. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BBrLiivl.js → blockDiagram-GPEHLZMM-DRAhpfjQ.js} +1 -1
  17. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BwDUoXA_.js → c4Diagram-AAUBKEIU-DVAnq8L5.js} +1 -1
  18. package/dist/web-ui/assets/channel-Dll32qm6.js +1 -0
  19. package/dist/web-ui/assets/{chunk-2J33WTMH-DCSfJ-S9.js → chunk-2J33WTMH-CNZ1Di5i.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-4BX2VUAB-CI0n1b2H.js → chunk-4BX2VUAB-BfZWR2ax.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-55IACEB6-DqlSWLrm.js → chunk-55IACEB6-CLvm88GS.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-727SXJPM-BtmAfGYV.js → chunk-727SXJPM-YptrHhiQ.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BgkA4lpQ.js → chunk-AQP2D5EJ-Bht-7eQm.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-FMBD7UC4-DCSr1JH4.js → chunk-FMBD7UC4-CXoaPK-Q.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-ND2GUHAM-CETYBRRm.js → chunk-ND2GUHAM-Bor_8TtZ.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-QZHKN3VN-C58yD7lH.js → chunk-QZHKN3VN-BWVZxTBv.js} +1 -1
  27. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BAXna0Rk.js +1 -0
  28. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BAXna0Rk.js +1 -0
  29. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BpvdK03m.js → cose-bilkent-S5V4N54A-Dc0GRajy.js} +1 -1
  30. package/dist/web-ui/assets/{dagre-BM42HDAG-CZ1K-KD5.js → dagre-BM42HDAG-CTnRRUJj.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-2AECGRRQ-D136Ok1V.js → diagram-2AECGRRQ-BJpt589H.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-5GNKFQAL-Ji6qPYYV.js → diagram-5GNKFQAL-Wonl9ScH.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-KO2AKTUF-B-s2RC-f.js → diagram-KO2AKTUF-DYlCFdL8.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-LMA3HP47-COWaps70.js → diagram-LMA3HP47-0bqbxPqr.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-OG6HWLK6-bh6MvwWn.js → diagram-OG6HWLK6-CCgq0GqI.js} +1 -1
  36. package/dist/web-ui/assets/{docx-preview-BRynUqJd.js → docx-preview-BvKeUHJr.js} +1 -1
  37. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DOPh2LlL.js → erDiagram-TEJ5UH35-CLUiZPDr.js} +1 -1
  38. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-B_kxDHIp.js → flowDiagram-I6XJVG4X-f6pN4cw1.js} +1 -1
  39. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DYBKHOkK.js → ganttDiagram-6RSMTGT7-BwJkS7mo.js} +1 -1
  40. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-D8_0BxLC.js → gitGraphDiagram-PVQCEYII-DI2zMknR.js} +1 -1
  41. package/dist/web-ui/assets/{index-TAHyKznL.js → index-Dc1HlaXE.js} +6 -6
  42. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DayJP7Ws.js → infoDiagram-5YYISTIA-oD_kael7.js} +1 -1
  43. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-vzxCYVSq.js → ishikawaDiagram-YF4QCWOH-CU8h8XWC.js} +1 -1
  44. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-B-Fud82o.js → journeyDiagram-JHISSGLW-0RIRYcwi.js} +1 -1
  45. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-DzuKdB65.js → kanban-definition-UN3LZRKU-BbjHZ91H.js} +1 -1
  46. package/dist/web-ui/assets/{mermaid.core-D4ql87kI.js → mermaid.core-BlPZWkyC.js} +5 -5
  47. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DosvXt2g.js → mindmap-definition-RKZ34NQL-BvaY6iLy.js} +1 -1
  48. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-DhXtMWhr.js → pieDiagram-4H26LBE5-CHAkMEBP.js} +1 -1
  49. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-D33pLLOq.js → quadrantDiagram-W4KKPZXB-BLmxZKSH.js} +1 -1
  50. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-B-iIz-XM.js → requirementDiagram-4Y6WPE33-CszQubly.js} +1 -1
  51. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-BMd9AFEW.js → sankeyDiagram-5OEKKPKP-ovwXJ_-9.js} +1 -1
  52. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CI1MIdwo.js → sequenceDiagram-3UESZ5HK-C5biPL1f.js} +1 -1
  53. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-Bq6FKPW2.js → stateDiagram-AJRCARHV-B_H8A-zE.js} +1 -1
  54. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-BHZhFie0.js +1 -0
  55. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-BDdmmSRo.js → timeline-definition-PNZ67QCA-DxHkO_i6.js} +1 -1
  56. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-DP2q5vY2.js → vennDiagram-CIIHVFJN-XuByI13m.js} +1 -1
  57. package/dist/web-ui/assets/{wardley-L42UT6IY-Bw3fjszD.js → wardley-L42UT6IY-DEu5IbdV.js} +1 -1
  58. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-37bQUocJ.js → wardleyDiagram-YWT4CUSO-Coe77zhN.js} +1 -1
  59. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-DnLDZyNC.js → xychartDiagram-2RQKCTM6-vMLEL3LK.js} +1 -1
  60. package/dist/web-ui/index.html +1 -1
  61. package/docs/architecture/desktop-auto-update.md +26 -11
  62. package/package.json +1 -1
  63. package/dist/web-ui/assets/channel-Bx09lbhA.js +0 -1
  64. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGZqU3iA.js +0 -1
  65. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGZqU3iA.js +0 -1
  66. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-8nMhmWY5.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownMessage-CaLBeMto.js","assets/index-TAHyKznL.js","assets/index-9SXWNIl0.css"])))=>i.map(i=>d[i]);
2
- import{r as w,a1 as xl,u as Tt,aD as sp,j as c,U as Rt,aE as Cs,k as ne,aF as uC,$ as uc,a as rp,b as ip,P as Ut,c as zo,aG as uh,X as fC,A as Is,n as gr,a7 as qo,i as np,aH as mC,aI as op,aJ as pC,aK as Kv,aL as EO,aM as AO,aN as gC,aO as OC,aP as Jv,aQ as ey,aR as xC,aS as bC,aT as vC,aU as MO,aV as yC,aW as SC,aX as wC,a5 as fc,V as LO,Z as _C,Y as kC,h as ap,aY as mu,aZ as CC,a_ as PC,d as TC,a$ as ty,b0 as QC,b1 as Df,aA as sy,b2 as $C,b3 as NO,b4 as jC,b5 as RC,b6 as EC,a6 as AC,_ as ry,a9 as DO,b7 as MC,ax as LC,b8 as NC,b9 as IO,R as BO,Q as WO,ba as DC,bb as IC,bc as pu,bd as BC,be as WC,bf as XO,E as zO,bg as XC,bh as zC,bi as qC,y as ZC,W as VC,bj as FC,bk as iy}from"./index-TAHyKznL.js";import{MarkdownMessage as Hi}from"./MarkdownMessage-CaLBeMto.js";import{t as lp,f as cp,s as UC,L as ny,a as fh,i as qO,E as HC,l as YC,P as oy,g as GC,d as mh,b as KC,c as gu,p as JC,r as e2,e as ZO,h as VO,j as FO,k as _a,m as UO,n as t2,o as HO,q as Bn,u as Vc,v as Fc,w as s2,x as r2,y as i2,z as YO,A as n2,B as o2,C as a2,D as Ou,F as GO,G as l2,H as xu,I as bu,J as c2,K as mc,M as KO,N as h2,O as d2,Q as JO,R as u2,S as f2,T as m2,U as p2,V as g2,W as O2,X as e0,Y as x2,Z as b2,_ as v2,$ as y2,a0 as S2}from"./ChatComponents-Bwh8SlUV.js";import{P as ay,E as w2,L as ly,S as _2}from"./AsyncState-ByYn1wrM.js";import{c as k2,C as cy,o as If,p as C2,a as P2,b as T2}from"./chatChips-DVIRVTpT.js";import{i as Q2,S as t0,n as s0,o as $2}from"./Switch-ByogYoGH.js";import{ContentRenderer as Bf,resolveFormat as j2}from"./ContentRenderer-GLgoGp2a.js";import{a as R2,c as E2,D as A2}from"./DeliverableShareModal-CRfnRuR3.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,O=b/16,g=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${g(b,5)} /${g(v,5)} ms`,`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownMessage-B-9NMrYX.js","assets/index-Dc1HlaXE.js","assets/index-9SXWNIl0.css"])))=>i.map(i=>d[i]);
2
+ import{r as w,a1 as xl,u as Tt,aD as sp,j as c,U as Rt,aE as Cs,k as ne,aF as uC,$ as uc,a as rp,b as ip,P as Ut,c as zo,aG as uh,X as fC,A as Is,n as gr,a7 as qo,i as np,aH as mC,aI as op,aJ as pC,aK as Kv,aL as EO,aM as AO,aN as gC,aO as OC,aP as Jv,aQ as ey,aR as xC,aS as bC,aT as vC,aU as MO,aV as yC,aW as SC,aX as wC,a5 as fc,V as LO,Z as _C,Y as kC,h as ap,aY as mu,aZ as CC,a_ as PC,d as TC,a$ as ty,b0 as QC,b1 as Df,aA as sy,b2 as $C,b3 as NO,b4 as jC,b5 as RC,b6 as EC,a6 as AC,_ as ry,a9 as DO,b7 as MC,ax as LC,b8 as NC,b9 as IO,R as BO,Q as WO,ba as DC,bb as IC,bc as pu,bd as BC,be as WC,bf as XO,E as zO,bg as XC,bh as zC,bi as qC,y as ZC,W as VC,bj as FC,bk as iy}from"./index-Dc1HlaXE.js";import{MarkdownMessage as Hi}from"./MarkdownMessage-B-9NMrYX.js";import{t as lp,f as cp,s as UC,L as ny,a as fh,i as qO,E as HC,l as YC,P as oy,g as GC,d as mh,b as KC,c as gu,p as JC,r as e2,e as ZO,h as VO,j as FO,k as _a,m as UO,n as t2,o as HO,q as Bn,u as Vc,v as Fc,w as s2,x as r2,y as i2,z as YO,A as n2,B as o2,C as a2,D as Ou,F as GO,G as l2,H as xu,I as bu,J as c2,K as mc,M as KO,N as h2,O as d2,Q as JO,R as u2,S as f2,T as m2,U as p2,V as g2,W as O2,X as e0,Y as x2,Z as b2,_ as v2,$ as y2,a0 as S2}from"./ChatComponents-B4gMEEQr.js";import{P as ay,E as w2,L as ly,S as _2}from"./AsyncState-BCS9C43h.js";import{c as k2,C as cy,o as If,p as C2,a as P2,b as T2}from"./chatChips-DVIRVTpT.js";import{i as Q2,S as t0,n as s0,o as $2}from"./Switch-BgdJa330.js";import{ContentRenderer as Bf,resolveFormat as j2}from"./ContentRenderer-iGJdjFvn.js";import{a as R2,c as E2,D as A2}from"./DeliverableShareModal-CY0_wqDC.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,O=b/16,g=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${g(b,5)} /${g(v,5)} ms`,`
3
3
  font-size: .6rem;
4
4
  font-weight: bold;
5
5
  color: hsl(${Math.max(0,Math.min(120-120*O,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 r0(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const M2=(s,e)=>Math.abs(s-e)<1.01,L2=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},i0=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},N2=s=>s,D2=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},I2=(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(i0(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(i0(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},n0={passive:!0},o0=typeof window>"u"?!0:"onscrollend"in window,B2=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&o0?()=>{}:L2(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,n0);const h=s.options.useScrollendEvent&&o0;return h&&t.addEventListener("scrollend",l,n0),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},W2=(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"]},X2=(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 z2{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:N2,rangeExtractor:D2,onChange:()=>{},measureElement:W2,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 O,g;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){O=b;const C=f[O],P=C!==void 0?d[C]:void 0;g=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?d[p-1]:this.getFurthestMeasurement(d,p);g=C?C.end+this.options.gap:r+i,O=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,O)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),k=g+y;d[p]={index:p,start:g,size:y,end:k,key:v,lane:O},f[O]=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?q2({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 r0(r[hy(0,r.length-1,i=>r0(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&&M2(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 hy=(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 q2({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=hy(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 a0=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Z2({useFlushSync:s=!0,...e}){const t=w.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?xl.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=w.useState(()=>new z2(r));return i.setOptions(r),a0(()=>i._didMount(),[]),a0(()=>i._willUpdate()),i}function V2(s){return Z2({observeElementRect:I2,observeElementOffset:B2,scrollToFn:X2,...s})}function F2(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 U2({approval:s,submitting:e,readOnly:t,onClose:r,onSubmit:i}){const{t:n}=Tt(["team","common"]);sp(!0);const a=w.useMemo(()=>F2(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}}))},O=(C,P)=>{const _=v(C.id);if(C.allowMultiple){const Q=_.selectedOptionIds.includes(P);b(C.id,{selectedOptionIds:Q?_.selectedOptionIds.filter(E=>E!==P):[..._.selectedOptionIds,P],text:Q?_.text:""})}else{const Q=_.selectedOptionIds.includes(P);b(C.id,{selectedOptionIds:Q?[]:[P],text:Q?_.text:""})}},g=C=>{const P=v(C.id);return C.inputType==="choice"?P.selectedOptionIds.length>0?(C.options??[]).some(Q=>Q.id&&P.selectedOptionIds.includes(Q.id)&&Q.requiresFreeform)?P.text.trim().length>0:!0:!!(C.allowFreeform&&P.text.trim()):P.text.trim().length>0},m=a.every(g),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 E=C[0];_=E?.selectedOptionIds?.[0]??(E?.text?"custom":void 0),P=_!=="reject"&&_!=="request_changes"}const Q=C.map(E=>E.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"),we=oe=>{if(!(de?oe.metaKey&&!oe.ctrlKey:oe.ctrlKey&&!oe.metaKey)||!oe.shiftKey||oe.altKey||oe.key.toLowerCase()!=="a")return;const ue=Y.current?.getSelection()?.trim();ue&&(oe.preventDefault(),Ke(ue))};return window.addEventListener("keydown",we),()=>window.removeEventListener("keydown",we)},[s.kind,i,Ke]);const mt=w.useCallback(de=>{if(!de.text.trim()||!i)return;const we=re.current?.querySelector("iframe")?.getBoundingClientRect(),oe=(we?.left??0)+de.rect.x+de.rect.width/2,st=(we?.top??0)+de.rect.y;W({x:oe,y:st,text:de.text,htmlMeta:{xpath:de.xpath,cssSelector:de.cssSelector}})},[i]);w.useEffect(()=>{const de=re.current;if(!de||!i)return;const we=()=>{requestAnimationFrame(()=>{const st=window.getSelection(),ue=st?.toString().trim();if(!ue||!st?.rangeCount){W(null);return}const Le=st.getRangeAt(0);if(!de.contains(Le.commonAncestorContainer)){W(null);return}const ke=Le.getBoundingClientRect();W({x:ke.left+ke.width/2,y:ke.top,text:ue})})},oe=st=>{const ue=document.getElementById("right-panel-selection-toolbar");ue&&ue.contains(st.target)||W(null)};return de.addEventListener("mouseup",we),document.addEventListener("mousedown",oe),()=>{de.removeEventListener("mouseup",we),document.removeEventListener("mousedown",oe)}},[i,x.mode]);const _t=()=>{ne.files.reveal(Fe||De).catch(()=>{})},Xt=()=>{navigator.clipboard?.writeText(Fe||De).then(()=>{_(!0),setTimeout(()=>_(!1),1500)}).catch(()=>{})},dt=w.useMemo(()=>{if(!i)return null;const de=Fe||De;if(s.kind==="deliverable"){const we=s.deliverable;if(!we.id&&!we.reference)return null;const oe=Te||we.title||we.reference||we.id;return{kind:"deliverable",label:`📄 ${oe.length>40?`${oe.slice(0,24)}…${oe.slice(-12)}`:oe}`,content:["[deliverable]",we.id?`ID: ${we.id}`:"",we.title?`Title: ${we.title}`:"",we.reference?`Reference: ${we.reference}`:"",we.taskId?`Task: ${we.taskId}`:"",we.projectId?`Project: ${we.projectId}`:""].filter(Boolean).join(`
61
61
  `)}}if(s.kind==="file"){if(!de||go(de))return null;const we=Te||de.split(/[/\\]/).pop()||de;return{kind:"file",label:`📄 ${we.length>40?`${we.slice(0,24)}…${we.slice(-12)}`:we}`,content:["[file]",`Path: ${de}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
62
62
  `)}}return null},[i,s,Fe,De,Te,x]),[Dt,Me]=w.useState(!1),jt=w.useCallback(()=>{dt&&(i?.(dt),Me(!0),setTimeout(()=>Me(!1),1200))},[dt,i]),ye=w.useCallback(async()=>{if(s.kind==="deliverable"){gr.navigate(Ut.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let we=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const oe=await window.markusDesktop.browser.getState(s.browserId);if(oe.ok){if(oe.directoryPath){await ne.system.openPath(oe.directoryPath).catch(()=>ne.files.reveal(oe.directoryPath));return}oe.url&&oe.url!=="about:blank"&&(we=oe.url)}}catch{}if(!we||we==="about:blank")return;if(/^https?:\/\//i.test(we)||/^file:\/\//i.test(we)){fc(we);return}await ne.system.openPath(we).catch(()=>fc(jv(we)));return}if(s.kind!=="file")return;const de=s.path;if(de){if(/^https?:\/\//i.test(de)||/^file:\/\//i.test(de)){fc(de);return}await ne.system.openPath(de).catch(()=>fc(jv(de)))}},[s]),ze=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,Ie=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),ce=!!De&&!go(De)&&(s.kind==="file"||s.kind==="deliverable"),et=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!De&&!go(De)&&!s.deliverable.artifactType&&R2(s.deliverable.format),xe=s.kind==="deliverable"?{...s.deliverable,hubShareId:A?.id??s.deliverable.hubShareId??null,shareStatus:A?.status??s.deliverable.shareStatus??null,shareUrl:A?.url??s.deliverable.shareUrl??null,shareVisibility:A?.visibility??s.deliverable.shareVisibility??null}:null,gt=w.useCallback(de=>{N(de)},[]),He=w.useMemo(()=>E2(LO,ap.getUrl()),[]),Ct=s.kind==="deliverable"?s.deliverable.id:null;w.useEffect(()=>{if(!Ct||!LO())return;let de=!1;const we=async()=>{try{const st=await He.listMine();if(de)return;const ue=s.kind==="deliverable"?s.deliverable:null;if(!ue)return;const Le=ue.hubShareId&&st.find(Ye=>Ye.id===ue.hubShareId)||st.find(Ye=>Ye.localId===ue.id);if(!Le)return;N(Ye=>Ye&&Ye.id===Le.id&&Ye.status===Le.status?Ye:Le);const ke={hubShareId:ue.hubShareId??Le.id??null,shareStatus:Le.status??null,shareUrl:Le.url??null,shareVisibility:ue.shareVisibility??Le.visibility??null};(ue.shareStatus!==ke.shareStatus||ue.hubShareId!==ke.hubShareId||ue.shareUrl!==ke.shareUrl||ue.shareVisibility!==ke.shareVisibility)&&ue.id&&ne.deliverables.update(ue.id,ke).catch(Ye=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",Ye)})}catch{}};we();const oe=setInterval(we,3e4);return()=>{de=!0,clearInterval(oe)}},[He,Ct,s]);const vt=xe?.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"})]})})]}),Ue||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:U,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 we=de.currentTarget;we.scrollWidth<=we.clientWidth||Math.abs(de.deltaY)<=Math.abs(de.deltaX)||(we.scrollLeft+=de.deltaY,de.preventDefault())},children:[n?.map(de=>{const we=de.id===a,oe=de.payload.kind==="url"?de.payload.pageId:void 0,st=de.payload.kind==="terminal"?de.payload.terminalId:void 0,ue=oe!=null?H[oe]:st?B[st]:void 0,Le=ue?`${de.title} — ${m("common:browserTabControlledBy",{name:ue.agentName})}`:de.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${we?ue?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":ue?"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":we,ref:we?te: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:Le,onPointerDown:ke=>{ke.button===0&&(de.id!==a&&!_e()||o?.(de.id))},onClick:()=>{de.id!==a&&!_e()||o?.(de.id)},children:[ue&&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:ue.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:ue.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:de.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:ke=>{ke.button===0&&(ke.preventDefault(),ke.stopPropagation(),!(de.id===a&&!_e())&&l(de.id))},onClick:ke=>{ke.preventDefault(),ke.stopPropagation(),!(de.id===a&&!_e())&&l(de.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${we?"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(uI,{scrollRef:U,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:De||Te,children:Te}),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:M,className:"relative shrink-0",children:[c.jsx("button",{type:"button",onClick:()=>q(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(q_,{items:ie,query:"",activeIndex:-1,onHover:()=>{},onPick:de=>{q(!1),z_(de,{openPanel:$e?.openRightPanel})},onRemove:de=>pe(ey(op(de))),onClear:()=>{Jv(),q(!1)},anchorClassName:"right-0 top-full mt-1 w-72",keyboardHint:!1})]}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{ft()},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"})})}),dt&&c.jsx("button",{type:"button",onClick:jt,title:Dt?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 ${Dt?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:Dt?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"})]})}),et&&c.jsxs("button",{type:"button",onClick:()=>E(!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 ${vt==="published"?"text-green-500 hover:text-green-400":vt==="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"})]}),(vt==="published"||vt==="pending_review"||vt==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${vt==="published"?"bg-green-500":vt==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),ze&&c.jsx("button",{type:"button",onClick:()=>{ye()},title:Ie,"aria-label":Ie,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"})]})}),ce&&c.jsx("button",{onClick:Xt,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"})]})}),ce&&c.jsx("button",{onClick:_t,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:()=>{_e()&&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(bI(Fe)),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"})}),m("deliverables:detail.backToParentFolder")]})}),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?` · ${$f(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?` · ${$f(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?` · ${$f(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{ne.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:re,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(_C,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{ne.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const de=De?De.replace(/[/\\][^/\\]+$/,""):void 0,we=De&&!go(De)?De:"",oe=x.format;return we&&(oe==="code"||oe==="json"||oe==="text")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(N_,{path:we,initialContent:x.content,language:xg(we,oe),onDirtyChange:I})}):we&&(oe==="markdown"||oe==="html")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(WD,{path:we,content:x.content,format:oe,basePath:de,onHtmlSelection:mt,onDirtyChange:I,copyVariant:"preview"})}):c.jsx("div",{ref:re,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(Bf,{content:x.content,format:oe,className:"text-fg-secondary text-sm",onHtmlSelection:mt,basePath:de,copyVariant:"preview"})})})(),x.mode==="artifact"&&c.jsx("div",{ref:re,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(Bf,{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(JD,{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(cI,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:Y,onMeta:b,onOpenUrl:O,onOpenPath:g,onSelection:de=>{if(!de||!i){W(null);return}W({x:de.x,y:de.y,text:de.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(kC,{path:x.path,entries:x.entries,onNavigate:de=>C(de),onOpenFile:de=>C(de),onReveal:_t,onCopyPath:Xt}),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:_t,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:_t,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:Xt,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"})})]})]})]},ve)]}),R&&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:R.x,top:R.y-8},children:c.jsxs("button",{onMouseDown:de=>{de.preventDefault(),de.stopPropagation(),Ke(R.text,R.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"})]})}),Q&&xe&&c.jsx(A2,{item:xe,onClose:()=>E(!1),onShared:gt})]})}function yI({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=Tt(["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(Is,{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 SI={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},wI={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 _I({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 kI({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:O}=Tt(["team","common"]),g=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{g.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:g,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 ${wI[k.field]}`,children:b(SI[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(_I,{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:cp(k.createdAt,O.language),children:lp(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 CI=300,PI=48;function TI(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 QI(s,e,t,r=PI){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 $I(s,e,t={}){const r=t.limit??CI,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 TI(o)){const u=h.toLocaleLowerCase();let d=0;for(;;){const f=u.indexOf(i,d);if(f===-1)break;const p=QI(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 jI(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 RI(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 O=b[0],g=Date.parse(O.createdAt);if(Number.isFinite(a)&&Number.isFinite(g)&&g<a)break;l=O.createdAt}return{found:d,messages:o,hasMore:h,oldestCursor:f(),exhausted:u}}const EI="markus.scrollDebug";let jf=null,Rv=!1;function AI(){if(!Rv){try{jf=typeof localStorage<"u"&&localStorage.getItem(EI)==="1"}catch{jf=!1}Rv=!0}return jf===!0}function Xi(s,e){AI()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}const Ev={urgent:0,high:1,normal:2,low:3};function Av(s){return Ev[s??"normal"]??Ev.normal}function MI(s){return[...s].sort((e,t)=>{const r=Av(e.priority)-Av(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function LI(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Gm(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 NI(s,e){return e?MI(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&LI(t)===e)):[]}const Mv={sessionId:null,messageId:null};function DI(s){if(s.length===0)return Mv;const e=new Set(s.map(Gm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Gm(n)))return Mv;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 F_={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"},external_signal:{icon:"📡",category:"notification"}};function zc(s){return s?F_[s]?.icon??"●":"●"}["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries(F_).filter(([,t])=>t.category===e).map(([t])=>t),s),{});const II=Object.freeze([{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:"bounced",dot:"bg-red-500"},{key:"catch_all",dot:"bg-red-700"}]);function Rf(s){return!s||s==="all"?void 0:s}const BI=[{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","bind_address","address_revoke","address_list","message_route","catch_all","external_source_register","external_source_list","external_source_toggle","rest","list_waits","cancel_wait"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide","fact_"]},{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:["work_status","discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval","org_info","org_list","org_usage"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function WI(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of BI){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 XI(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function zI({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const qI=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function Lv(s){if(!s)return null;for(const e of qI){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const U_=16;function ZI(s,e,t=U_){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 VI(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 H_(s,e={}){const{enabled:t=!0,deps:r=[]}=e,[i,n]=w.useState(mu()),[a,o]=w.useState(0),l=w.useRef(s);l.current=s;const h=JSON.stringify(r);w.useEffect(()=>{if(!t){n(mu());return}let d=!1;return n(mu()),(async()=>{const f=await CC(()=>l.current());d||n(f)})(),()=>{d=!0}},[t,h,a]);const u=w.useCallback(()=>o(d=>d+1),[]);return{resource:i,view:PC(i),reload:u}}const FI=w.lazy(()=>ry(()=>import("./MarkdownMessage-CaLBeMto.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),Ef=new Map,Af=new Map,Y_=s=>{s.size>4e3&&s.clear()},UI=s=>{if(!s)return"";const e=Ef.get(s);if(e!==void 0)return e;Y_(Ef);const t=new Date(s).toLocaleString();return Ef.set(s,t),t},HI=s=>{if(!s)return"";const e=Af.get(s);if(e!==void 0)return e;Y_(Af);const t=new Date(s).toLocaleTimeString();return Af.set(s,t),t},dh={mind:"run",files:"settings",tools:"settings",memory:"memory"},bg=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function YI(s,e){const{labelKey:t}=vl(s);return t?e(t):s}function Km(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Nv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:u}=Tt(["agent","common"]),d=rp(),[f,p]=w.useState(null),[v,b]=w.useState(null),[O,g]=w.useState(r??"overview"),m=o&&l?l:O,[x,y]=w.useState(null),k=w.useMemo(()=>bg.map(Z=>({...Z,label:u(`agent:tabs.${Z.key}`)})),[u]),C=w.useMemo(()=>k.map(Z=>({id:Z.key})),[k]),P=w.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=TC(C,O,g,P),Q=w.useRef(null);w.useEffect(()=>{const Z=Q.current;if(!Z)return;Z.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[O]);const E=w.useCallback(()=>{ne.agents.get(s).then(p).catch(()=>{})},[s]);if(w.useEffect(()=>(g(r??"overview"),y(null),E(),ne.externalAgents.list().then(B=>{const K=B.agents.find($=>$.markusAgentId===s);y(K??null)}).catch(()=>{}),Rt.on("agent:update",B=>{B.payload.agentId===s&&E()})),[s,E]),!f)return c.jsx(ay,{label:u("agent:profilePage.loadingAgent")});const A=vl(f.state.status).dotClass,N=a?.role==="owner"||a?.role==="admin",R=Z=>h??dh[Z],W=Z=>x||dh[Z]?"overview":Z,H=dh[O];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[W(m)==="overview"&&c.jsx(Dv,{agent:f,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:R(m)}),W(m)==="deliverables"&&c.jsx(qv,{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(Is,{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 ${A}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:YI(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:()=>gr.navigate(Ut.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:Z}=await ne.agents.getFilesMap(s),B={type:"agent",name:ty(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 ap.publishViaProxy({itemType:"agent",name:f.name,description:B.description,category:"general",config:B,files:Z}),b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(Z){b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishFailed",{error:String(Z)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title: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:Q,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(Z=>!x||Z.key==="overview").map(Z=>c.jsxs("button",{onClick:()=>g(Z.key),"data-active":O===Z.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${O===Z.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:Z.icon}),Z.label]},Z.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?_.onTouchStart:void 0,onTouchEnd:d?_.onTouchEnd:void 0,children:[W(O)==="overview"&&c.jsx(Dv,{agent:f,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:h??H}),W(O)==="deliverables"&&c.jsx(qv,{agentId:s})]}),v&&c.jsx(qo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function GI({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:dp.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 qc({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function Dv({agent:s,externalInfo:e,t,canManageAgents:r,highlightMailboxId:i,initialSection:n}){const[a,o]=w.useState(null),[l,h]=w.useState([]),[u,d]=w.useState(null),[f,p]=w.useState(null),[v,b]=w.useState(""),[O,g]=w.useState([]),[m,x]=w.useState(0),[y,k]=w.useState(!1),[C,P]=w.useState(!1),[_,Q]=w.useState(()=>y0(n,i));w.useEffect(()=>{Q(y0(n,i))},[n,i]);const E=(s.state.activeTaskIds??[]).join(",");w.useEffect(()=>{ne.usage.agents().then($=>{const I=$.agents.find(X=>X.agentId===s.id);I&&o(I)}).catch(()=>{}),s.state.activeTaskIds?.length&&ne.tasks.list({assignedAgentId:s.id}).then($=>{g($.tasks.filter(I=>s.state.activeTaskIds?.includes(I.id)))}).catch(()=>{}),ne.agents.getMailbox(s.id,{limit:1}).then($=>{x($.queued?.length??0)}).catch(()=>{})},[s.id,E,s.state.status]);const A=w.useCallback(async()=>{if(!y){k(!0);try{const $=await ne.agents.storage(s.id);b($.dataDir),p({size:$.size,subItems:$.subItems??[],depthLimited:$.depthLimited})}catch{}finally{k(!1)}}},[s.id,y]);w.useEffect(()=>{if(_!=="run")return;let $=!1;return P(!0),ne.agents.getActivities(s.id,{limit:FP}).then(I=>{$||h(I.activities)}).catch(()=>{}).finally(()=>{$||P(!1)}),()=>{$=!0}},[_,s.id]);const N=w.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:t("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:t("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:t("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:t("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:t("agent:profilePage.gateway.requirements")}],[t]),R=w.useMemo(()=>[{field:"assignedTasks",desc:t("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:t("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:t("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:t("agent:profilePage.syncContext.projectContext")}],[t]);if(e)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(pr,{title:t("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ls,{label:t("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?t("agent:profilePage.roles.managerDisplay"):t("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():t("agent:profilePage.emDash")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(di,{label:t("agent:profilePage.overview.labels.connection"),value:QC(e.connected?"online":"offline",t),color:e.connected?"green":"gray"}),c.jsx(di,{label:t("agent:profilePage.overview.labels.platform"),value:t("agent:profilePage.overview.openClaw")}),c.jsx(di,{label:t("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.lastSync"),value:e.lastHeartbeat?new Date(e.lastHeartbeat).toLocaleTimeString():t("agent:profilePage.never")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ls,{label:t("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:e.externalAgentId}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.registered"),children:new Date(e.registeredAt).toLocaleString()}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.capabilities"),children:e.capabilities.length>0?e.capabilities.join(", "):t("agent:profilePage.overview.noneDeclared")}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.lastHeartbeat"),children:e.lastHeartbeat?new Date(e.lastHeartbeat).toLocaleString():t("agent:profilePage.never")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:R.map($=>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:$.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:$.desc})]},$.field))})}),c.jsx(pr,{title:t("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:N.map($=>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 ${$.method==="POST"?"text-amber-600":"text-green-600"}`,children:$.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:$.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:$.desc})]},$.path))})})]});const{heartbeats:W,comms:H}=UP(l),Z=v0(W),B=v0(H),K=s.state.activeTaskIds?.length??0;return[l.length>0?t("agent:profilePage.overview.recentWindow",{count:l.length}):null,Z.total>0?t("agent:profilePage.overview.heartbeatRuns",{count:Z.total}):null,B.total>0?t("agent:profilePage.overview.a2aRuns",{count:B.total}):null].filter(Boolean).join(" · "),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(Ls,{label:t("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?t("agent:profilePage.roles.managerDisplay"):t("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Ls,{label:t("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:t("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:t("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:t("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.tokensToday"),children:Km(XP(a,s.state.tokensUsedToday))}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():t("agent:profilePage.emDash")})]}),(s.state.status==="error"||s.state.status==="working"&&(K>0||m>0||s.runtime?.activityLabel))&&c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[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:t("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:c.jsx(ny,{text:fh(s.state.lastError,t)||s.state.lastError||t("agent:profilePage.overview.errorFallback")})})]}),s.state.status==="working"&&(K>0||m>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($=>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:$.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Df($.status,t,$.blockedReason)})]},$.id)),m>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:t("agent:profilePage.overview.mailboxQueued",{count:m})})]})]})})]}),c.jsx(GI,{section:_,onChange:Q,t}),_==="settings"&&c.jsx(qc,{children:c.jsx(t3,{agentId:s.id})}),_==="settings"&&c.jsx(qc,{children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.lifetimeCaption")}),a?c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(di,{label:t("agent:profilePage.overview.labels.totalTokens"),value:Km(a.totalTokens)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.requests"),value:String(a.requestCount)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.toolCalls"),value:String(a.toolCalls)})]}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.overview.sections.usage.empty")})]}),c.jsxs("div",{className:"border-t border-border-subtle pt-2 space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageLabel","磁盘占用")}),f?c.jsxs(c.Fragment,{children:[c.jsx(di,{label:t("agent:profilePage.overview.storage"),value:Mf(f.size)}),pc(f.subItems).slice(0,4).map($=>{const I=qP($.name);return c.jsx(di,{label:I?t(I):$.name,value:Mf($.size)},$.name)}),pc(f.subItems).length>4&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageMore",{count:pc(f.subItems).length-4,size:Mf(pc(f.subItems).slice(4).reduce(($,I)=>$+I.size,0))})}),c.jsxs("button",{onClick:()=>{ne.system.openPath(v)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary",children:[t("agent:profilePage.overview.openFolder")," →"]})]}):c.jsx("button",{onClick:()=>{A()},disabled:y,className:"text-[11px] px-2 py-1 rounded border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40 disabled:opacity-50",children:y?t("agent:profilePage.overview.storageLoading","读取中…"):t("agent:profilePage.overview.storageScanBtn","查看磁盘占用")})]}),f?.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageDepthLimited")})]}),c.jsxs("div",{className:"border-t border-border-subtle pt-2 space-y-1",children:[c.jsx("button",{type:"button",onClick:()=>gr.navigate(Ut.TEAM,{agentId:s.id,preferMain:"1",prefillMessage:t("agent:profilePage.overview.cleanupPrefill",{name:s.name,defaultValue:`请检查你自己的数据(工作区、日志、会话历史、记忆归档),列出一份「可以安全清理」的清单与理由。
63
+ `)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function QI(s,e,t,r=PI){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 $I(s,e,t={}){const r=t.limit??CI,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 TI(o)){const u=h.toLocaleLowerCase();let d=0;for(;;){const f=u.indexOf(i,d);if(f===-1)break;const p=QI(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 jI(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 RI(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 O=b[0],g=Date.parse(O.createdAt);if(Number.isFinite(a)&&Number.isFinite(g)&&g<a)break;l=O.createdAt}return{found:d,messages:o,hasMore:h,oldestCursor:f(),exhausted:u}}const EI="markus.scrollDebug";let jf=null,Rv=!1;function AI(){if(!Rv){try{jf=typeof localStorage<"u"&&localStorage.getItem(EI)==="1"}catch{jf=!1}Rv=!0}return jf===!0}function Xi(s,e){AI()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}const Ev={urgent:0,high:1,normal:2,low:3};function Av(s){return Ev[s??"normal"]??Ev.normal}function MI(s){return[...s].sort((e,t)=>{const r=Av(e.priority)-Av(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function LI(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Gm(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 NI(s,e){return e?MI(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&LI(t)===e)):[]}const Mv={sessionId:null,messageId:null};function DI(s){if(s.length===0)return Mv;const e=new Set(s.map(Gm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Gm(n)))return Mv;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 F_={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"},external_signal:{icon:"📡",category:"notification"}};function zc(s){return s?F_[s]?.icon??"●":"●"}["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries(F_).filter(([,t])=>t.category===e).map(([t])=>t),s),{});const II=Object.freeze([{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:"bounced",dot:"bg-red-500"},{key:"catch_all",dot:"bg-red-700"}]);function Rf(s){return!s||s==="all"?void 0:s}const BI=[{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","bind_address","address_revoke","address_list","message_route","catch_all","external_source_register","external_source_list","external_source_toggle","rest","list_waits","cancel_wait"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide","fact_"]},{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:["work_status","discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval","org_info","org_list","org_usage"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function WI(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of BI){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 XI(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function zI({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const qI=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function Lv(s){if(!s)return null;for(const e of qI){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const U_=16;function ZI(s,e,t=U_){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 VI(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 H_(s,e={}){const{enabled:t=!0,deps:r=[]}=e,[i,n]=w.useState(mu()),[a,o]=w.useState(0),l=w.useRef(s);l.current=s;const h=JSON.stringify(r);w.useEffect(()=>{if(!t){n(mu());return}let d=!1;return n(mu()),(async()=>{const f=await CC(()=>l.current());d||n(f)})(),()=>{d=!0}},[t,h,a]);const u=w.useCallback(()=>o(d=>d+1),[]);return{resource:i,view:PC(i),reload:u}}const FI=w.lazy(()=>ry(()=>import("./MarkdownMessage-B-9NMrYX.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),Ef=new Map,Af=new Map,Y_=s=>{s.size>4e3&&s.clear()},UI=s=>{if(!s)return"";const e=Ef.get(s);if(e!==void 0)return e;Y_(Ef);const t=new Date(s).toLocaleString();return Ef.set(s,t),t},HI=s=>{if(!s)return"";const e=Af.get(s);if(e!==void 0)return e;Y_(Af);const t=new Date(s).toLocaleTimeString();return Af.set(s,t),t},dh={mind:"run",files:"settings",tools:"settings",memory:"memory"},bg=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function YI(s,e){const{labelKey:t}=vl(s);return t?e(t):s}function Km(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function Nv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:u}=Tt(["agent","common"]),d=rp(),[f,p]=w.useState(null),[v,b]=w.useState(null),[O,g]=w.useState(r??"overview"),m=o&&l?l:O,[x,y]=w.useState(null),k=w.useMemo(()=>bg.map(Z=>({...Z,label:u(`agent:tabs.${Z.key}`)})),[u]),C=w.useMemo(()=>k.map(Z=>({id:Z.key})),[k]),P=w.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=TC(C,O,g,P),Q=w.useRef(null);w.useEffect(()=>{const Z=Q.current;if(!Z)return;Z.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[O]);const E=w.useCallback(()=>{ne.agents.get(s).then(p).catch(()=>{})},[s]);if(w.useEffect(()=>(g(r??"overview"),y(null),E(),ne.externalAgents.list().then(B=>{const K=B.agents.find($=>$.markusAgentId===s);y(K??null)}).catch(()=>{}),Rt.on("agent:update",B=>{B.payload.agentId===s&&E()})),[s,E]),!f)return c.jsx(ay,{label:u("agent:profilePage.loadingAgent")});const A=vl(f.state.status).dotClass,N=a?.role==="owner"||a?.role==="admin",R=Z=>h??dh[Z],W=Z=>x||dh[Z]?"overview":Z,H=dh[O];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[W(m)==="overview"&&c.jsx(Dv,{agent:f,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:R(m)}),W(m)==="deliverables"&&c.jsx(qv,{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(Is,{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 ${A}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:YI(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:()=>gr.navigate(Ut.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:Z}=await ne.agents.getFilesMap(s),B={type:"agent",name:ty(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 ap.publishViaProxy({itemType:"agent",name:f.name,description:B.description,category:"general",config:B,files:Z}),b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(Z){b({title:u("agent:profilePage.hub"),message:u("agent:profilePage.publishFailed",{error:String(Z)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title: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:Q,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(Z=>!x||Z.key==="overview").map(Z=>c.jsxs("button",{onClick:()=>g(Z.key),"data-active":O===Z.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${O===Z.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:Z.icon}),Z.label]},Z.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:d?_.onTouchStart:void 0,onTouchEnd:d?_.onTouchEnd:void 0,children:[W(O)==="overview"&&c.jsx(Dv,{agent:f,externalInfo:x,t:u,canManageAgents:N,highlightMailboxId:n,initialSection:h??H}),W(O)==="deliverables"&&c.jsx(qv,{agentId:s})]}),v&&c.jsx(qo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function GI({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:dp.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 qc({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function Dv({agent:s,externalInfo:e,t,canManageAgents:r,highlightMailboxId:i,initialSection:n}){const[a,o]=w.useState(null),[l,h]=w.useState([]),[u,d]=w.useState(null),[f,p]=w.useState(null),[v,b]=w.useState(""),[O,g]=w.useState([]),[m,x]=w.useState(0),[y,k]=w.useState(!1),[C,P]=w.useState(!1),[_,Q]=w.useState(()=>y0(n,i));w.useEffect(()=>{Q(y0(n,i))},[n,i]);const E=(s.state.activeTaskIds??[]).join(",");w.useEffect(()=>{ne.usage.agents().then($=>{const I=$.agents.find(X=>X.agentId===s.id);I&&o(I)}).catch(()=>{}),s.state.activeTaskIds?.length&&ne.tasks.list({assignedAgentId:s.id}).then($=>{g($.tasks.filter(I=>s.state.activeTaskIds?.includes(I.id)))}).catch(()=>{}),ne.agents.getMailbox(s.id,{limit:1}).then($=>{x($.queued?.length??0)}).catch(()=>{})},[s.id,E,s.state.status]);const A=w.useCallback(async()=>{if(!y){k(!0);try{const $=await ne.agents.storage(s.id);b($.dataDir),p({size:$.size,subItems:$.subItems??[],depthLimited:$.depthLimited})}catch{}finally{k(!1)}}},[s.id,y]);w.useEffect(()=>{if(_!=="run")return;let $=!1;return P(!0),ne.agents.getActivities(s.id,{limit:FP}).then(I=>{$||h(I.activities)}).catch(()=>{}).finally(()=>{$||P(!1)}),()=>{$=!0}},[_,s.id]);const N=w.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:t("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:t("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:t("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:t("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:t("agent:profilePage.gateway.requirements")}],[t]),R=w.useMemo(()=>[{field:"assignedTasks",desc:t("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:t("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:t("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:t("agent:profilePage.syncContext.projectContext")}],[t]);if(e)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(pr,{title:t("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ls,{label:t("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?t("agent:profilePage.roles.managerDisplay"):t("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():t("agent:profilePage.emDash")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(di,{label:t("agent:profilePage.overview.labels.connection"),value:QC(e.connected?"online":"offline",t),color:e.connected?"green":"gray"}),c.jsx(di,{label:t("agent:profilePage.overview.labels.platform"),value:t("agent:profilePage.overview.openClaw")}),c.jsx(di,{label:t("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.lastSync"),value:e.lastHeartbeat?new Date(e.lastHeartbeat).toLocaleTimeString():t("agent:profilePage.never")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(Ls,{label:t("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:e.externalAgentId}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.registered"),children:new Date(e.registeredAt).toLocaleString()}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.capabilities"),children:e.capabilities.length>0?e.capabilities.join(", "):t("agent:profilePage.overview.noneDeclared")}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.lastHeartbeat"),children:e.lastHeartbeat?new Date(e.lastHeartbeat).toLocaleString():t("agent:profilePage.never")})]})}),c.jsx(pr,{title:t("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:R.map($=>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:$.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:$.desc})]},$.field))})}),c.jsx(pr,{title:t("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:N.map($=>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 ${$.method==="POST"?"text-amber-600":"text-green-600"}`,children:$.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:$.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:$.desc})]},$.path))})})]});const{heartbeats:W,comms:H}=UP(l),Z=v0(W),B=v0(H),K=s.state.activeTaskIds?.length??0;return[l.length>0?t("agent:profilePage.overview.recentWindow",{count:l.length}):null,Z.total>0?t("agent:profilePage.overview.heartbeatRuns",{count:Z.total}):null,B.total>0?t("agent:profilePage.overview.a2aRuns",{count:B.total}):null].filter(Boolean).join(" · "),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(Ls,{label:t("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?t("agent:profilePage.roles.managerDisplay"):t("agent:profilePage.roles.workerDisplay")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(Ls,{label:t("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:t("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:t("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:t("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.tokensToday"),children:Km(XP(a,s.state.tokensUsedToday))}),c.jsx(Ls,{label:t("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():t("agent:profilePage.emDash")})]}),(s.state.status==="error"||s.state.status==="working"&&(K>0||m>0||s.runtime?.activityLabel))&&c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[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:t("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:c.jsx(ny,{text:fh(s.state.lastError,t)||s.state.lastError||t("agent:profilePage.overview.errorFallback")})})]}),s.state.status==="working"&&(K>0||m>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($=>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:$.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Df($.status,t,$.blockedReason)})]},$.id)),m>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:t("agent:profilePage.overview.mailboxQueued",{count:m})})]})]})})]}),c.jsx(GI,{section:_,onChange:Q,t}),_==="settings"&&c.jsx(qc,{children:c.jsx(t3,{agentId:s.id})}),_==="settings"&&c.jsx(qc,{children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.lifetimeCaption")}),a?c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(di,{label:t("agent:profilePage.overview.labels.totalTokens"),value:Km(a.totalTokens)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.requests"),value:String(a.requestCount)}),c.jsx(di,{label:t("agent:profilePage.overview.labels.toolCalls"),value:String(a.toolCalls)})]}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.overview.sections.usage.empty")})]}),c.jsxs("div",{className:"border-t border-border-subtle pt-2 space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageLabel","磁盘占用")}),f?c.jsxs(c.Fragment,{children:[c.jsx(di,{label:t("agent:profilePage.overview.storage"),value:Mf(f.size)}),pc(f.subItems).slice(0,4).map($=>{const I=qP($.name);return c.jsx(di,{label:I?t(I):$.name,value:Mf($.size)},$.name)}),pc(f.subItems).length>4&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageMore",{count:pc(f.subItems).length-4,size:Mf(pc(f.subItems).slice(4).reduce(($,I)=>$+I.size,0))})}),c.jsxs("button",{onClick:()=>{ne.system.openPath(v)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary",children:[t("agent:profilePage.overview.openFolder")," →"]})]}):c.jsx("button",{onClick:()=>{A()},disabled:y,className:"text-[11px] px-2 py-1 rounded border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40 disabled:opacity-50",children:y?t("agent:profilePage.overview.storageLoading","读取中…"):t("agent:profilePage.overview.storageScanBtn","查看磁盘占用")})]}),f?.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.storageDepthLimited")})]}),c.jsxs("div",{className:"border-t border-border-subtle pt-2 space-y-1",children:[c.jsx("button",{type:"button",onClick:()=>gr.navigate(Ut.TEAM,{agentId:s.id,preferMain:"1",prefillMessage:t("agent:profilePage.overview.cleanupPrefill",{name:s.name,defaultValue:`请检查你自己的数据(工作区、日志、会话历史、记忆归档),列出一份「可以安全清理」的清单与理由。
64
64
  不确定的项先问我,不要自行删除;我确认后你再动手。`})}),className:"text-[11px] px-2 py-1 rounded border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40",children:t("agent:profilePage.overview.cleanupCta","让 Agent 清理数据")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.overview.cleanupHint","会在聊天里预填指令,发送与否由你决定;Agent 拿不准时会先问你。")})]})]})}),_==="run"&&c.jsx(qc,{children:c.jsx(p3,{agentId:s.id,highlightId:i,agentStatus:s.state.status,canManageAgents:r})}),_==="settings"&&c.jsxs("details",{className:"mt-4 border border-border-default rounded-xl bg-surface-elevated/30",children:[c.jsx("summary",{className:"cursor-pointer px-4 py-3 text-xs font-medium text-fg-secondary select-none",children:t("agent:profilePage.overview.capabilityCollapsed","能力(工具与技能)— 点开查看")}),c.jsx("div",{className:"px-4 pb-4",children:c.jsx(o3,{tools:s.tools??[],agent:s})})]}),_==="memory"&&c.jsx(qc,{children:c.jsx(a3,{agentId:s.id})})]})}function KI(s,e){const t=s.split(`
65
65
  `),r=e.split(`
66
66
  `),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 Iv(s){return s.match(/\S+|\s+/g)??[""]}function Bv({oldText:s,newText:e,mode:t}){const r=Iv(s),i=Iv(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 JI({agent:s,template:e,templateId:t}){const{t:r}=Tt(["agent","common"]),i=w.useMemo(()=>KI(s,e),[s,e]),[n,a]=w.useState(!0),o=3,l=w.useMemo(()=>{const p=i.map((g,m)=>g.type!=="equal"?m:-1).filter(g=>g>=0);if(p.length===0)return[];const v=[];let b=Math.max(0,p[0]-o),O=Math.min(i.length-1,p[0]+o);for(let g=1;g<p.length;g++){const m=Math.max(0,p[g]-o),x=Math.min(i.length-1,p[g]+o);m<=O+1||(v.push({start:b,end:O}),b=m),O=x}return v.push({start:b,end:O}),v},[i]),h=(p,v,b)=>{const O=p.type==="add"?"+":p.type==="remove"?"-":" ",g=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(Bv,{oldText:p.content,newText:b[v+1].content,mode:"remove"}):p.type==="add"&&v>0&&b[v-1].type==="remove"&&(k=c.jsx(Bv,{oldText:b[v-1].content,newText:p.content,mode:"add"})),c.jsxs("div",{className:`flex ${g} 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:O}),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,O=n&&b&&p._idx-b._idx>1;return c.jsxs("div",{children:[O&&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 e3(s,e){const t=s.split(`
@@ -85,7 +85,7 @@ ${de}
85
85
  @2xl:static @2xl:z-auto @2xl:w-auto @2xl:max-w-none @2xl:translate-x-0 @2xl:overflow-y-auto
86
86
  @2xl:bg-transparent @2xl:border-0 @2xl:shadow-none @2xl:p-0
87
87
  @2xl:flex-1 @2xl:min-w-0 @2xl:max-h-[30rem] space-y-1
88
- `,children:[c.jsxs("div",{className:"@2xl:hidden sticky top-0 z-10 -mx-3 mb-2 px-3 py-2 bg-surface-primary border-b border-border-default flex items-center gap-2",children:[c.jsx("span",{className:"text-[11px] font-medium text-fg-secondary truncate flex-1",children:ze?.name||(ze?.key?S0(ze.key):"")}),c.jsx("button",{onClick:()=>V(!1),className:"text-fg-tertiary hover:text-fg-primary text-sm px-1","aria-label":i("common:close"),children:"✕"})]}),(()=>{const ce=Ie.flatMap(xe=>xe.decisions??[]);if(ce.length===0)return null;const et=new Map;for(const xe of ce){const gt=et.get(xe.decisionType);gt?gt.push(xe):et.set(xe.decisionType,[xe])}return c.jsxs("div",{className:"mb-2 rounded-lg border border-border-subtle bg-surface-elevated/40 px-2 py-1.5",children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-tertiary mb-1",children:i("agent:profilePage.mind.roundDecisions","本轮决策")}),c.jsx("div",{className:"space-y-0.5",children:[...et.entries()].map(([xe,gt])=>c.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]",children:[c.jsx("span",{className:"shrink-0 font-medium text-fg-primary",children:xe}),c.jsxs("span",{className:"shrink-0 tabular-nums text-fg-tertiary",children:["×",gt.length]}),c.jsx("span",{className:"truncate text-fg-secondary",title:gt[0]?.reasoning??"",children:gt[0]?.reasoning??""})]},xe))})]})})(),Ie.length===0&&X.length>0&&c.jsx("p",{className:"text-xs text-fg-tertiary py-6 text-center",children:ze&&ze.key.startsWith("channel:loop_")?i("agent:profilePage.mind.loopIdle","这段时间没有需要它判断的信号 —— 它在睡或已完成处置"):i("agent:profilePage.mind.unitEmpty","这个实体目前没有记录")}),Ie.map(ce=>{const et=k===ce.id,xe=zc(ce.sourceType),gt=zv(ce,i),He=zI({itemStatus:ce.status,agentRunning:dt,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:ce.id}),Ct=ce.metadata?.senderName,vt=ce.metadata?.senderRole,de=P===ce.id;return c.jsxs("div",{id:`mbx-${ce.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${de?"border-brand-500 ring-1 ring-brand-500/40":ce.status==="bounced"||ce.status==="catch_all"?"border-border-subtle border-l-2 border-l-red-500":"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:()=>{const we=et?null:ce.id;C(we),we&&ce.contentTruncated&&!Xe[we]&&ft(we)},children:[c.jsx("span",{className:"hidden @sm:inline text-xs mt-0.5 text-fg-tertiary",children:et?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${He==="stale"?"bg-amber-400/70":f3[ce.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:xe}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:`text-xs font-medium text-fg-primary break-words ${et?"":"truncate"}`,children:gt.title}),gt.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 break-words ${et?"":"truncate"}`,children:gt.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap items-center",children:[c.jsx("span",{children:UI(ce.queuedAt)}),ce.completedAt&&c.jsxs("span",{children:["→ ",HI(ce.completedAt)]}),ce.activity&&c.jsxs(c.Fragment,{children:[ce.activity.totalTokens>0&&c.jsx("span",{className:"hidden @sm:inline",children:i("agent:profilePage.mind.tokensCount",{count:Km(ce.activity.totalTokens)})}),ce.activity.totalTools>0&&c.jsx("span",{className:"hidden @sm:inline",children:i("agent:profilePage.mind.toolsCount",{count:ce.activity.totalTools})})]}),gt.badge&&c.jsx("span",{className:`font-medium ${gt.badge.color}`,children:gt.badge.label}),c.jsx("span",{className:Xv[ce.priority]??"text-fg-tertiary",children:i(`agent:profilePage.mind.priority.${Wv[ce.priority]??ce.priority}`,{defaultValue:""})})]})]}),r&&XI({agentRunning:dt,itemId:ce.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:ce.status})&&c.jsxs("button",{onClick:we=>{we.stopPropagation(),W(ce.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")]})]}),et&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:c.jsx("span",{className:"bg-surface-overlay px-1.5 py-0.5 rounded",children:ce.sourceType})}),Ct&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Ct}),vt&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",vt,")"]})]}),["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(ce.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:Xe[ce.id]??ce.payload?.content??c.jsx("span",{className:"text-fg-tertiary",children:i("agent:profilePage.mind.loadingContent","正在载入完整正文…")})}),ce.decisions&&ce.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:ce.decisions.map(we=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${h3[we.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:we.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:we.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(we.createdAt).toLocaleTimeString()})]},we.id))})]}),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:U===ce.id,onClick:()=>{_e(ce.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")})})]}),ce.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:ce.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${ce.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:ce.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),ce.activity.type==="task"&&ce.payload?.taskId?c.jsx(l3,{taskId:ce.payload.taskId,isLive:qO(ce.activity,te)}):c.jsx(c3,{agentId:s,activityId:ce.activity.id,isLive:qO(ce.activity,te)})]}):He==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):He==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):ce.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},ce.id)}),Ie.length>Fe&&c.jsx("button",{onClick:()=>Ue(ce=>ce+Te),className:"w-full text-center text-[11px] text-brand-400 hover:text-brand-300 py-2",children:i("agent:profilePage.mind.showMoreCount",{count:Ie.length-Fe})})]})]})})})()]}),R&&c.jsx(qo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const ye=R;W(null),ne.agents.cancelProcessing(s,{itemId:ye}).then(()=>{let ze=0;const Ie=()=>{ze+=1,me(),ze<8&&window.setTimeout(Ie,750)};Ie()}).catch(()=>{me()})},onCancel:()=>W(null)})]})}function qv({agentId:s}){const{t:e}=Tt(["agent","common"]),t=zo(),r=H_(()=>ne.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(GP(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:l});return}gr.navigate(Ut.DELIVERABLES,{openDeliverable:l.id})},[t]);return w.useEffect(()=>{const l=Rt.on("deliverable:created",()=>a()),h=Rt.on("deliverable:updated",()=>a()),u=Rt.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(sy,{variant:"inline",subject:e("common:deliverables"),error:r.resource.error??e("common:readFailed"),notEquals:e("agent:profilePage.noDeliverables"),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=$C[l.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=NO[l.status]??NO.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 g3=w.lazy(()=>ry(()=>import("./MarkdownMessage-CaLBeMto.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),vg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Zv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Vv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Tt(["team","common","work","agent"]),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState(!0),[p,v]=w.useState(null),[b,O]=w.useState("overview"),g=r&&i?i:b,[m,x]=w.useState(""),[y,k]=w.useState(""),[C,P]=w.useState(!1),[_,Q]=w.useState(!1),[E,A]=w.useState(""),[N,R]=w.useState(""),W=w.useRef(null),H=w.useRef(null),Z=w.useRef(null),B=w.useRef(null),[K,$]=w.useState(!1),[I,X]=w.useState(!1),[q,ie]=w.useState(""),[pe,$e]=w.useState(""),[re,U]=w.useState(!1),[M,te]=w.useState([]),Y=w.useRef(null),ae=w.useCallback(async()=>{try{const Xe=(await ne.teams.list()).teams.find(ft=>ft.id===s);Xe&&l(Xe);const Ke=await ne.teams.status(s);te(Ke.agents)}catch{}finally{u(!1)}},[s]),ee=w.useCallback(async()=>{f(!0);try{const V=await ne.teams.getFile(s,"ANNOUNCEMENT.md");x(V.content)}catch{x("")}try{const V=await ne.teams.getFile(s,"NORMS.md");k(V.content)}catch{k("")}finally{f(!1)}},[s]);w.useEffect(()=>{O("overview"),ae(),ee()},[s,ae,ee]),w.useEffect(()=>{C&&H.current&&H.current.focus()},[C]),w.useEffect(()=>{_&&B.current&&B.current.focus()},[_]);const me=async(V,Xe)=>{$(!0);try{await ne.teams.updateFile(s,V,Xe),V==="ANNOUNCEMENT.md"?(x(Xe),P(!1)):(k(Xe),Q(!1))}catch{}$(!1)},Re=async()=>{q.trim()&&(await ne.teams.update(s,{name:q.trim()}),X(!1),ae())},_e=async()=>{await ne.teams.update(s,{description:pe}),U(!1),ae()};if(!o)return h?c.jsx(ay,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(w2,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const De=o.members.find(V=>V.agentRole==="manager"),Te=M.filter(V=>V.status!=="offline").length,Fe=V=>{const{labelKey:Xe}=vl(V);return Xe?a(Xe):V??"offline"},Ue=g==="announcements"&&C||g==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ue?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ue?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="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:a("agent:profilePage.badges.manager")}),c.jsx("div",{className:"text-sm font-medium",children:De?.name??o.managerName??a("common: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:a("team:teamProfile.teamId")}),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:a("team:page.members")}),o.members.map(V=>{const Xe=M.find(mt=>mt.id===V.id),Ke=Zv[Xe?.status??"offline"]??"bg-gray-500",ft=V.type==="agent";return c.jsxs("div",{onClick:()=>ft&&n?.(V.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ft&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Is,{name:V.name,avatarUrl:V.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:V.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Fe(Xe?.status)}),V.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:a("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[V.role," · ",V.type]})]}),ft&&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"})})]},V.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("team:teamProfile.noMembers")})]})]}),g==="announcements"&&c.jsx(Zc,{content:m,draft:E,setDraft:A,editing:C,setEditing:P,textareaRef:H,contentRef:W,saving:K,onSave:()=>me("ANNOUNCEMENT.md",E),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),g==="norms"&&c.jsx(Zc,{content:y,draft:N,setDraft:R,editing:_,setEditing:Q,textareaRef:B,contentRef:Z,saving:K,onSave:()=>me("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),g==="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:a("team:modals.createTeam.teamName")}),I?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:q,onChange:V=>ie(V.target.value),onKeyDown:V=>V.key==="Enter"&&Re(),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:Re,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common: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:a("common:cancel")})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{ie(o.name),X(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:a("work:project.description")}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:pe,onChange:V=>$e(V.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:_e,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common:save")}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:a("common:cancel")})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||a("work:task.noDescription")}),c.jsx("button",{onClick:()=>{$e(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]})]}),c.jsx(Fv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ve=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ve?"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.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:a("common:units.members",{count:o.members.length})}),c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:a("team:teamProfile.onlineCount",{count:Te})})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||a("work:task.noDescription")})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:V}=await ne.teams.getFilesMap(o.id),Xe=o.members.filter(ft=>ft.type==="agent"),Ke={type:"team",name:ty(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Xe.map(ft=>({name:ft.name,roleName:ft.role,role:ft.agentRole??"worker",count:1,skills:[]}))}};await ap.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ke,files:V}),v({title:"Hub",message:a("agent:profilePage.publishSuccess",{name:o.name}),variant:"primary"})}catch(V){v({title:"Hub",message:a("agent:profilePage.publishFailed",{error:String(V)}),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:a("common:publishToHub"),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:vg.map(V=>c.jsxs("button",{onClick:()=>O(V.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===V.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[V.icon," ",a(V.labelKey)]},V.key))})]}),c.jsxs("div",{className:`${ve?"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:a("agent:profilePage.badges.manager")}),c.jsx("div",{className:"text-sm font-medium",children:De?.name??o.managerName??a("common: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:a("team:teamProfile.teamId")}),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:a("team:page.members")}),o.members.map(V=>{const Xe=M.find(mt=>mt.id===V.id),Ke=Zv[Xe?.status??"offline"]??"bg-gray-500",ft=V.type==="agent";return c.jsxs("div",{onClick:()=>ft&&n?.(V.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ft&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Is,{name:V.name,avatarUrl:V.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:V.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Fe(Xe?.status)}),V.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:a("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[V.role," · ",V.type]})]}),ft&&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"})})]},V.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(Zc,{content:m,draft:E,setDraft:A,editing:C,setEditing:P,textareaRef:H,contentRef:W,saving:K,onSave:()=>me("ANNOUNCEMENT.md",E),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),b==="norms"&&c.jsx(Zc,{content:y,draft:N,setDraft:R,editing:_,setEditing:Q,textareaRef:B,contentRef:Z,saving:K,onSave:()=>me("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:a("team:modals.createTeam.teamName")}),I?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:q,onChange:V=>ie(V.target.value),onKeyDown:V=>V.key==="Enter"&&Re(),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:Re,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common: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:a("common:cancel")})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{ie(o.name),X(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:a("work:project.description")}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:pe,onChange:V=>$e(V.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:_e,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common:save")}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:a("common:cancel")})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||a("work:task.noDescription")}),c.jsx("button",{onClick:()=>{$e(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]})]}),c.jsx(Fv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(qo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Zc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:u,loading:d}){const{t:f}=Tt(["common"]);return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:p=>t(p.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:p=>{p.key==="Escape"&&(p.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:f("common: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:p=>{p.key==="Enter"&&(t(s),i(!0))},children:d&&!s.trim()?c.jsx(ly,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:f("common:loading")}),children:c.jsx(g3,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:u})})}function Fv({teamId:s,teamName:e,onDeleted:t}){const{t:r}=Tt(["team","common","work"]),[i,n]=w.useState(!1),[a,o]=w.useState(!1),[l,h]=w.useState(!1),[u,d]=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:r("work:project.dangerZone")}),i?c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:r("team:teamProfile.deleteTeamConfirm",{name:e})}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:f=>h(f.target.checked),className:"rounded"}),r("team:modals.deleteTeam.deleteMembers")]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:a,onChange:f=>o(f.target.checked),className:"rounded"}),r("team:modals.deleteTeam.purgeFiles")]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:u,onClick:async()=>{d(!0);try{await ne.teams.delete(s,l,{purgeFiles:a}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:r(u?"common:deleting":"common:confirmDelete")}),c.jsx("button",{onClick:()=>n(!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:r("common:cancel")})]})]}):c.jsx("button",{onClick:()=>n(!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:r("team:contextMenu.deleteTeam")})]})}const O3=["chat","overview","deliverables"],x3=["chat","overview","announcements","norms","settings"];function b3(s,e){if(s==="chat")return e("page.chatTitle");if(bg.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=vg.find(i=>i.key===s);return r?e(r.labelKey):s}function v3(s){if(s==="chat")return"💬";const e=bg.find(r=>r.key===s);if(e)return e.icon;const t=vg.find(r=>r.key===s);return t?t.icon:""}function zi(s){return s!=="chat"}function Aa(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Jm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Ns{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.isStreamLiveForSession(e,Ns.NEW_CHAT_ID)||(this.buffers.delete(Ns.NEW_CHAT_ID),this.windowBounds.delete(Ns.NEW_CHAT_ID),this.actBuffers.delete(Ns.NEW_CHAT_ID),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>Ns.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(!Jm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Ns.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Ns.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(Ns.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Jm(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(Ns.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}protectedBufferIds(){const e=new Set(this.view.values());e.add(this.viewBufferId());for(const t of this.streamingSessions.values())for(const r of t)e.add(r);for(const[t,r]of this.phase)r==="streaming"&&!this.streamingSessions.get(t)?.size&&(e.add(Ns.NEW_CHAT_ID),e.add(this.view.get(t)??t));return e}evictIfNeeded(e){if(this.buffers.size<=Ns.MAX_BUFFERS)return;const t=this.protectedBufferIds();t.add(e);for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Ns.MAX_BUFFERS)break;t.has(r)||(this.deleteBuffer(r),this.actBuffers.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>Ns.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(this.protectedBufferIds().has(r)){this.bufferOrder.push(r);break}this.deleteBuffer(r),this.actBuffers.delete(r)}}}const lt=Ns.NEW_CHAT_ID;function y3(s){const e=w.useRef(new Ns),[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(E=>E+1),[]),d=w.useCallback(E=>e.current.getStreamSessions(E),[]),f=w.useCallback((E,A)=>{e.current.addStreamSession(E,A)&&u()},[u]),p=w.useCallback((E,A)=>{e.current.removeStreamSession(E,A)&&u()},[u]),v=w.useCallback((E,A)=>e.current.setActiveSession(E,A),[]),b=w.useCallback(E=>e.current.clearActiveSession(E),[]);w.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const O=w.useCallback((E,A,N)=>{const R=e.current.updateMessages(E,A,N);R.displayChanged&&R.newMessages&&r(R.newMessages)},[]),g=w.useCallback((E,A,N)=>{e.current.updateMessages(E,A,N).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const W=e.current.getMessages(E);W&&e.current.currentConvKey===E&&r([...W])}))},[]),m=w.useCallback((E,A,N)=>{const R=e.current.appendActivity(E,A,N);R.displayChanged&&R.newActivities&&o(R.newActivities)},[]),x=w.useCallback(E=>e.current.getPhase(E),[]),y=w.useCallback(E=>e.current.beginLoad(E),[]),k=w.useCallback(E=>{e.current.beginStream(E)},[]),C=w.useCallback(E=>{e.current.endStream(E)},[]),P=w.useCallback((E,A)=>{e.current.abortStream(E,A)&&u(),e.current.currentConvKey===E&&(n(!1),o([]))},[u]),_=w.useCallback((E,A)=>{e.current.resetConv(E,A)},[]),Q=w.useCallback(async(E,A,N)=>{e.current.loadingSession=E,e.current.beginLoad(A);try{const R=await N(),W=e.current.applyLoadResult(A,E,R.messages);return W.displayChanged&&W.newMessages&&r(W.newMessages),{count:R.messages.length,hasMore:R.hasMore,oldestCursor:R.oldestCursor}}catch{return e.current.currentConvKey===A&&e.current.getPhase(A)!=="streaming"&&(r([]),e.current.completeLoad(A)),{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(E){e.current.currentConvKey=E}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(E){e.current.loadingSession=E}}},updateConvMsgs:O,updateConvMsgsRaf:g,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:Q,setActiveSession:v,clearActiveSession:b,incrementSending:E=>e.current.incrementSend(E),decrementSending:E=>e.current.decrementSend(E),resetSending:E=>e.current.resetSend(E),isSendingFor:E=>e.current.isSending(E),setStreamSession:f,clearStreamSession:p,getStreamSession:d,saveSessionToCache:(E,A)=>e.current.saveToCache(),restoreSessionFromCache:(E,A)=>{const N=e.current.restoreFromCache(E,A);return r(N??[]),N},readConvMsgs:E=>e.current.getMessages(E),readSessionMsgs:E=>e.current.buffers.get(E),writeConvMsgs:(E,A)=>{const N=e.current.updateMessages(E,()=>A);N.displayChanged&&N.newMessages&&r(N.newMessages)}}}function Nf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function Uv(){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 S3(s){const e=w.useRef(new Map),t=w.useRef(new Map),r=Ue=>{if(Ue)for(const[ve,V]of e.current)V===Ue&&e.current.delete(ve)},i=Ue=>{if(Ue)for(const[ve,V]of t.current)V===Ue&&t.current.delete(ve)},n=Ue=>{const ve=e.current.get(Ue);ve&&(ve.abort(),e.current.delete(Ue));const V=t.current.get(Ue);V&&(V.abort(),t.current.delete(Ue))},a=Ue=>{const ve=e.current.get(lt);ve&&e.current.size===1&&(e.current.delete(lt),e.current.set(Ue,ve))},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,readSessionMsgs:O,currentConvKeyRef:g,updateConvMsgs:m,updateConvMsgsRaf:x,appendConvActivity:y,beginStream:k,endStream:C,abortStream:P,clearStreamSession:_,setStreamSession:Q,getStreamSession:E,setActiveSession:A,incrementSending:N,decrementSending:R,loadAndDisplay:W,sessionSwitchSeqRef:H,setSending:Z,setActivities:B,setInput:K,setChatContext:$,setPendingImages:I,setMentionDropdown:X,setChatReplyTo:q,setActiveSessionId:ie,setStoredActiveSession:pe,setOpenSessionTabs:$e,setSessions:re,setLoadingChat:U,setWindowBounds:M,makeConvKey:te,makeDmChannel:Y,addRecentMsgId:ae,resumeChatScrollFollow:ee,loadSessions:me}=s,{t:Re}=s,_e=w.useCallback(async(Ue,ve)=>{const V=H.current,Xe=g.current===ve&&(b(ve)?.length??0)===0;Xe&&U(!0);try{const{count:Ke,hasMore:ft,oldestCursor:mt}=await W(Ue,ve,async()=>{const _t=await ne.sessions.getMessages(Ue,50);return{messages:_t.messages.map(mh).filter(dt=>dt.sender!=="agent"||dt.text||dt.segments&&dt.segments.length>0||dt.isStreaming),hasMore:_t.hasMore,oldestCursor:_t.messages[0]?new Date(_t.messages[0].createdAt).toISOString():null}});return M(Ue,{hasMore:ft,oldestCursor:mt}),Ke}finally{Xe&&g.current===ve&&H.current===V&&U(!1)}},[W,b,H]),De=()=>{const Ue=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ue){const ve=Nf(f.current.activeSessionId,lt);ve.kind==="cancel"&&ne.agents.cancelProcessing(Ue,ve.target).catch(()=>{})}n(f.current.activeSessionId??lt),Ue&&f.current.activeSessionId&&f.current.activeSessionId!==lt&&l.current.add(f.current.activeSessionId),P(g.current,f.current.activeSessionId)},Te=w.useCallback(async(Ue,ve,V)=>{if(!Ue||!ve||ve===lt||l.current.has(ve))return;let Xe=null;try{const Ke=e.current.get(ve);if(Ke&&!Ke.signal.aborted&&E(V)?.has(ve)){g.current===V&&Z(!0);return}const ft=()=>{KC({liveSessions:E(V),sessionId:ve,placeholderId:lt})&&(_(V,ve),g.current===V&&(Z(!1),m(V,ue=>gu(ue),ve)))},mt=`${Ue}:${ve}`,_t=o.current.get(mt)??0;if(Date.now()-_t<1500)return;o.current.set(mt,Date.now());let Xt;const dt=await ne.sessions.streamStatus(Ue,ve);dt.messageId&&(Xt=dt.messageId);const Dt=O(ve)??[],Me=dt.status==="streaming",jt=JC(Dt,{expectedMessageId:dt.messageId,allowCurrentTurnPartial:Me}),ye=!!dt.active&&(dt.status==="done"||dt.status==="error")&&!!jt?.isStreaming;if(O0({aborted:!1,sawTerminal:ye,serverStatus:x0(dt.status)})==="finalize"){ft();return}o.current.set(mt,Date.now());for(const ue of t.current.values())ue.abort();t.current.clear(),Xe=new AbortController,t.current.set(ve,Xe),k(V),Z(!0),Q(V,ve);const Ie=jt&&!jt.isError&&jt.sender==="agent"?Dt.findIndex(ue=>ue.id===jt.id):-1,ce=Ie>=0?Dt[Ie]:void 0,et=e2(dt);if(!ce&&!et){ft();return}const xe=ce?ce.id:et;if(!ce)m(V,ue=>[...ue,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ve);else{const ue=(ce.segments??[]).filter(Le=>Le.type==="tool").map(Le=>Le.status==="stopped"||Le.status==="running"?{...Le,status:"running"}:Le);m(V,Le=>Le.map(ke=>ke.id===xe?{...ke,text:"",isStreaming:!0,isStopped:!1,segments:ue,committedSegments:void 0}:ke),ve)}const gt=ue=>{g.current===V&&(d.current=Date.now(),x(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(J=>J.id===xe):-1,Ye=nt>=0?nt:ke.map((J,je)=>({m:J,j:je})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];return ke[Ye]={...Je,text:(Je.text??"")+ue,segments:ZO(Je.segments??[],ue),isStreaming:!0},ke},ve))},He=ue=>{g.current===V&&(d.current=Date.now(),x(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(J=>J.id===xe):-1,Ye=nt>=0?nt:ke.map((J,je)=>({m:J,j:je})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];return ke[Ye]={...Je,segments:VO(Je.segments??[],ue),isStreaming:!0},ke},ve))},Ct=ue=>{if(g.current===V&&(d.current=Date.now(),ue.phase!=="heartbeat")){if((ue.phase==="start"||ue.phase==="end")&&y(V,{...ue,phase:ue.phase,ts:Date.now()},ve),ue.phase==="start"){const Le=`${ue.tool}_${Date.now()}`,ke=new Date().toISOString(),nt=Ye=>{const Je=[...Ye];for(let J=Je.length-1;J>=0;J--){const je=Je[J];if(je.type==="tool"&&je.tool===ue.tool&&(je.status==="running"||je.status==="stopped"))return Je[J]={...je,status:"running",args:ue.arguments??je.args},Je}return Je.push({type:"tool",key:Le,tool:ue.tool,status:"running",args:ue.arguments,createdAt:ke}),Je};m(V,Ye=>{const Je=[...Ye],J=xe?Je.findIndex(Pe=>Pe.id===xe):-1;if(J<0)return Ye;const je=nt(Je[J].segments??[]),Qe=Je[J].committedSegments,be=Qe&&nt(Qe);return Je[J]={...Je[J],segments:je,committedSegments:be,isStreaming:!0},Je},ve)}else if(ue.phase==="end"){const Le=new Date().toISOString(),ke=nt=>{const Ye=[...nt];for(let Je=Ye.length-1;Je>=0;Je--){const J=Ye[Je];if(J.type==="tool"&&J.tool===ue.tool&&(J.status==="running"||J.status==="stopped")){Ye[Je]={...J,status:ue.success===!1?"error":"done",args:ue.arguments??J.args,result:ue.result,error:ue.error,durationMs:ue.durationMs,liveOutput:void 0,createdAt:Le};break}}return Ye};m(V,nt=>{const Ye=[...nt],Je=xe?Ye.findIndex(be=>be.id===xe):-1;if(Je<0)return nt;const J=ke(Ye[Je].segments??[]),je=Ye[Je].committedSegments,Qe=je&&ke(je);return Ye[Je]={...Ye[Je],segments:J,committedSegments:Qe,isStreaming:!0},Ye},ve)}else if(ue.phase==="subagent_progress"&&ue.subagentEvent){const Le=ke=>{const nt=[...ke];for(let Ye=nt.length-1;Ye>=0;Ye--){const Je=nt[Ye];if(Je.type==="tool"&&(Je.tool==="spawn_subagent"||Je.tool==="spawn_subagents")&&(Je.status==="running"||Je.status==="stopped")){nt[Ye]={...Je,status:"running",subagentLogs:FO(Je.subagentLogs,ue.subagentEvent)};break}}return nt};x(V,ke=>{const nt=[...ke],Ye=xe?nt.findIndex(Qe=>Qe.id===xe):-1;if(Ye<0)return ke;const Je=Le(nt[Ye].segments??[]),J=nt[Ye].committedSegments,je=J&&Le(J);return nt[Ye]={...nt[Ye],segments:Je,committedSegments:je,isStreaming:!0},nt},ve)}}},vt=ue=>{g.current===V&&(d.current=Date.now(),m(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(Je=>Je.id===xe):-1;if(nt<0)return Le;const Ye=[...ke[nt].committedSegments??[]];if(ue.type==="thinking_commit")Ye.push({type:"text",content:"",thinking:ue.content,createdAt:ue.createdAt});else if(ue.type==="text_commit")Ye.push({type:"text",content:ue.content,createdAt:ue.createdAt});else return Le;return ke[nt]={...ke[nt],committedSegments:Ye,isStreaming:!0},ke},ve))},de=ue=>{if(g.current!==V)return;d.current=Date.now();const Le=(ue.segments??[]).map((ke,nt)=>ke.type==="tool"?{type:"tool",key:`${ke.tool}_${nt}`,tool:ke.tool??"tool",status:ke.status==="error"?"error":ke.status==="running"||ke.status==="stopped"?"running":"done",args:ke.arguments,result:ke.result,error:ke.error,durationMs:ke.durationMs,createdAt:ke.createdAt,...ke.subagentLogs?.length?{subagentLogs:ke.subagentLogs}:{}}:{type:"text",content:ke.content??"",thinking:ke.thinking,createdAt:ke.createdAt});m(V,ke=>{const nt=[...ke],Ye=xe?nt.findIndex(Je=>Je.id===xe):-1;return Ye<0?ke:(nt[Ye]={...nt[Ye],text:ue.content||nt[Ye].text,segments:Le,committedSegments:Le,isStreaming:!0,isStopped:!1},nt)},ve);for(const ke of Le)ke.type==="tool"&&y(V,{tool:ke.tool,phase:ke.status==="running"||ke.status==="stopped"?"start":"end",success:ke.status!=="error",arguments:ke.args,result:ke.result,error:ke.error,durationMs:ke.durationMs,ts:Date.now()},ve)},we=8;let oe=null;const st=ue=>{g.current===V&&m(V,Le=>{const ke=Le.map((Ye,Je)=>({m:Ye,j:Je})).reverse().find(Ye=>Ye.m.sender==="agent"&&Ye.m.isStreaming)?.j??-1;if(ke<0||Le[ke].reconnecting===ue)return Le;const nt=[...Le];return nt[ke]={...nt[ke],reconnecting:ue},nt},ve)};for(let ue=1;ue<=we;ue++){if(Xe.signal.aborted)return;try{oe=await ne.sessions.reattachStream(Ue,ve,{onChunk:gt,onThinking:He,onActivity:Ct,onCommit:vt,onSnapshot:de},Xe.signal,0)}catch(ke){if(Xe.signal.aborted)throw ke;oe=null}if(!oe||!oe.attached){oe=null;break}if(oe.terminal)break;st(!0);const Le=await ne.sessions.streamStatus(Ue,ve).catch(()=>null);if(Le?.messageId&&(Xt=Le.messageId),!Le||!Le.active||Le.status==="not_found"||Le.status==="idle"){st(!1),oe=null;break}await new Promise(ke=>setTimeout(ke,Math.min(800*ue,4e3))),st(!1)}if(!oe){C(V),_(V,ve),g.current===V&&(Z(!1),Xt&&xe&&m(V,ue=>_a(ue,xe,Xt),ve),_e(ve,V).catch(()=>{}).finally(()=>{m(V,ue=>gu(ue,"done"),ve)})),i(Xe);return}if(g.current===V){let ue;m(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(je=>je.id===xe):-1,Ye=nt>=0?nt:ke.map((je,Qe)=>({m:je,j:Qe})).reverse().find(je=>je.m.sender==="agent"&&je.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];if(!Je.isStreaming)return Le;ue=Je.id;const J=oe.segments?.length?UO(oe.segments,Je.segments):void 0;return ke[Ye]={...Je,text:oe.content||Je.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...J?{segments:J,committedSegments:J}:{}},ke},ve),ue&&m(V,Le=>_a(Le,ue,oe.messageId),ve),Z(!1)}C(V),_(V,ve),i(Xe)}catch(Ke){const ft=Xe?[...t.current.values()].includes(Xe):!1;i(Xe),C(V);const mt=l.current.has(ve);if(mt&&_(V,ve),g.current===V&&(Z(!1),ft&&mt&&m(V,_t=>gu(_t),ve)),Ke instanceof Error&&Ke.name==="AbortError")return}},[y,k,C,E,b,Q,m,x]),Fe=w.useCallback(async(Ue,ve)=>{const V=f.current,Xe=rP({text:V.input,chips:V.chatContext??[]}),Ke=Ue?Ue.trim():Xe.text,ft=Ue?Ue.trim():Xe.titleSource,mt=Ue?void 0:Xe.chips.length>0?Xe.chips:void 0;if(!Ke&&V.pendingImages.length===0||V.chatMode==="direct"&&!V.selectedAgent)return;ee();const _t=Date.now(),Xt=h.current;if(!ve?.isRetry&&!ve?.isResume&&Ke&&Xt&&Xt.text===Ke&&_t-Xt.at<1500)return;if(h.current={text:Ke,at:_t},ve?.isResume){const Ie=ve.sessionIdOverride??V.activeSessionId??"";if(_t-(u.current.get(Ie)??0)<2e3)return;u.current.set(Ie,_t)}if(V.chatMode==="direct"){if(t2({authorityStreaming:Cs.isServerConfirmedStreaming(V.activeSessionId),sendSessionId:V.activeSessionId})){const ce=g.current;if([...b(ce)??[]].reverse().find(He=>He.sender==="user")?.text===Ke&&!ve?.isRetry&&!ve?.isResume){n(V.activeSessionId??lt);const He=Nf(V.activeSessionId,lt);return He.kind==="cancel"&&ne.agents.cancelProcessing(V.selectedAgent,He.target).catch(()=>{}),P(ce,V.activeSessionId),m(ce,Ct=>{const vt=[...Ct];return vt.length>0&&vt[vt.length-1].sender==="agent"&&vt.pop(),vt.length>0&&vt[vt.length-1].sender==="user"&&vt[vt.length-1].text===Ke&&vt.pop(),vt}),await new Promise(Ct=>setTimeout(Ct,50)),Fe(Ke,{isRetry:!0})}n(V.activeSessionId??lt);const gt=Nf(V.activeSessionId,lt);gt.kind==="cancel"&&ne.agents.cancelProcessing(V.selectedAgent,gt.target).catch(()=>{}),P(ce,V.activeSessionId),m(ce,He=>HO(He)),await new Promise(He=>setTimeout(He,50))}}else if(V.sending){n(f.current.activeSessionId??g.current);const Ie=g.current;P(Ie),m(Ie,ce=>HO(ce)),await new Promise(ce=>setTimeout(ce,50))}const dt=V.pendingImages.length>0?V.pendingImages.map(Ie=>Ie.dataUrl):void 0,Dt=V.pendingImages.length>0?V.pendingImages.map(Ie=>Ie.name):void 0,Me=te(V.chatMode,V.selectedAgent??"",V.activeChannel??"",V.activeDmUserId),jt=V.chatReplyTo;Ue||(K(""),$([])),I([]),X(!1),q(null);const ye=V.chatMode==="dm";N(Me);const ze=V.activeSessionId??Me;if(p.set(ze,[]),g.current===Me&&!ye&&(Z(!0),B([])),V.chatMode==="dm"){const Ie=Y(V.authUser?.id??"",V.activeDmUserId),ce=`opt_${Date.now()}`,et={id:ce,sender:"user",text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};dt?.length&&(et.images=dt),jt&&(et.replyToId=jt.id,et.replyToSender=jt.sender,et.replyToText=jt.text),m(Me,xe=>[...xe,et]);try{const xe=await ne.channels.sendMessage(Ie,{text:Ke,senderName:V.authUser?.name??Re("page.fallbackYou"),senderId:V.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...dt?.length?{images:dt}:{},...Dt?.length?{fileNames:Dt}:{}});xe.userMessage&&ae(xe.userMessage.id),m(Me,gt=>{const He=gt.filter(vt=>vt.id!==ce),Ct=[];return xe.userMessage&&Ct.push(Bn(xe.userMessage,V.authUser?.id)),Ct.length>0?[...He,...Ct]:gt})}catch(xe){Vc(xe)&&Fc(),DO(xe)&&(K(Ke),I(V.pendingImages)),m(Me,gt=>[...gt.filter(Ct=>Ct.id!==ce),{id:`err_${Date.now()}`,sender:"agent",text:Re("page.errorWithMessage",{message:String(xe)}),errorRaw:String(xe),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}])}R(Me),g.current===Me&&Z(!1)}else if(V.chatMode==="channel"){const Ie=`opt_${Date.now()}`,ce={id:Ie,sender:"user",text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};jt&&(ce.replyToId=jt.id,ce.replyToSender=jt.sender,ce.replyToText=jt.text),m(Me,xe=>[...xe,ce]);const et=s2(Ke);V.groupChats.find(xe=>xe.channelKey===V.activeChannel);try{const xe=await ne.channels.sendMessage(V.activeChannel,{text:Ke,senderName:V.authUser?.name??Re("page.fallbackYou"),mentions:et,senderId:V.authUser?.id,orgId:"default",replyToId:jt?.id,...dt?.length?{images:dt}:{},...Dt?.length?{fileNames:Dt}:{}});xe.userMessage&&ae(xe.userMessage.id),xe.agentMessage&&ae(xe.agentMessage.id),xe.agentStopped&&m(Me,gt=>[...gt,{id:`stopped_${Date.now()}`,sender:"agent",text:xe.notice??Re("page.agentStopped"),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}]),m(Me,gt=>{const He=gt.filter(vt=>vt.id!==Ie),Ct=[];return xe.userMessage&&Ct.push(Bn(xe.userMessage,V.authUser?.id)),xe.agentMessage&&Ct.push(Bn(xe.agentMessage,V.authUser?.id)),Ct.length>0?[...He,...Ct]:gt})}catch(xe){Vc(xe)&&Fc();const gt=DO(xe);gt&&(K(Ke),I(V.pendingImages));const He=fh(xe,Re)||Re("page.errorWithMessage",{message:String(xe)});m(Me,Ct=>[...gt?Ct.filter(de=>de.id!==Ie):Ct,{id:`err_${Date.now()}`,sender:"agent",text:He,errorRaw:String(xe),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}])}R(Me),g.current===Me&&Z(!1)}else{k(Me);const Ie=ve?.isResume?b(Me)??[]:[],ce=ve?.isResume?r2(Ie):-1,et=ce>=0?Ie[ce].id:void 0,xe=et??Uv(),gt=Uv();let He=ve?.sessionIdOverride??(V.activeSessionId===lt?null:V.activeSessionId??null);if(ve?.isResume){const J=new Date().toISOString();m(Me,je=>{if(et){const Qe=je.findIndex(be=>be.id===et);if(Qe>=0)return je.map((be,Pe)=>Pe===Qe?{...be,isStreaming:!0,isStopped:!1,isError:!1}:be)}return[...je,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:J,segments:[],isStreaming:!0}]},He)}else{const J=new Date().toISOString(),je=i2({id:gt,text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:J,chips:mt,images:dt,replyTo:jt});m(Me,Qe=>[...Qe,je,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:J,segments:[],isStreaming:!0}],He)}const Ct=J=>{d.current=Date.now(),x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=Qe[be];return Qe[be]={...Pe,text:(Pe.text??"")+J,segments:ZO(Pe.segments??[],J)},Qe},He)},vt=J=>{d.current=Date.now(),x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=Qe[be];return Qe[be]={...Pe,segments:VO(Pe.segments??[],J)},Qe},He)},de=J=>{if(d.current=Date.now(),J.type==="session_start"&&J.sessionId){const je=He;if(He=J.sessionId,l.current.delete(J.sessionId),je&&je!==J.sessionId&&(_(Me,je),V.selectedAgent&&je===lt&&(Cs.applyLocalOptimistic(V.selectedAgent,je,!1),Cs.applyLocalOptimistic(V.selectedAgent,J.sessionId,!0))),Q(Me,J.sessionId),J.userMessageId&&!ve?.isResume&&m(Me,Qe=>Qe.map(be=>be.id===gt?{...be,id:J.userMessageId}:be),J.sessionId),g.current===Me){const Qe=V.activeSessionId;(!Qe||Qe===lt||Qe===J.sessionId)&&(ie(J.sessionId),A(Me,J.sessionId),a(J.sessionId),V.selectedAgent&&pe(V.selectedAgent,J.sessionId),$e(be=>be.some(Pe=>Pe.id===lt)?be.map(Pe=>Pe.id===lt?{...Pe,id:J.sessionId}:Pe):be.some(Pe=>Pe.id===J.sessionId)?be:[...be,{id:J.sessionId,agentId:V.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}m(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=[...Qe[be].committedSegments??[]];return J.type==="thinking_commit"?Pe.push({type:"text",content:"",thinking:J.content,createdAt:J.createdAt}):Pe.push({type:"text",content:J.content,createdAt:J.createdAt}),Qe[be]={...Qe[be],committedSegments:Pe},Qe},He)},we=J=>{d.current=Date.now(),J.phase!=="heartbeat"&&((J.phase==="start"||J.phase==="end")&&y(Me,{...J,phase:J.phase,ts:Date.now()},He),J.phase==="start"?m(Me,je=>{const Qe=[...je],be=Qe.findIndex(Ot=>Ot.id===xe);if(be<0)return je;const Pe=[...Qe[be].segments??[]];let tt=!1;if(J.arguments)for(let Ot=Pe.length-1;Ot>=0;Ot--){const At=Pe[Ot];if(At.type==="tool"&&At.tool===J.tool&&At.status==="running"){Pe[Ot]={...At,args:J.arguments},tt=!0;break}}const pt=`${J.tool}_${Date.now()}`,Pt=new Date().toISOString();tt||Pe.push({type:"tool",key:pt,tool:J.tool,status:"running",args:J.arguments,createdAt:Pt});const kt=[...Qe[be].committedSegments??[]];return J.arguments!==void 0&&kt.push({type:"tool",key:pt,tool:J.tool,status:"running",args:J.arguments,createdAt:Pt}),Qe[be]={...Qe[be],segments:Pe,committedSegments:kt},Qe},He):J.phase==="output"?x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=[...Qe[be].segments??[]];for(let tt=Pe.length-1;tt>=0;tt--){const pt=Pe[tt];if(pt.type==="tool"&&pt.tool===J.tool&&pt.status==="running"){Pe[tt]={...pt,liveOutput:a2(pt.liveOutput,J.output??"")};break}}return Qe[be]={...Qe[be],segments:Pe},Qe},He):J.phase==="subagent_progress"&&J.subagentEvent?x(Me,je=>{const Qe=[...je],be=Qe.findIndex(Pt=>Pt.id===xe);if(be<0)return je;const Pe=Pt=>{const kt=[...Pt];for(let Ot=kt.length-1;Ot>=0;Ot--){const At=kt[Ot];if(At.type==="tool"&&(At.tool==="spawn_subagent"||At.tool==="spawn_subagents")&&At.status==="running"){kt[Ot]={...At,subagentLogs:FO(At.subagentLogs,J.subagentEvent)};break}}return kt},tt=Pe(Qe[be].segments??[]),pt=Pe(Qe[be].committedSegments??[]);return Qe[be]={...Qe[be],segments:tt,committedSegments:pt},Qe},He):m(Me,je=>{const Qe=[...je],be=Qe.findIndex(kt=>kt.id===xe);if(be<0)return je;const Pe=new Date().toISOString(),tt=[...Qe[be].segments??[]];let pt;for(let kt=tt.length-1;kt>=0;kt--){const Ot=tt[kt];if(Ot.type==="tool"&&Ot.tool===J.tool&&Ot.status==="running"){pt=Ot.subagentLogs,tt[kt]={...Ot,status:J.success===!1?"error":"done",args:J.arguments,result:J.result,error:J.error,durationMs:J.durationMs,liveOutput:void 0,createdAt:Pe};break}}const Pt=[...Qe[be].committedSegments??[]];for(let kt=Pt.length-1;kt>=0;kt--){const Ot=Pt[kt];if(Ot.type==="tool"&&Ot.tool===J.tool&&Ot.status==="running"){Pt[kt]={...Ot,status:J.success===!1?"error":"done",args:J.arguments,result:J.result,error:J.error,durationMs:J.durationMs,liveOutput:void 0,createdAt:Pe,subagentLogs:pt??Ot.subagentLogs};break}}return Qe[be]={...Qe[be],segments:tt,committedSegments:Pt},Qe},He))},oe=new AbortController;e.current.set(f.current.activeSessionId??lt,oe);const st=He,ue=st;ue&&l.current.delete(ue),ue&&Q(Me,ue),V.selectedAgent&&Cs.applyLocalOptimistic(V.selectedAgent,ue??lt,!0);try{d.current=Date.now();const J=await ne.agents.messageStream(V.selectedAgent,Ke,{onChunk:Ct,onThinking:vt,onActivity:we,onCommit:de},{signal:oe.signal,images:dt,sessionId:st,isRetry:ve?.isRetry,isResume:ve?.isResume,fileNames:Dt,replyTo:jt,titleSource:ft,chips:mt,userMessageId:gt,assistantMessageId:xe});if(g.current===Me){if(J.merged&&m(Me,Qe=>Qe.filter(be=>be.id!==xe&&be.id!==gt),He),!J.merged&&J.segments?.length&&m(Me,Qe=>{const be=[...Qe],Pe=be.findIndex(kt=>kt.id===xe);if(Pe<0)return Qe;const tt=UO(J.segments,be[Pe].segments);let pt=J.content||be[Pe].text;pt||(pt=tt.filter(kt=>kt.type==="text").map(kt=>kt.content).join(""));const Pt=J.emptyReply===!0;return be[Pe]={...be[Pe],text:pt,segments:tt,committedSegments:tt,isStopped:J.cancelled||be[Pe].isStopped,emptyReply:J.emptyReply||Pt||void 0,isError:J.emptyReply||Pt?!0:be[Pe].isError},be},He),!J.merged&&!J.segments?.length&&m(Me,Qe=>{const be=[...Qe],Pe=be.findIndex(At=>At.id===xe);if(Pe<0)return Qe;const tt=be[Pe],pt=tt.committedSegments??[],kt=pt.filter(At=>At.type==="text"&&!!At.content).map(At=>At.content).join("")||J.content||tt.text,Ot=J.emptyReply===!0;return(pt.length>0||kt||J.cancelled||J.emptyReply||Ot)&&(be[Pe]={...tt,text:kt,segments:pt.length>0?pt:tt.segments,isStopped:J.cancelled||tt.isStopped,emptyReply:J.emptyReply||Ot||void 0,isError:J.emptyReply||Ot?!0:tt.isError}),be},He),J.sessionId){ie(be=>!be||be===lt||be===J.sessionId?J.sessionId:be);const Qe=v.get(Me);(!Qe||Qe===lt||Qe===J.sessionId)&&(A(Me,J.sessionId),a(J.sessionId)),$e(be=>be.some(Pe=>Pe.id===lt)?be.map(Pe=>Pe.id===lt?{...Pe,id:J.sessionId}:Pe):be.some(Pe=>Pe.id===J.sessionId)?be:[...be,{id:J.sessionId,agentId:V.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}me(V.selectedAgent).then(Qe=>{if(g.current===Me&&(re(Qe),J.sessionId)){const be=Qe.find(Pe=>Pe.id===J.sessionId);be&&$e(Pe=>Pe.some(pt=>pt.id===be.id)?Pe.map(pt=>pt.id===be.id?be:pt):[be,...Pe.filter(pt=>pt.id!==lt)])}});const je=J.sessionId??(ue&&ue!==lt?ue:null);if(!oe.signal.aborted&&!J.merged&&(J.softDisconnected??J.segments===void 0)&&V.chatMode==="direct"&&V.selectedAgent&&je){const Qe=V.selectedAgent;let be=!1,Pe;for(let tt=0;tt<4&&!be&&(tt>0&&await new Promise(pt=>setTimeout(pt,350*tt)),!oe.signal.aborted);tt+=1)try{const pt=await ne.sessions.streamStatus(Qe,je);if(pt.messageId&&(Pe=pt.messageId),O0({aborted:oe.signal.aborted,sawTerminal:!1,serverStatus:x0(pt.status)})==="reattach"){m(Me,kt=>kt.map(Ot=>Ot.id===xe?{...Ot,isStreaming:!0,isStopped:!1,segments:(Ot.segments??[]).map(At=>At.type==="tool"&&(At.status==="stopped"||At.status==="running")?{...At,status:"running"}:At)}:Ot),je),R(Me),r(oe),Q(Me,je),C(Me),Te(Qe,je,Me),be=!0;return}break}catch{}if(!be&&!oe.signal.aborted){Pe&&xe&&m(Me,tt=>_a(tt,xe,Pe),je);try{if(await _e(je,Me)>0){R(Me),r(oe),C(Me);return}}catch{}}}}!J.merged&&(He||g.current===Me)&&m(Me,je=>_a(je,xe,J.messageId),He)}catch(J){const je=J?.sessionId;je&&V.chatMode==="direct"&&g.current===Me&&(ie(je),A(Me,je),a(je),$e(be=>be.map(Pe=>Pe.id===lt?{...Pe,id:je}:Pe)),me(V.selectedAgent).then(be=>{if(g.current!==Me)return;re(be);const Pe=be.find(tt=>tt.id===je);Pe&&$e(tt=>tt.some(Pt=>Pt.id===Pe.id)?tt.map(Pt=>Pt.id===Pe.id?Pe:Pt):[Pe,...tt])})),Vc(J)&&Fc();const Qe=fh(J,Re);Qe?m(Me,be=>{const Pe=[...be],tt=Pe.findIndex(pt=>pt.id===xe);return tt>=0&&(Pe[tt]={...Pe[tt],text:Qe,isError:!0,errorRaw:String(J)}),Pe},He):m(Me,be=>{const Pe=[...be],tt=Pe.findIndex(pt=>pt.id===xe);if(tt>=0){const pt=YO(Pe[tt],"stopped");if(pt===null)return be.filter(Pt=>Pt.id!==xe);Pe[tt]=pt}return Pe},He)}m(Me,J=>n2(J,xe),He),oe.signal.aborted&&m(Me,J=>{const je=[...J],Qe=je.findIndex(be=>be.id===xe);if(Qe>=0){const be=YO(je[Qe],"stopped");if(be===null)return J.filter(Pe=>Pe.id!==xe);je[Qe]=be}return je},He);const ke=((He?O(He):b(Me))??[]).find(J=>J.id===xe),nt=He&&He!==lt?He:V.activeSessionId&&V.activeSessionId!==lt?V.activeSessionId:null,Ye=ke?o2(ke):!1;ke&&!Ye&&V.chatMode==="direct"&&nt&&!oe.signal.aborted&&await(async(je,Qe)=>{for(let be=0;be<je;be++){const Pe=MC(be,{baseMs:Qe,maxMs:8e3,maxAttempts:je});await new Promise(tt=>setTimeout(tt,Pe));try{const pt=(await ne.sessions.getMessages(nt,2)).messages.find(Pt=>Pt.role==="assistant");if(pt?.content){const Pt=mh(pt);m(Me,kt=>{const Ot=[...kt],At=Ot.findIndex(js=>js.id===xe);return At>=0&&(Ot[At]={...Ot[At],text:Pt.text,segments:Pt.segments}),Ot},He),m(Me,kt=>_a(kt,xe,Pt.id),He);return}}catch{}}})(5,2e3);const Je=R(Me);_(Me,He??lt),V.selectedAgent&&Cs.applyLocalOptimistic(V.selectedAgent,He??lt,!1),C(Me),[...e.current.values()].includes(oe)||e.current.size===0?(r(oe),p.delete(He??Me),g.current===Me&&(Z(Je>0),Je===0&&B([]))):p.delete(He??Me)}},[y,k,_,g,R,C,N,me,b,Z,Q,f,m,x]);return{send:Fe,stopSending:De,tryReattachActiveStream:Te,loadSessionMessages:_e}}function w3({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Tt("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,O]=w.useState(null),g=w.useRef(null),m=w.useCallback(async()=>{f(!0);try{const P=await LC(),_=P.providers?.markus;if(_?.configured&&_.enabled!==!1&&(!_.models||_.models.length===0))try{const A=await fetch("/api/models/live/markus",{credentials:"include"});if(A.ok){const N=await A.json();N.models?.length&&(_.models=N.models)}}catch{}const Q=[];for(const[A,N]of Object.entries(P.providers??{})){if(!N.configured||N.enabled===!1)continue;const R=(N.models??[]).filter(Q2).map(W=>({id:W.id,name:W.name}));R.length!==0&&Q.push({provider:A,displayName:N.displayName??A,models:R})}Q.sort((A,N)=>A.displayName.localeCompare(N.displayName)),v(Q);let E=null;if(P.routingDefaultModel?.provider&&P.routingDefaultModel?.model)E={provider:P.routingDefaultModel.provider,model:P.routingDefaultModel.model};else if(P.defaultProvider){const A=P.providers?.[P.defaultProvider];A?.model&&(E={provider:P.defaultProvider,model:A.model})}O(E)}catch{v([])}finally{f(!1)}},[]);w.useEffect(()=>{m()},[m]),w.useEffect(()=>{n&&(l("agent"),u(""),m())},[n,m]),w.useEffect(()=>{if(!n)return;const P=_=>{g.current?.contains(_.target)||a(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[n]);const x=w.useMemo(()=>{const P=h.trim().toLowerCase();return p.map(_=>({..._,models:P?_.models.filter(Q=>Q.id.toLowerCase().includes(P)||(Q.name?.toLowerCase().includes(P)??!1)||_.displayName.toLowerCase().includes(P)||_.provider.toLowerCase().includes(P)):_.models})).filter(_=>_.models.length>0)},[p,h]),y=s??b,C=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:g,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(P=>!P),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:y?`${y.provider}: ${y.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:C}),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:P=>u(P.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(t0,{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(t0,{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(P=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:P.displayName}),P.models.slice(0,80).map(_=>{const Q=y?.provider===P.provider&&y?.model===_.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:P.provider,model:_.id},o),o==="global"&&O({provider:P.provider,model:_.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 ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:_.id}),Q&&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"})})]},`${P.provider}:${_.id}`)})]},P.provider))]})]})]})}async function Hv(s,e,t){if(e==="agent"){if(!t)return;await ne.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}}),s0(t);return}t&&await ne.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:null}}).then(()=>s0(t)).catch(()=>{}),await ne.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}}),NC()}const Yv="markus_team_sidebars_c";function ep(s,e){return s.id===lt?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Gv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):ep(s,e)}const tp=new Set;function _3(){return window.location.hash}function k3(s){return tp.add(s),()=>{tp.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>tp.forEach(s=>s()));function V3({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Tt(["team","common"]),a=w.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=ip(Ut.TEAM),[l,h]=w.useState(r?.agents??[]),[u,d]=w.useState(r?.humans??[]),[f,p]=w.useState(!r),v=rp(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),O=w.useSyncExternalStore(k3,_3),g=v&&(O.startsWith(`#${Ut.TEAM}/`)||O.startsWith("#chat/")),m=v&&O.match(/^#team\/t\/(.+)$/),x=v?m?"team":g?"chat":"roster":"roster",y=m?m[1]:null;w.useEffect(()=>(IO(v&&x==="chat"),()=>IO(!1)),[v,x]),w.useEffect(()=>(BO(Ut.TEAM,v&&x!=="roster"?1:0),()=>BO(Ut.TEAM,0)),[v,x]);const k=w.useCallback(()=>{window.location.hash=`${Ut.TEAM}/d`},[]),C=w.useCallback(S=>{window.location.hash=`${Ut.TEAM}/t/${S}`},[]);w.useEffect(()=>{if(!v)return;const S=()=>{zi(Q.current)&&_("chat")};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[v]);const[P,_]=w.useState("chat"),Q=w.useRef("chat");Q.current=P;const E=WO({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[A,N]=w.useState(()=>{try{return localStorage.getItem(Yv)==="1"}catch{return!1}}),R=w.useCallback(S=>{N(S);try{localStorage.setItem(Yv,S?"1":"0")}catch{}},[]),W=zo(),H=W?.leftCollapsed??!1,Z=W?.rightPanel??null,B=W?.rightPanelTabs??[],K=W?.activeRightPanelTabId??null,$=W?.rightPanelFullscreen??!1,I=Z?"2xl:pr-8":"2xl:pr-[280px]",X=W?.setHostAvailable,q=W?.collapseRightPanelOnly??W?.toggleRightPanel,ie=W?.openRightPanel,pe=400,$e=320,re=6,[U,M]=w.useState(typeof window<"u"?window.innerWidth:1440),[te,Y]=w.useState("auto"),ae=w.useRef(H);w.useEffect(()=>{ae.current!==H&&(ae.current=H,N(H))},[H]);const ee=W?.keyboardPane??"content",me=w.useRef(!1),Re=w.useRef(ee);w.useEffect(()=>{if(t||v||!o)return;const S=Re.current;Re.current=ee,(ee==="l1"||ee==="l2")&&S!==ee&&A&&(N(!1),W?.setLeftCollapsed(!1))},[ee,t,v,o,A,W]),w.useEffect(()=>{if(t||v||!o)return;const S=T=>{const j=W?.keyboardPane??"content";if(j==="l0"||j==="l1"||j==="l2"||T.metaKey||T.ctrlKey||T.altKey)return;if(T.target instanceof HTMLElement){const F=T.target.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||T.target.isContentEditable||T.target.closest(".xterm"))return}const D=T.key.length===1?T.key.toLowerCase():T.key;D!=="h"&&D!=="ArrowLeft"||(T.preventDefault(),A&&(R(!1),W?.setLeftCollapsed(!1)),W?.setKeyboardPane(me.current?"l2":"l1"))};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,v,o,W,A,R]),w.useEffect(()=>{if(X)return X(o&&!v),()=>X(!1)},[o,v,X]),w.useEffect(()=>t||v||!o?void 0:Rt.on("ui:right_panel",T=>{const j=T.payload;if(j.action==="collapse"){q?.();return}if(j.action!=="open"||!j.panel||!ie)return;const D=j.panel;if(D.kind==="url"&&D.url){const F=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ie({kind:"url",url:D.url,title:D.title||D.url,browserId:F});return}if(D.kind==="file"&&D.path){ie({kind:"file",path:D.path,title:D.title});return}if(D.kind==="terminal"){const F=D.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ie({kind:"terminal",terminalId:F,title:D.title||"Terminal",cwd:D.cwd});return}D.kind==="deliverable"&&D.deliverableId&&ne.deliverables.get(D.deliverableId).then(F=>{F.deliverable&&ie({kind:"deliverable",deliverable:F.deliverable})}).catch(()=>{})}),[t,v,o,q,ie]);const _e=w.useCallback((S,T)=>{const j=pd.current,D=T??Ss.current?.selectionStart??j.text.length,F=hp({text:j.text,chips:j.chips},S,D);ir(F.draft.text),pn(F.draft.chips),requestAnimationFrame(()=>{const G=Ss.current;G&&(G.focus(),G.setSelectionRange(F.caret,F.caret))})},[]),De=w.useCallback(S=>{if(!S)return;let T=0;const j=C2(S,()=>`ctx_${Date.now()}_${++T}`);if(j.length===0)return;const D=pd.current,F=nP({text:D.text,chips:D.chips},j);ir(F.draft.text),pn(F.draft.chips),requestAnimationFrame(()=>{const G=Ss.current;G&&(G.focus(),G.setSelectionRange(F.caret,F.caret))})},[]),Te=w.useRef(null),[Fe,Ue]=w.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ve=WO({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),V=w.useRef(null),[Xe,Ke]=w.useState(!1),[ft,mt]=w.useState(!1),_t=w.useCallback(()=>{Xe?mt(S=>!S):Ue(S=>{const T=!S;try{localStorage.setItem("markus_team_panel_visible",String(T))}catch{}return T})},[Xe]);w.useEffect(()=>{if(v)return;const S=V.current;if(!S)return;const T=new ResizeObserver(([j])=>{if(!j)return;const D=j.contentRect.width;if(M(D),!t){const F=D-E.width-ve.width;Ke(F<400)}});return T.observe(S),()=>T.disconnect()},[v,t,E.width,ve.width]);const Xt=Fe&&!Xe&&!ft,dt=A?0:E.width+re+(Xt?ve.width+re:0),Dt=Math.max(0,U-dt-re-8),Me=Math.min(pe,Math.floor(Dt*.4)),jt=Math.max(0,Dt-Me),ye=Math.min(Math.round(Dt/2),jt),Ie=Math.max(0,Math.min(te==="auto"?ye:te,jt)),ce=w.useRef(!1);w.useEffect(()=>{const S=(W?.rightPanel??null)!==null;S&&!ce.current&&(N(!0),Y("auto")),ce.current=S},[W?.rightPanel]);const et=w.useRef(Ie);et.current=Ie;const xe=w.useRef(jt);xe.current=jt;const gt=w.useCallback(S=>{S.preventDefault();const T=S.clientX,j=et.current,D=G=>{const se=j+(T-G.clientX),Ee=xe.current,Ze=Math.min($e,Ee);Y(Math.max(Ze,Math.min(Ee,se)))},F=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",F),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",D),document.addEventListener("mouseup",F),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);w.useEffect(()=>{if(!ft)return;const S=T=>{T.target.closest("[data-l2-floating]")||mt(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[ft]);const[He,Ct]=w.useState(null),[vt,de]=w.useState(!1),we=w.useRef(null);w.useEffect(()=>{if(!vt)return;const S=j=>{we.current&&!we.current.contains(j.target)&&de(!1)},T=j=>{j.key==="Escape"&&de(!1)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",T)}},[vt]);const[oe,st]=w.useState(),[ue,Le]=w.useState(),[ke,nt]=w.useState(),[Ye,Je]=w.useState(!1),[J,je]=w.useState(""),[Qe,be]=w.useState(!1),[Pe,tt]=w.useState(""),pt=w.useRef(null),Pt=w.useRef(null),kt=w.useCallback((S,T)=>{const j=S?dh[S]:void 0,D=j?"overview":S;Le(j),st(D),nt(T),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(D??"overview")},[v]);w.useCallback(S=>{S==="profile"?kt():zi(Q.current)?history.back():_("chat")},[kt]);const Ot=w.useCallback((S,T)=>{Mt("direct"),Xs(S),v&&k(),kt(T?.tab,T?.highlightMailboxId),Ct(null)},[v,k,kt]),At=w.useCallback((S,T)=>{const j=l.find(D=>D.name.toLowerCase()===S.toLowerCase());if(j){const D=T.target.getBoundingClientRect();Ct({agentId:j.id,top:D.bottom,left:D.left})}},[l]),js=w.useMemo(()=>l.map(S=>S.name),[l]),[he,Mt]=w.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,Xs]=w.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[yt,zs]=w.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Zt,Ti]=w.useState(""),Rl=500,ln=w.useRef(new Set),fd=S=>{if(ln.current.add(S),ln.current.size>Rl){const T=Math.floor(Rl*.2),j=ln.current.values();for(let D=0;D<T;D++){const F=j.next().value;F&&ln.current.delete(F)}}},cn=w.useMemo(()=>{if(r?.channelMessages){const S=r.activeChannel??"custom:general";return r.channelMessages.filter(T=>T.channel===S).map(T=>Bn(T))}},[]),{manager:zt,messages:ns,setMessages:Rs,sending:hs,setSending:Qi,activities:hn,setActivities:dn,activeSessionBuffer:un,actBuffers:Gn,sessionTabsBuffer:Yo,readConvMsgs:Hs,readSessionMsgs:$i,writeConvMsgs:z,setActiveSession:Oe,currentConvKeyRef:le,updateConvMsgs:Be,updateConvMsgsRaf:rt,appendConvActivity:ot,beginLoad:ut,beginStream:Lt,endStream:St,resetConv:ss,abortStream:gs,loadAndDisplay:rr,incrementSending:ni,decrementSending:Br,isSendingFor:xr,setStreamSession:us,clearStreamSession:ji,getStreamSession:md,saveSessionToCache:Kt,restoreSessionFromCache:fn}=y3(cn),[os,ir]=w.useState(""),[mn,El]=w.useState(null),[br,pn]=w.useState([]),pd=w.useRef({text:"",chips:[]});pd.current={text:os,chips:br};const[Al,Ml]=w.useState(!!r?.streamLastMessage),gn=w.useRef(null),G_=400;w.useEffect(()=>(hs?(gn.current&&(clearTimeout(gn.current),gn.current=null),Ml(!0)):Al&&(gn.current=setTimeout(()=>{Ml(!1),gn.current=null},G_)),()=>{gn.current&&clearTimeout(gn.current)}),[hs]);const gd=w.useRef({fullText:"",timers:[]});w.useEffect(()=>{if(!t||!r?.streamLastMessage||ns.length===0)return;const S=ns[ns.length-1];if(!S||S.sender!=="agent")return;const T=S.text;gd.current.fullText=T;const j=gd.current.timers;function D(){let G=0;Rs(Ee=>Ee.map((Ze,Se)=>Se===Ee.length-1?{...Ze,text:""}:Ze)),Ml(!0);const se=setInterval(()=>{if(G+=1+Math.floor(Math.random()*2),G>=T.length){clearInterval(se),Rs(Se=>Se.map((Ce,Ne)=>Ne===Se.length-1?{...Ce,text:T}:Ce));const Ee=setTimeout(()=>Ml(!1),800);j.push(Ee);const Ze=setTimeout(D,6e3);j.push(Ze)}else Rs(Ee=>Ee.map((Ze,Se)=>Se===Ee.length-1?{...Ze,text:T.slice(0,G)}:Ze))},30);j.push(se)}const F=setTimeout(D,1500);return j.push(F),()=>{j.forEach(G=>clearTimeout(G)),gd.current.timers=[]}},[]);const[K_,yg]=w.useState(!1),[Od,Sg]=w.useState(!1),[J_,wg]=w.useState(!1);w.useEffect(()=>{if(!Od){wg(!1);return}const S=setTimeout(()=>wg(!0),250);return()=>clearTimeout(S)},[Od]);const[On,Wr]=w.useState(!0),[ek,xd]=w.useState(!0),bd=w.useRef(0),[nr,Ll]=w.useState([]),[_g,kg]=w.useState(null),vd=w.useRef(null),Ss=w.useRef(null),[tk,Ri]=w.useState(null),[sk,Cg]=w.useState(0);w.useEffect(()=>$2(S=>{S===ge&&Cg(T=>T+1)}),[ge]),w.useEffect(()=>{const S=()=>Cg(T=>T+1);return window.addEventListener("focus",S),()=>window.removeEventListener("focus",S)},[]),w.useEffect(()=>{if(!ge){Ri(null);return}let S=!1;return ne.agents.get(ge).then(T=>{if(S)return;const j=T.effectiveModel;Ri(j?.provider&&j?.model?{provider:j.provider,model:j.model}:null)}).catch(()=>{S||Ri(null)}),()=>{S=!0}},[ge,sk]);const yd=w.useRef(!1),Go=w.useCallback(()=>{const S=Ss.current;if(!S)return;const T=yd.current,j=T?36:52,D=e0(T);S.style.height="auto";const F=Math.max(j,Math.min(S.scrollHeight,D));S.style.height=`${F}px`,S.style.overflowY=F>=D?"auto":"hidden"},[]);w.useEffect(()=>{const S=requestAnimationFrame(()=>Go());return()=>cancelAnimationFrame(S)},[os,nr.length,Go]);const Sd=S=>{try{const T=localStorage.getItem(`markus_closed_tabs_${S}`);return T?new Set(JSON.parse(T)):new Set}catch{return new Set}},rk=(S,T)=>{const j=Sd(S);j.add(T);try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...j]))}catch{}},ik=(S,T)=>{const j=Sd(S);if(j.delete(T))try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...j]))}catch{}},Pg=S=>{try{return localStorage.getItem(`markus_active_session_${S}`)}catch{return null}},Ko=(S,T)=>{if(S)try{T&&T!==lt?localStorage.setItem(`markus_active_session_${S}`,T):localStorage.removeItem(`markus_active_session_${S}`)}catch{}},[Qr,Ei]=w.useState([]),[nk,Nl]=w.useState(0),[Tg,Dl]=w.useState(1),[Il,Bl]=w.useState(!1),[Wl,Qg]=w.useState(!1),[it,Ai]=w.useState(null),[Jo,xn]=w.useState(!1),[$g,bn]=w.useState(!1),[wd,jg]=w.useState(null),[_d,kd]=w.useState(""),[Rg,Cd]=w.useState([]),[vn,Xl]=w.useState(null),[ok,Eg]=w.useState(null),[ea,Pd]=w.useState([]),[yn,ta]=w.useState(null),[ak,Ag]=w.useState(null),Mg=w.useRef(new Set),[Lg,Td]=w.useState([]),[$r,sa]=w.useState(null),Mi=$r?$r.items[$r.index]??null:null,[lk,Ng]=w.useState(null),[Dg,Qd]=w.useState([]),[qs,ck]=w.useState([]),Ys=S=>{ck(T=>{const j=typeof S=="function"?S(T):S,D=new Set,F=j.filter(G=>D.has(G.id)?!1:(D.add(G.id),!0));return F.some(G=>G.isMain)?[...F.filter(G=>G.isMain),...F.filter(G=>!G.isMain)]:F})},Ig=w.useRef(null);w.useEffect(()=>{if(!it)return;const S=Ig.current;if(!S)return;const T=S.querySelector(`[data-session-tab-id="${CSS.escape(it)}"]`);if(!T)return;const j=requestAnimationFrame(()=>{T.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(j)},[it,qs.length]);const zl=w.useRef(null),$d=w.useRef(null),[ws,ra]=w.useState(r?.groupChats??[]),jd=w.useRef(ws);jd.current=ws;const Bg=w.useRef(null),[Rd,_s]=w.useState(!1),[Ed,Kn]=w.useState(!1),[ql,Ad]=w.useState(""),[hk,ia]=w.useState(-1),[dk,Zl]=w.useState([]),[uk,Wg]=w.useState(!1),Md=w.useRef(void 0),[Es,Xg]=w.useState(r?.teams??[]),[Ld,fk]=w.useState(!!r),[mk,pk]=w.useState([]),[Nd,zg]=w.useState([]),[gk,Ok]=w.useState(null),[T3,Q3]=w.useState(!1),[$3,j3]=w.useState(""),[Jn,na]=w.useState(!1),Vl=w.useRef(null),[qg,xk]=w.useState(""),[oa,eo]=w.useState(0),[to,Fl]=w.useState(!1),[Zg,bk]=w.useState(""),[Dd,aa]=w.useState(0),[Id,vk]=w.useState([]),Vg=w.useRef(!1),Bd=w.useCallback(()=>{Vg.current||(Vg.current=!0,(async()=>{try{const{skills:S}=await ne.skills.list();vk(S.map(T=>({name:T.name,description:T.description??T.name})))}catch{}})())},[]);w.useEffect(()=>{Bd()},[Bd]);const Sn=Zg?Id.filter(S=>S.name.toLowerCase().includes(Zg.toLowerCase())):Id,[yk,Sk]=w.useState([]),Fg=w.useRef(!1),wk=w.useCallback(()=>{Fg.current||(Fg.current=!0,(async()=>{const S=[];try{const[T,j,D,F,G]=await Promise.all([ne.projects.list().catch(()=>({projects:[]})),ne.requirements.list({lean:!0}).catch(()=>({requirements:[]})),ne.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),ne.deliverables.search({limit:100}).catch(()=>({results:[]})),ne.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const se of T.projects)S.push({id:se.id,name:se.name,entityType:"project",role:se.status});for(const se of j.requirements)S.push({id:se.id,name:se.title,entityType:"requirement",role:se.priority});for(const se of D.tasks)S.push({id:se.id,name:se.title,entityType:"task",role:se.status});for(const se of F.results)S.push({id:se.id,name:se.title,entityType:"deliverable",role:se.type});for(const se of G.teams)try{const Ee=await ne.workflows.list(se.id);for(const Ze of Ee.workflows)S.push({id:Ze.name,name:Ze.displayName||Ze.name,entityType:"workflow",role:`v${Ze.version}`})}catch{}}catch{}Sk(S)})())},[]),as=he==="channel"?ws.find(S=>S.channelKey===yt)?.teamId:void 0,_k=w.useRef(null),Xr=w.useRef(null),Ug=w.useRef(void 0),la=w.useCallback((S,T)=>{Ai(T),S&&(T===null?zt.clearActiveSession(S):zt.setActiveSession(S,T))},[Ai,zt]),Hg=w.useMemo(()=>Aa(he,ge,yt,Zt),[he,ge,yt,Zt]);uh();const ca=Cs.isStreaming(it),kk=Cs.liveBubbleId(it),wn=w.useMemo(()=>po(Hg,it),[Hg,it]),Zs=w.useRef(wn);Zs.current=wn;const[ha,Ck]=w.useState(wn);if(w.useEffect(()=>{ka.save(ha,{text:os,images:nr,context:br,replyTo:mn})},[os,ha,nr,br,mn]),ha!==wn){const S={text:os,images:nr,context:br,replyTo:mn};if(os!==ka.peek(ha).text)ka.save(wn,S);else{ka.save(ha,S);const T=ka.get(wn);ir(T.text),Ll(T.images),pn(T.context),El(T.replyTo)}Ck(wn)}const Os=w.useRef(null),Wd=w.useRef(null),oi=w.useRef(null),Ul=w.useRef(null),Xd=w.useRef(null),Hl=w.useRef(0),Yl=w.useRef([]),so=w.useRef(null),Yg=w.useRef([]),zd=w.useRef(void 0),Gl=w.useRef(null),_n=w.useCallback(()=>zt.getActiveSession(le.current)??le.current,[zt]),Li=w.useCallback((S,T)=>{S&&(zt.setWindowBounds(S,T),S===_n()&&yg(T.hasMore))},[zt,_n]);w.useEffect(()=>{yg(zt.getWindowBounds(_n()).hasMore)},[zt,_n,he,ge,yt,Zt,it]),w.useEffect(()=>{if(!Jo)return;const S=T=>{$d.current&&!$d.current.contains(T.target)&&zl.current&&!zl.current.contains(T.target)&&xn(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[Jo]);const Kl=(S,T)=>{if(!T||S===T)return`notes:${S}`;const[j,D]=[S,T].sort();return`dm:${j}:${D}`};w.useEffect(()=>{localStorage.setItem("markus_chat_mode",he)},[he]),w.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),w.useEffect(()=>{localStorage.setItem("markus_chat_channel",yt)},[yt]),w.useEffect(()=>{let S=!1;if(t||!ge||he!=="direct"){Ri(null);return}return ne.agents.get(ge).then(T=>{if(S)return;const j=T.config?.llmConfig;Ri(j?.modelMode==="custom"&&j.primary&&j.defaultModel?{provider:j.primary,model:j.defaultModel}:null)}).catch(()=>{S||Ri(null)}),()=>{S=!0}},[ge,he,t]);const{counts:qd,sessionAgentMap:da,markRead:Zd,markReadMany:Gg,setActiveKey:Pk,clearActiveKeys:Tk}=DC({enabled:!t}),Jl=w.useMemo(()=>{const S={};for(const[T,j]of Object.entries(qd))T.startsWith("channel:")&&(S[T.slice(8)]=j);return S},[qd]),Vd=IC(da,qd);w.useEffect(()=>{let S=0;for(const T of Vd.values())S+=T;for(const T of Object.values(Jl))S+=T;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:S}}))},[Vd,Jl]);const ec=Vd,Qk=w.useCallback(async S=>{const T=[];for(const[j,D]of Object.entries(da))D===S&&T.push(`session:${j}`);await Gg(T)},[da,Gg]);w.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(he==="direct"&&ge&&Qk(ge),he==="channel"&&yt)Zd(`channel:${yt}`);else if(he==="direct"&&it)Zd(`session:${it}`);else if(he==="dm"&&Zt){const j=`dm:${[e?.id,Zt].sort().join(":")}`;Zd(`channel:${j}`)}const T=[];if(he==="direct"&&it){T.push(`session:${it}`);for(const[j,D]of Object.entries(da))D===ge&&T.push(`session:${j}`)}else he==="channel"&&yt?T.push(`channel:${yt}`):he==="dm"&&Zt&&e?.id&&T.push(`channel:dm:${[e.id,Zt].sort().join(":")}`);for(const j of T)Pk(j);return()=>{Tk(T)}},[t,he,yt,it,Zt,ge,x,P,da]);const or=w.useCallback(()=>ne.agents.list().then(S=>h(S.agents)).catch(()=>{}),[]),$k=w.useCallback((S,T)=>{S&&h(j=>j.map(D=>D.id===S?{...D,avatarUrl:T}:D))},[]),Gs=w.useCallback(()=>ne.teams.list().then(S=>{Xg(S.teams),fk(!0)}).catch(()=>{}),[]),ro=w.useCallback(()=>ne.groupChats.list().then(S=>ra(S.chats)).catch(()=>{}),[]),jk=w.useMemo(()=>Ou(or,3e3),[or]),tc=w.useMemo(()=>Ou(Gs,5e3),[Gs]),Fd=w.useMemo(()=>Ou(ro,3e3),[ro]),ua=w.useCallback(()=>{ne.users.list(e?.orgId).then(S=>d(S.users)).catch(()=>{})},[e?.orgId]);w.useEffect(()=>{v&&(x!=="team"||!y||GO(y,Es.map(S=>S.id),Ld)==="missing"&&(window.location.hash=Ut.TEAM))},[v,x,y,Es,Ld]),w.useEffect(()=>{t||(Promise.all([or(),Gs()]).finally(()=>p(!1)),ua(),ne.tasks.list().then(S=>zg(S.tasks)).catch(()=>{}),ne.externalAgents.list().then(S=>pk(S.agents)).catch(()=>{}),ro())},[t,ua]),w.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),d(r.humans??[]),Xg(r.teams??[]),ra(r.groupChats??[]),r.channelMessages)){const S=r.activeChannel??"custom:general";Rs(r.channelMessages.filter(T=>T.channel===S).map(T=>Bn(T)))}},[t,r]),w.useEffect(()=>{AP()},[]),w.useEffect(()=>{if(t||!o)return;const S=()=>{const G=ge,se=qs.map(Ee=>Ee.id).filter(Ee=>Ee!==lt);it&&it!==lt&&!se.includes(it)&&se.push(it),G&&se.length>0&&MP(G,se)};let T=null;const j=()=>{T||(T=setInterval(S,6e4))},D=()=>{T&&clearInterval(T),T=null},F=()=>{document.hidden?D():(S(),j())};return document.addEventListener("visibilitychange",F),document.hidden||j(),S(),()=>{D(),document.removeEventListener("visibilitychange",F)}},[t,o,qs,ge,it]),w.useEffect(()=>{if(t||!o)return;or(),Gs();const S=setInterval(or,3e4),T=setInterval(Gs,6e4),j=Rt.on("agent:update",Ne=>{const ct=Ne?.payload;if(ct?.agentId){const wt=ct.status,es=ct.currentActivity;h(Vt=>Vt.map(xs=>{if(xs.id!==ct.agentId)return xs;const bs={...xs};return wt&&(bs.status=wt),es!==void 0&&(bs.currentActivity=es),bs}))}jk(),tc()}),D=Rt.on("team:update",()=>{tc(),Fd()}),F=Rt.on("agent:removed",tc),G=Rt.on("chat:group_created",()=>{ro(),Gs(),or()}),se=Rt.on("chat:group_updated",Fd),Ee=Rt.on("chat:group_deleted",()=>{Fd(),tc()}),Ze=Rt.on("task:update",Ne=>{const ct=Ne?.payload;ct?.taskId&&zg(wt=>wt.map(es=>es.id===ct.taskId?{...es,status:ct.status??es.status}:es))}),Se=Rt.on("approval:resolved",Ne=>{const ct=Ne?.payload?.approvalId;ct&&(Xl(wt=>wt&&wt.id===ct?null:wt),ta(wt=>wt&&wt.id===ct?null:wt))}),Ce=()=>{or(),Gs(),ua()};return window.addEventListener("markus:data-changed",Ce),()=>{clearInterval(S),clearInterval(T),j(),D(),F(),G(),se(),Ee(),Ze(),Se(),window.removeEventListener("markus:data-changed",Ce)}},[t,o,ua]),w.useEffect(()=>{if(t)return;const S=Se=>{const Ce=Se.detail;if(VC(Ce.page)===Ut.TEAM){if(Ce.params?.agentId&&(Ce.params.profileTab?Ot(Ce.params.agentId,{tab:Ce.params.profileTab}):(Mt("direct"),Xs(Ce.params.agentId),_("chat"),v&&k(),Ce.params.sessionId?Te.current={agentId:Ce.params.agentId,sessionId:Ce.params.sessionId,chips:Ce.params.chatChips??null}:Ce.params.preferMain==="1"&&(oi.current={mode:"direct",agentId:Ce.params.agentId,sessionId:null,preferMain:!0}))),Ce.params?.selectAgent&&(Mt("direct"),Xs(Ce.params.selectAgent),_("chat"),v&&k()),Ce.params?.openDeliverable){const Ne=Ce.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?gr.navigate(Ut.DELIVERABLES,{openDeliverable:Ne}):ie&&ne.deliverables.get(Ne).then(ct=>{ct.deliverable&&ie({kind:"deliverable",deliverable:ct.deliverable})}).catch(()=>{})}if(Ce.params?.prefillMessage){const Ne=Ce.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Ce.params?.autoSend==="true"?setTimeout(()=>Ug.current?.(Ne),300):((Ce.params?.preferMain==="1"||Ce.params?.sessionId)&&(Ul.current=Ne),ir(Ne),setTimeout(()=>{const ct=Ss.current;ct&&(ct.focus(),ct.setSelectionRange(ct.value.length,ct.value.length))},100))}if(Ce.params?.chatChips){const Ne=Ce.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ce.params.sessionId||De(Ne)}if(Ce.params?.dm&&(Mt("dm"),Ti(Ce.params.dm),_("chat"),v&&k()),Ce.params?.channel&&(Mt("channel"),zs(Ce.params.channel),_("chat"),v&&k()),Ce.params?.selectTeam){const Ne=Ce.params.selectTeam;if(v)C(Ne);else{const ct=jd.current.find(wt=>wt.type==="team"&&wt.teamId===Ne);Mt("channel"),zs(ct?.channelKey??`group:${Ne}`),_("chat"),_s(!1),Ue(!0)}}Ce.params?.openHire}},T=localStorage.getItem("markus_nav_agentId");if(T){localStorage.removeItem("markus_nav_agentId");const Se=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),Mt("direct"),Xs(T),Se?Ot(T,{tab:Se}):(_("chat"),v&&k())}const j=localStorage.getItem("markus_nav_dm");j&&(localStorage.removeItem("markus_nav_dm"),Mt("dm"),Ti(j),_("chat"),v&&k());const D=localStorage.getItem("markus_nav_channel");D&&(localStorage.removeItem("markus_nav_channel"),Mt("channel"),zs(D),_("chat"),v&&k());const F=localStorage.getItem("markus_nav_prefillMessage");F&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ir(F),setTimeout(()=>{const Se=Ss.current;Se&&(Se.focus(),Se.setSelectionRange(Se.value.length,Se.value.length))},150));const G=localStorage.getItem("markus_nav_chatChips");G&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),De(G));const se=localStorage.getItem("markus_nav_openDeliverable");se&&(localStorage.removeItem("markus_nav_openDeliverable"),v?gr.navigate(Ut.DELIVERABLES,{openDeliverable:se}):ie&&ne.deliverables.get(se).then(Se=>{Se.deliverable&&ie({kind:"deliverable",deliverable:Se.deliverable})}).catch(()=>{}));const Ee=localStorage.getItem("markus_nav_selectAgent");Ee&&(localStorage.removeItem("markus_nav_selectAgent"),Mt("direct"),Xs(Ee),_("chat"),v&&k());const Ze=localStorage.getItem("markus_nav_selectTeam");if(Ze)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(Ze);else{const Se=jd.current.find(Ce=>Ce.type==="team"&&Ce.teamId===Ze);Mt("channel"),zs(Se?.channelKey??`group:${Ze}`),_("chat"),_s(!1),Ue(!0)}return window.addEventListener("markus:navigate",S),()=>window.removeEventListener("markus:navigate",S)},[t]),w.useEffect(()=>{const S=Bg.current;if(!S)return;const T=ws.find(j=>j.type==="team"&&j.teamId===S);Bg.current=null,Mt("channel"),zs(T?.channelKey??`group:${S}`),_("chat"),_s(!1),Ue(!0)},[ws,Es]),w.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||ge&&l.some(j=>j.id===ge))return;const S=localStorage.getItem("markus_nav_after_remove");if(S&&(localStorage.removeItem("markus_nav_after_remove"),S.startsWith("channel:"))){Mt("channel"),zs(S.slice(8)),_("chat");return}const T=l.find(j=>!j.teamId&&j.role?.toLowerCase()==="secretary")??l.find(j=>j.role?.toLowerCase()==="secretary")??l.find(j=>j.name?.toLowerCase().includes("secretary"));T?(Mt("direct"),Xs(T.id),_("chat")):l.length>0&&(Mt("direct"),Xs(l[0].id),_("chat"))},[l,ge]);const io=w.useRef(!1),kn=w.useRef(!1),fa=w.useRef(0),Ud=w.useRef("none"),Hd=w.useRef(0),sc=w.useRef(0),ai=w.useRef(null),Yd=w.useRef(null),Kg=w.useRef([]),Gd=w.useRef(0),[Rk,Cn]=w.useState(!1),no=w.useRef(0),[Jg,ma]=w.useState(0),oo=w.useCallback(()=>performance.now()<fa.current,[]),Ni=w.useCallback(()=>xP({takeover:kn.current,gestureActive:oo()}),[oo]),ar=w.useCallback(()=>{kn.current=!1,fa.current=0,Ud.current="none",Gd.current=0,sc.current+=1,io.current=!1,Cn(!1),no.current=0,ma(0)},[]),zr=w.useCallback(()=>{kn.current||(kn.current=!0,sc.current+=1,io.current=!1,ai.current!==null&&(cancelAnimationFrame(ai.current),ai.current=null),Cn(!0))},[]),rc=w.useCallback(S=>{fa.current=performance.now()+vu,S!=="none"&&(Ud.current=S);const T=Xr.current;bP(S,!!T&&c0(T))&&zr()},[zr]),ic=w.useCallback(S=>{const T=Xr.current;if(!T)return;const j=T.scrollTop-Hd.current;Hd.current=T.scrollTop;const D=OP({takeover:kn.current,gestureActive:oo(),gestureDirection:Ud.current,scrollable:c0(T),distance:Uc(T),deltaScrollTop:j,programmatic:S?.programmatic??io.current,intentPending:Os.current!==null});D==="handover"?zr():D==="resume"?ar():D==="follow"?(Cn(!1),no.current=0,ma(0)):kn.current&&Cn(!0)},[oo,zr,ar]);w.useEffect(()=>{const S=Xr.current;if(!S)return;let T=null;const j=Ce=>{rc(uP(Ce.deltaX,Ce.deltaY))},D=Ce=>{T=Ce.touches[0]?.clientY??null,fa.current=performance.now()+vu},F=Ce=>{const Ne=Ce.touches[0]?.clientY;if(Ne==null)return;const ct=gP(T,Ne);T=Ne,rc(ct)},G=()=>{T=null},se=Ce=>{np(Ce.target)||rc(pP(Ce.key))},Ee=Ce=>{const Ne=S.getBoundingClientRect();Ce.clientX-Ne.left<S.clientWidth||(fa.current=performance.now()+vu)},Ze=()=>{ic()};S.addEventListener("wheel",j,{passive:!0}),S.addEventListener("touchstart",D,{passive:!0}),S.addEventListener("touchmove",F,{passive:!0}),S.addEventListener("touchend",G,{passive:!0}),S.addEventListener("pointerdown",Ee,{passive:!0}),S.addEventListener("scroll",Ze,{passive:!0}),document.addEventListener("keydown",se);const Se=typeof ResizeObserver<"u"?new ResizeObserver(()=>ic()):null;return Se?.observe(S),Hd.current=S.scrollTop,ic(),()=>{S.removeEventListener("wheel",j),S.removeEventListener("touchstart",D),S.removeEventListener("touchmove",F),S.removeEventListener("touchend",G),S.removeEventListener("pointerdown",Ee),S.removeEventListener("scroll",Ze),document.removeEventListener("keydown",se),Se?.disconnect()}},[x,ic,rc]);const Kd=w.useMemo(()=>new Set(Dg),[Dg]),ls=w.useMemo(()=>{const S=he==="channel"?ns:ns.filter(D=>!D.isActivityLog),T=Kd.size===0?S:S.filter(D=>!(D.isNotification&&Kd.has(D.id))),j=t&&Al?T.length-1:-1;return T.filter((D,F)=>l2(D,F===j||!!D.isStreaming&&ca))},[ns,he,Kd,ca,t,Al]);w.useEffect(()=>{yd.current=P==="chat"&&ls.length>0,Go()},[P,ls.length,Go]);const ao=V2({count:ls.length,getScrollElement:()=>Xr.current,getItemKey:S=>ls[S]?.id??S,estimateSize:S=>{const T=ls[S];return T?T.segments&&T.segments.length>0?300:T.text.length>500?200:120:120},overscan:8});ao.shouldAdjustScrollPositionOnItemSizeChange=(S,T,j)=>xu()||Os.current?.priority==="jump"?!1:S.start<(j.scrollOffset??0);const lr=w.useCallback((S="instant")=>{if(!Ni()||performance.now()<Gd.current)return;const T=Xr.current;if(!T)return;const j=++sc.current,D=()=>j===sc.current&&Ni();if(S==="smooth"){Gd.current=performance.now()+hP,T.scrollTo({top:T.scrollHeight,behavior:"smooth"});return}ai.current!==null&&(cancelAnimationFrame(ai.current),ai.current=null),io.current=!0;let F=0;const G=()=>{if(ai.current=null,!D()){io.current=!1;return}if(T.scrollTop=T.scrollHeight,F+=1,F<cP&&Uc(T)>1){ai.current=requestAnimationFrame(G);return}io.current=!1};T.scrollTop=T.scrollHeight,ai.current=requestAnimationFrame(G)},[Ni]),Pn=w.useCallback(S=>{const T=Xr.current;!T||!S||T.scrollHeight<=T.clientHeight||u0.save(S,yP(d0(T),T))},[]),Tn=w.useCallback(()=>{Hl.current+=1;for(const S of Yl.current)clearTimeout(S);Yl.current=[]},[]),lo=w.useCallback(()=>{Os.current=null,Tn()},[Tn]),eO=w.useCallback(()=>{ar(),lo(),Yd.current!==null&&cancelAnimationFrame(Yd.current);for(const S of Kg.current)clearTimeout(S);lr("instant"),Yd.current=requestAnimationFrame(()=>lr("instant")),Kg.current=[60,160,320].map(S=>setTimeout(()=>lr("instant"),S))},[ar,lo,lr]),Jd=w.useCallback(S=>{const T=Os.current;if(!T||T.key!==S)return!0;if(Zs.current!==S||T.priority!=="prepend"&&oo())return Os.current=null,!0;const j=Xr.current;if(!j)return!0;if(xu())return!1;const{anchor:D}=T;if(D.kind==="bottom"){yu(T.priority)&&ar(),j.scrollTop=j.scrollHeight;const ct=Uc(j)<=1,wt=p0(ct,T.prevSettled);return T.prevSettled=ct,wt?(Os.current=null,!0):!1}const F=TP(T.at,performance.now()),G=_P(d0(j),j,D.id,D.delta),se=G===null&&!F&&(Hs(T.bufferId)??[]).some(ct=>ct.id===D.id),Ee=G!==null&&Math.abs(G)<=1,Ze=p0(Ee,T.prevSettled),Se=G===null&&!se,Ce=zt.getWindowBounds(T.bufferId).hasMore,Ne=QP({priority:T.priority,rendered:G!==null,stale:F,stable:Ze,absent:Se,canLoadMore:Ce});switch(T.prevSettled=G!==null?Ee:null,yu(T.priority)&&Ne!=="release-bottom"&&Ne!=="release-hold"&&zr(),Ne){case"apply":return Xi("intent:apply",{id:D.id,priority:T.priority,correction:G}),Os.current=null,!0;case"refine":return G!==null&&Math.abs(G)>1&&(j.scrollTop+=G),G!==null&&Math.abs(G)>8&&Xi("intent:refine",{id:D.id,priority:T.priority,correction:G}),!1;case"release-bottom":return Xi("intent:release-bottom",{id:D.id,priority:T.priority}),Os.current=null,yu(T.priority)&&ar(),j.scrollTop=j.scrollHeight,!0;case"release-hold":return Xi("intent:release-hold",{id:D.id,priority:T.priority,stale:F,absent:Se,canLoadMore:Ce,bufferId:T.bufferId}),Os.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:T.priority,anchor:D}),!0;default:{const ct=Yg.current.findIndex(wt=>wt.id===D.id);if(ct>=0){const wt=ao.getOffsetForIndex(ct,"start");wt&&(j.scrollTop=wt[0]+D.delta)}else zd.current?.();return!1}}},[ao,oo,zr,ar,Hs]),nc=w.useCallback(()=>{const S=Os.current;if(!S)return;const T=S.key;Tn();const j=Hl.current,D=G=>{Yl.current.push(setTimeout(()=>{j===Hl.current&&Os.current?.key===T&&(Jd(T)||D(m0))},G))},F=[0,60,160,320,560,900];F.forEach((G,se)=>{const Ee=se===F.length-1,Ze=()=>{if(j!==Hl.current)return;!Jd(T)&&Ee&&D(m0)};G===0?requestAnimationFrame(Ze):Yl.current.push(setTimeout(Ze,G))})},[Jd,Tn]),co=w.useCallback((S,T,j="restore",D)=>{if(!S)return!1;const F=Os.current;return CP(F,{key:S,priority:j})?(Os.current={key:S,bufferId:D??_n(),anchor:T,at:performance.now(),priority:j,prevSettled:null},nc(),!0):!1},[_n,nc]),pa=w.useCallback(S=>{S&&co(S,u0.get(S)??{kind:"bottom"})},[co]),Ek=w.useCallback(()=>{Os.current||(so.current!==null&&clearTimeout(so.current),so.current=setTimeout(()=>{so.current=null,Pn(Zs.current)},200))},[Pn]);Yg.current=ls,w.useLayoutEffect(()=>()=>{Pn(Zs.current),Tn(),so.current!==null&&clearTimeout(so.current)},[Pn,Tn]);const ga=w.useMemo(()=>$I(ls,ql),[ls,ql]);w.useEffect(()=>{ia(-1)},[ql]);const oc=w.useCallback(S=>{const T=()=>{const F=document.getElementById(`msg-${S}`);return F?(F.classList.remove("chat-find-hit"),F.offsetWidth,F.classList.add("chat-find-hit"),window.setTimeout(()=>F.classList.remove("chat-find-hit"),1600),!0):!1};let j=0;const D=()=>{T()||j++>=8||window.requestAnimationFrame(D)};D()},[]),tO=w.useCallback(async(S,T)=>{lo(),zr();const j=Zs.current,D=le.current,F=()=>(Hs(D)??[]).some(se=>se.id===S);let G=F();if(!G&&j){const se=zt.getActiveSession(D)??D,Ee=await RI({targetId:S,has:F,targetCreatedAt:T,fetchPage:async Se=>{if(!se||se===lt)return{messages:[],hasMore:!1};const Ce=await ne.sessions.getMessages(se,50,Se);return{messages:Ce.messages,hasMore:Ce.hasMore}}}),Ze=jI(Ee.messages,S);Ze.length>0&&(z(D,Ze.map(mh)),Li(se,{hasMore:Ee.hasMore,oldestCursor:Ze[0]?new Date(Ze[0].createdAt).toISOString():null})),G=Ee.found||F(),Xi("jump:collected",{messageId:S,found:Ee.found,kept:Ze.length,exhausted:Ee.exhausted})}if(Xi("jump:located",{messageId:S,loaded:G,key:j,nowKey:Zs.current}),!(j&&Zs.current!==j)){if(G&&j){co(j,h0(S),"jump",_n()),Xi("jump:scheduled",{messageId:S,key:j}),oc(S);return}j&&(Xi("jump:fallback-bottom",{messageId:S,key:j}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:S}),ar(),lr("instant"))}},[lo,zr,co,oc,Hs,zt,z,Li,ar,lr]),Ak=w.useCallback(S=>{const T=ga.matches[S];T&&(ia(S),lo(),zr(),Zs.current&&co(Zs.current,h0(T.messageId),"jump"),oc(T.messageId))},[ga.matches,lo,zr,co,oc]);w.useEffect(()=>{if(P!=="chat"||t)return;const S=T=>{T.key.toLowerCase()!=="f"||T.altKey||T.shiftKey||!(b?T.metaKey&&!T.ctrlKey:T.ctrlKey&&!T.metaKey)||(T.preventDefault(),Kn(!0))};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[P,t,b]);const sO=w.useRef(o);w.useEffect(()=>{sO.current=o},[o]),w.useLayoutEffect(()=>{const S=Wd.current;if(S&&(Wd.current=null,!Os.current&&S.key===Zs.current)){const T=Xr.current,j=T?T.scrollHeight-S.scrollHeight:0;T&&j>0&&(T.scrollTop+=j,T.dispatchEvent(new Event("scroll")))}if(Os.current){nc();return}sO.current&&Ni()&&(xu()||lr())},[ns,lr,Ni,nc]);const rO=w.useRef(P);w.useEffect(()=>{const S=rO.current!=="chat";rO.current=P,P==="chat"&&S&&pa(Zs.current)},[P,hs,lr,Ni,pa]);const iO=w.useRef(I);w.useEffect(()=>{if(iO.current===I||(iO.current=I,P!=="chat")||ls.length===0||hs||On||!Ni())return;const S=[],T=requestAnimationFrame(()=>lr("instant"));for(const j of[60,160,320])S.push(setTimeout(()=>lr("instant"),j));return()=>{cancelAnimationFrame(T);for(const j of S)clearTimeout(j)}},[I,P,ls.length,hs,On,lr,Ni]);const ac=w.useCallback(async(S,T,j)=>{const D=T??`ch:${S}`;!j?.quiet&&le.current===D&&Wr(!0);try{const F=await ne.channels.getMessages(S,50),G=F.messages.map(se=>Bn(se,e?.id));z(D,G),Li(D,{hasMore:F.hasMore,oldestCursor:F.messages[0]?new Date(F.messages[0].createdAt).toISOString():null}),le.current===D&&Rs(G)}catch{le.current===D&&Rs([])}finally{!j?.quiet&&le.current===D&&Wr(!1)}},[Li]),eu=w.useCallback(async S=>{if(!S)return Ei([]),Nl(0),Dl(1),Bl(!1),xd(!1),[];xd(!0);try{const T=await ne.sessions.listByAgent(S,20,1);return Ei(T.sessions),Nl(T.total??T.sessions.length),Dl(T.page??1),Bl(!!T.hasMore),T.sessions}catch{return Ei([]),Nl(0),Dl(1),Bl(!1),[]}finally{xd(!1)}},[]),nO=w.useRef({chatContext:[],input:"",pendingImages:[],chatMode:he,selectedAgent:ge,activeSessionId:it,activeDmUserId:Zt,authUser:e,activeChannel:yt,groupChats:ws,agents:l,humans:u,sending:hs,chatReplyTo:null});nO.current={chatContext:br,input:os,pendingImages:nr,chatMode:he,selectedAgent:ge,activeSessionId:it,activeDmUserId:Zt,authUser:e,activeChannel:yt,groupChats:ws,agents:l,humans:u,sending:hs,chatReplyTo:mn};const Mk=S3({stateRef:nO,actBuffers:Gn,activeSessionBuffer:un,readConvMsgs:Hs,readSessionMsgs:$i,currentConvKeyRef:le,updateConvMsgs:Be,updateConvMsgsRaf:rt,appendConvActivity:ot,beginStream:Lt,endStream:St,abortStream:gs,clearStreamSession:ji,setStreamSession:us,getStreamSession:md,setActiveSession:Oe,incrementSending:ni,decrementSending:Br,loadAndDisplay:rr,sessionSwitchSeqRef:bd,setSending:Qi,setActivities:dn,setInput:ir,setChatContext:pn,setPendingImages:Ll,setMentionDropdown:na,setChatReplyTo:El,setActiveSessionId:Ai,setStoredActiveSession:Ko,setOpenSessionTabs:Ys,setSessions:Ei,setLoadingChat:Wr,setWindowBounds:Li,makeConvKey:Aa,makeDmChannel:Kl,addRecentMsgId:fd,resumeChatScrollFollow:ar,loadSessions:eu,t:i}),{send:ho,stopSending:Lk,tryReattachActiveStream:Qn,loadSessionMessages:lc}=Mk;Ug.current=ho;const oO=w.useCallback(()=>{eO(),ho()},[eO,ho]),aO=w.useRef(Qn);aO.current=Qn;const Nk=uh();w.useEffect(()=>{if(!o||t||he!=="direct"||!ge)return;const S=it;!S||S===lt||Cs.isStreaming(S)&&aO.current(ge,S,le.current)},[o,t,he,ge,it,Nk]);const lO=w.useRef(()=>{});lO.current=()=>{const S=b2({isActive:o,previewMode:t,chatMode:he,selectedAgent:ge,activeSessionId:it,placeholderId:lt});if(!S||!ge)return;const T=le.current;lc(S,T).then(()=>{Qn(ge,S,T)})},w.useEffect(()=>{const S=()=>{document.visibilityState==="visible"&&lO.current()};return document.addEventListener("visibilitychange",S),window.addEventListener("pageshow",S),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("pageshow",S)}},[]);const Dk=w.useCallback(async()=>{if(Wl||!ge||!Il)return;Qg(!0);const S=Tg+1,T=ge;try{const j=await ne.sessions.listByAgent(T,20,S);Ei(D=>{const F=new Set(D.map(se=>se.id)),G=[...D,...j.sessions.filter(se=>!F.has(se.id))];return Nl(j.total??G.length),G}),Dl(S),Bl(!!j.hasMore)}catch{}Qg(!1)},[Wl,Il,Tg,ge]),cO=w.useCallback(S=>{jg(S.id),kd((S.isMain?"":S.title)||"")},[]),Oa=w.useCallback(()=>{jg(null),kd("")},[]),hO=w.useCallback(async S=>{const T=_d.trim();if(!T){Oa();return}try{const D=(await ne.sessions.renameTitle(S.id,T))?.session?.title??T;Ei(F=>F.map(G=>G.id===S.id?{...G,title:D}:G)),Ys(F=>F.map(G=>G.id===S.id?{...G,title:D}:G))}catch{}Oa()},[_d,Oa]),dO=w.useCallback(async()=>{if(Gl.current)return Gl.current;const S=le.current,T=zt.getActiveSession(S)??S,j=zt.getWindowBounds(T),D=j.oldestCursor;if(!j.hasMore||!D)return 0;const F=T&&T!==lt?T:null,se=(async()=>{Sg(!0);try{const Ee=Zs.current;let Ze=[],Se=!1,Ce=null;if(he==="channel"||he==="dm"){const xs=he==="dm"?Kl(e?.id??"",Zt):yt,bs=await ne.channels.getMessages(xs,50,D);Ze=bs.messages.map(jr=>Bn(jr,e?.id)),Se=bs.hasMore,Ce=bs.messages[0]?new Date(bs.messages[0].createdAt).toISOString():null}else if(F){const xs=await ne.sessions.getMessages(F,50,D);Ze=xs.messages.map(mh),Se=xs.hasMore,Ce=xs.messages[0]?new Date(xs.messages[0].createdAt).toISOString():null}else return 0;if(Ze.length===0)return Li(T,{hasMore:Se,oldestCursor:D}),0;if(le.current!==S||Zs.current!==Ee)return 0;const Ne=Xr.current,ct=Ne?Ne.scrollHeight:null,wt=Hs(S)??[],es=new Set(Ze.map(xs=>xs.id));let Vt=[...Ze,...wt.filter(xs=>!es.has(xs.id))];return Vt.length>500&&(Vt=Vt.slice(-500)),z(S,Vt),Li(T,{hasMore:Se,oldestCursor:Ce}),ct!==null&&(Wd.current={key:Zs.current,scrollHeight:ct}),Rs(Vt),Ze.length}catch{return 0}finally{Sg(!1)}})();Gl.current=se;try{return await se}finally{Gl.current=null}},[he,yt,e?.id,Zt,Hs,z,zt,Li]);zd.current=dO;const tu=w.useRef(!1),Ik=w.useCallback(S=>{Ek(),!tu.current&&(tu.current=!0,requestAnimationFrame(()=>{tu.current=!1,S.target.scrollTop<100&&zd.current?.()}))},[]);w.useEffect(()=>{if(t)return;const S=Aa(he,ge,yt,Zt),T=le.current;le.current=S,T&&T!==S&&(Yo.set(T,qs),it&&Jm(T)&&Oe(T,it),Pn(po(T,it))),T!==S&&(ar(),Cn(!1),no.current=0,ma(0),Kn(!1),Ad(""),ia(-1));const j=Hs(S),D=Yo.get(S),F=un.get(S)??(ge?Pg(ge)??void 0:void 0),G=F??it,se=he!=="direct"?xr(S):Cs.isStreaming(G),Ee=G??S,Ze=Gn.get(Ee)??[];dn(se?Ze:[]),Qi(se),he==="direct"&&ge&&eu(ge),D&&D.length>0&&Ys(D),xn(!1);const Se=LP(oi.current,{chatMode:he,agentId:ge});if(j!==void 0&&j.length>0)if(se||zt.completeLoad(S),Wr(!1),Rs(j),F!==void 0&&(la(S,F),pa(po(S,F))),(!D||D.length===0)&&Ys([]),he==="channel"||he==="dm"){const Ne=he==="dm"?Kl(e?.id??"",Zt):yt;ac(Ne,S)}else he==="direct"&&ge&&F&&F!==lt&&!Se&&(se?Qn(ge,F,S):lc(F,S).then(()=>{le.current===S&&ge&&Qn(ge,F,S)}));else if(ut(S),Wr(!0),Rs([]),z(S,[]),he==="channel"||he==="dm"){const Ne=he==="dm"?Kl(e?.id??"",Zt):yt;ac(Ne,S),(!D||D.length===0)&&Ys([])}else he==="direct"&&ge?eu(ge).then(Ne=>{if(le.current===S)if(Ne.length>0){const ct=Ne.find(Ms=>Ms.isMain),wt=Sd(ge),es=ct?[ct,...Ne.filter(Ms=>!Ms.isMain&&!wt.has(Ms.id)).slice(0,4)]:Ne.filter(Ms=>!wt.has(Ms.id)).slice(0,5);let Vt=D&&D.length>0?D:es;const xs=Pg(ge),bs=F!==void 0?F:xs??ct?.id??Vt[0].id;if(bs&&bs!==lt&&!Vt.some(Ms=>Ms.id===bs)){const Ms=Ne.find(fu=>fu.id===bs);Ms&&(Vt=[...Vt,Ms])}const jr=bs&&Vt.some(Ms=>Ms.id===bs)?bs:Vt[0].id,ci=oi.current;if(ci&&ci.mode==="direct"&&ci.agentId===ge&&(ci.sessionId||ci.preferMain)){Ys(Vt);return}la(S,jr),pa(po(S,jr)),Ko(ge,jr),Ys(Vt),lc(jr,S).then(()=>{le.current===S&&ge&&Qn(ge,jr,S)})}else la(S,null),Wr(!1),(!D||D.length===0)&&Ys([])}).catch(()=>{le.current===S&&Wr(!1)}):Wr(!1)},[t,he,ge,yt,Zt,n.language,i]),w.useEffect(()=>t?void 0:Rt.on("chat:message",T=>{const j=T.payload,D=j.channel??"";if(!D)return;const F=j.senderType??"agent",G=j.text??j.message??"",se=j.senderId??j.agentId??"",Ee=j.senderName??j.agentId??i("page.fallbackAgent"),Ze=j.metadata,Se=j.messageId??j.id??"";if(Se&&ln.current.has(Se))return;const Ce=F==="human"&&se===(e?.id??""),Ne={id:Se||`ws_${Date.now()}_${se}`,sender:Ce?"user":"agent",text:G,time:new Date().toLocaleTimeString(),rawCreatedAt:T.timestamp??new Date().toISOString(),agentName:Ce?void 0:Ee,agentId:Ce?void 0:se,replyToId:j.replyToId??void 0,replyToSender:j.replyToSender??void 0,replyToText:j.replyToText??void 0};if(Ze&&F==="agent"){const wt=[];if(Ze.thinking?.length&&wt.push({type:"text",content:"",thinking:Ze.thinking.join(`
88
+ `,children:[c.jsxs("div",{className:"@2xl:hidden sticky top-0 z-10 -mx-3 mb-2 px-3 py-2 bg-surface-primary border-b border-border-default flex items-center gap-2",children:[c.jsx("span",{className:"text-[11px] font-medium text-fg-secondary truncate flex-1",children:ze?.name||(ze?.key?S0(ze.key):"")}),c.jsx("button",{onClick:()=>V(!1),className:"text-fg-tertiary hover:text-fg-primary text-sm px-1","aria-label":i("common:close"),children:"✕"})]}),(()=>{const ce=Ie.flatMap(xe=>xe.decisions??[]);if(ce.length===0)return null;const et=new Map;for(const xe of ce){const gt=et.get(xe.decisionType);gt?gt.push(xe):et.set(xe.decisionType,[xe])}return c.jsxs("div",{className:"mb-2 rounded-lg border border-border-subtle bg-surface-elevated/40 px-2 py-1.5",children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-tertiary mb-1",children:i("agent:profilePage.mind.roundDecisions","本轮决策")}),c.jsx("div",{className:"space-y-0.5",children:[...et.entries()].map(([xe,gt])=>c.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]",children:[c.jsx("span",{className:"shrink-0 font-medium text-fg-primary",children:xe}),c.jsxs("span",{className:"shrink-0 tabular-nums text-fg-tertiary",children:["×",gt.length]}),c.jsx("span",{className:"truncate text-fg-secondary",title:gt[0]?.reasoning??"",children:gt[0]?.reasoning??""})]},xe))})]})})(),Ie.length===0&&X.length>0&&c.jsx("p",{className:"text-xs text-fg-tertiary py-6 text-center",children:ze&&ze.key.startsWith("channel:loop_")?i("agent:profilePage.mind.loopIdle","这段时间没有需要它判断的信号 —— 它在睡或已完成处置"):i("agent:profilePage.mind.unitEmpty","这个实体目前没有记录")}),Ie.map(ce=>{const et=k===ce.id,xe=zc(ce.sourceType),gt=zv(ce,i),He=zI({itemStatus:ce.status,agentRunning:dt,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:ce.id}),Ct=ce.metadata?.senderName,vt=ce.metadata?.senderRole,de=P===ce.id;return c.jsxs("div",{id:`mbx-${ce.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${de?"border-brand-500 ring-1 ring-brand-500/40":ce.status==="bounced"||ce.status==="catch_all"?"border-border-subtle border-l-2 border-l-red-500":"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:()=>{const we=et?null:ce.id;C(we),we&&ce.contentTruncated&&!Xe[we]&&ft(we)},children:[c.jsx("span",{className:"hidden @sm:inline text-xs mt-0.5 text-fg-tertiary",children:et?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${He==="stale"?"bg-amber-400/70":f3[ce.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:xe}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:`text-xs font-medium text-fg-primary break-words ${et?"":"truncate"}`,children:gt.title}),gt.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 break-words ${et?"":"truncate"}`,children:gt.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap items-center",children:[c.jsx("span",{children:UI(ce.queuedAt)}),ce.completedAt&&c.jsxs("span",{children:["→ ",HI(ce.completedAt)]}),ce.activity&&c.jsxs(c.Fragment,{children:[ce.activity.totalTokens>0&&c.jsx("span",{className:"hidden @sm:inline",children:i("agent:profilePage.mind.tokensCount",{count:Km(ce.activity.totalTokens)})}),ce.activity.totalTools>0&&c.jsx("span",{className:"hidden @sm:inline",children:i("agent:profilePage.mind.toolsCount",{count:ce.activity.totalTools})})]}),gt.badge&&c.jsx("span",{className:`font-medium ${gt.badge.color}`,children:gt.badge.label}),c.jsx("span",{className:Xv[ce.priority]??"text-fg-tertiary",children:i(`agent:profilePage.mind.priority.${Wv[ce.priority]??ce.priority}`,{defaultValue:""})})]})]}),r&&XI({agentRunning:dt,itemId:ce.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:ce.status})&&c.jsxs("button",{onClick:we=>{we.stopPropagation(),W(ce.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")]})]}),et&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:c.jsx("span",{className:"bg-surface-overlay px-1.5 py-0.5 rounded",children:ce.sourceType})}),Ct&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Ct}),vt&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",vt,")"]})]}),["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(ce.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:Xe[ce.id]??ce.payload?.content??c.jsx("span",{className:"text-fg-tertiary",children:i("agent:profilePage.mind.loadingContent","正在载入完整正文…")})}),ce.decisions&&ce.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:ce.decisions.map(we=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${h3[we.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:we.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:we.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(we.createdAt).toLocaleTimeString()})]},we.id))})]}),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:U===ce.id,onClick:()=>{_e(ce.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")})})]}),ce.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:ce.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${ce.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:ce.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),ce.activity.type==="task"&&ce.payload?.taskId?c.jsx(l3,{taskId:ce.payload.taskId,isLive:qO(ce.activity,te)}):c.jsx(c3,{agentId:s,activityId:ce.activity.id,isLive:qO(ce.activity,te)})]}):He==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):He==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):ce.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},ce.id)}),Ie.length>Fe&&c.jsx("button",{onClick:()=>Ue(ce=>ce+Te),className:"w-full text-center text-[11px] text-brand-400 hover:text-brand-300 py-2",children:i("agent:profilePage.mind.showMoreCount",{count:Ie.length-Fe})})]})]})})})()]}),R&&c.jsx(qo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const ye=R;W(null),ne.agents.cancelProcessing(s,{itemId:ye}).then(()=>{let ze=0;const Ie=()=>{ze+=1,me(),ze<8&&window.setTimeout(Ie,750)};Ie()}).catch(()=>{me()})},onCancel:()=>W(null)})]})}function qv({agentId:s}){const{t:e}=Tt(["agent","common"]),t=zo(),r=H_(()=>ne.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(GP(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:l});return}gr.navigate(Ut.DELIVERABLES,{openDeliverable:l.id})},[t]);return w.useEffect(()=>{const l=Rt.on("deliverable:created",()=>a()),h=Rt.on("deliverable:updated",()=>a()),u=Rt.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(sy,{variant:"inline",subject:e("common:deliverables"),error:r.resource.error??e("common:readFailed"),notEquals:e("agent:profilePage.noDeliverables"),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=$C[l.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=NO[l.status]??NO.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 g3=w.lazy(()=>ry(()=>import("./MarkdownMessage-B-9NMrYX.js"),__vite__mapDeps([0,1,2])).then(s=>({default:s.MarkdownMessage}))),vg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Zv={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Vv({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Tt(["team","common","work","agent"]),[o,l]=w.useState(null),[h,u]=w.useState(!0),[d,f]=w.useState(!0),[p,v]=w.useState(null),[b,O]=w.useState("overview"),g=r&&i?i:b,[m,x]=w.useState(""),[y,k]=w.useState(""),[C,P]=w.useState(!1),[_,Q]=w.useState(!1),[E,A]=w.useState(""),[N,R]=w.useState(""),W=w.useRef(null),H=w.useRef(null),Z=w.useRef(null),B=w.useRef(null),[K,$]=w.useState(!1),[I,X]=w.useState(!1),[q,ie]=w.useState(""),[pe,$e]=w.useState(""),[re,U]=w.useState(!1),[M,te]=w.useState([]),Y=w.useRef(null),ae=w.useCallback(async()=>{try{const Xe=(await ne.teams.list()).teams.find(ft=>ft.id===s);Xe&&l(Xe);const Ke=await ne.teams.status(s);te(Ke.agents)}catch{}finally{u(!1)}},[s]),ee=w.useCallback(async()=>{f(!0);try{const V=await ne.teams.getFile(s,"ANNOUNCEMENT.md");x(V.content)}catch{x("")}try{const V=await ne.teams.getFile(s,"NORMS.md");k(V.content)}catch{k("")}finally{f(!1)}},[s]);w.useEffect(()=>{O("overview"),ae(),ee()},[s,ae,ee]),w.useEffect(()=>{C&&H.current&&H.current.focus()},[C]),w.useEffect(()=>{_&&B.current&&B.current.focus()},[_]);const me=async(V,Xe)=>{$(!0);try{await ne.teams.updateFile(s,V,Xe),V==="ANNOUNCEMENT.md"?(x(Xe),P(!1)):(k(Xe),Q(!1))}catch{}$(!1)},Re=async()=>{q.trim()&&(await ne.teams.update(s,{name:q.trim()}),X(!1),ae())},_e=async()=>{await ne.teams.update(s,{description:pe}),U(!1),ae()};if(!o)return h?c.jsx(ay,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(w2,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const De=o.members.find(V=>V.agentRole==="manager"),Te=M.filter(V=>V.status!=="offline").length,Fe=V=>{const{labelKey:Xe}=vl(V);return Xe?a(Xe):V??"offline"},Ue=g==="announcements"&&C||g==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ue?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ue?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[g==="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:a("agent:profilePage.badges.manager")}),c.jsx("div",{className:"text-sm font-medium",children:De?.name??o.managerName??a("common: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:a("team:teamProfile.teamId")}),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:a("team:page.members")}),o.members.map(V=>{const Xe=M.find(mt=>mt.id===V.id),Ke=Zv[Xe?.status??"offline"]??"bg-gray-500",ft=V.type==="agent";return c.jsxs("div",{onClick:()=>ft&&n?.(V.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ft&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Is,{name:V.name,avatarUrl:V.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:V.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Fe(Xe?.status)}),V.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:a("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[V.role," · ",V.type]})]}),ft&&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"})})]},V.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("team:teamProfile.noMembers")})]})]}),g==="announcements"&&c.jsx(Zc,{content:m,draft:E,setDraft:A,editing:C,setEditing:P,textareaRef:H,contentRef:W,saving:K,onSave:()=>me("ANNOUNCEMENT.md",E),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),g==="norms"&&c.jsx(Zc,{content:y,draft:N,setDraft:R,editing:_,setEditing:Q,textareaRef:B,contentRef:Z,saving:K,onSave:()=>me("NORMS.md",N),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:d}),g==="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:a("team:modals.createTeam.teamName")}),I?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:q,onChange:V=>ie(V.target.value),onKeyDown:V=>V.key==="Enter"&&Re(),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:Re,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common: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:a("common:cancel")})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{ie(o.name),X(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:a("work:project.description")}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:pe,onChange:V=>$e(V.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:_e,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common:save")}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:a("common:cancel")})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||a("work:task.noDescription")}),c.jsx("button",{onClick:()=>{$e(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]})]}),c.jsx(Fv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ve=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ve?"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.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:a("common:units.members",{count:o.members.length})}),c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:a("team:teamProfile.onlineCount",{count:Te})})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||a("work:task.noDescription")})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:V}=await ne.teams.getFilesMap(o.id),Xe=o.members.filter(ft=>ft.type==="agent"),Ke={type:"team",name:ty(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:Xe.map(ft=>({name:ft.name,roleName:ft.role,role:ft.agentRole??"worker",count:1,skills:[]}))}};await ap.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:Ke,files:V}),v({title:"Hub",message:a("agent:profilePage.publishSuccess",{name:o.name}),variant:"primary"})}catch(V){v({title:"Hub",message:a("agent:profilePage.publishFailed",{error:String(V)}),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:a("common:publishToHub"),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:vg.map(V=>c.jsxs("button",{onClick:()=>O(V.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===V.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[V.icon," ",a(V.labelKey)]},V.key))})]}),c.jsxs("div",{className:`${ve?"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:a("agent:profilePage.badges.manager")}),c.jsx("div",{className:"text-sm font-medium",children:De?.name??o.managerName??a("common: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:a("team:teamProfile.teamId")}),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:a("team:page.members")}),o.members.map(V=>{const Xe=M.find(mt=>mt.id===V.id),Ke=Zv[Xe?.status??"offline"]??"bg-gray-500",ft=V.type==="agent";return c.jsxs("div",{onClick:()=>ft&&n?.(V.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${ft&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Is,{name:V.name,avatarUrl:V.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:V.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:Fe(Xe?.status)}),V.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:a("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[V.role," · ",V.type]})]}),ft&&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"})})]},V.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(Zc,{content:m,draft:E,setDraft:A,editing:C,setEditing:P,textareaRef:H,contentRef:W,saving:K,onSave:()=>me("ANNOUNCEMENT.md",E),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:d}),b==="norms"&&c.jsx(Zc,{content:y,draft:N,setDraft:R,editing:_,setEditing:Q,textareaRef:B,contentRef:Z,saving:K,onSave:()=>me("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:a("team:modals.createTeam.teamName")}),I?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:q,onChange:V=>ie(V.target.value),onKeyDown:V=>V.key==="Enter"&&Re(),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:Re,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common: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:a("common:cancel")})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{ie(o.name),X(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:a("work:project.description")}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:pe,onChange:V=>$e(V.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:_e,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-on-brand",children:a("common:save")}),c.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:a("common:cancel")})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||a("work:task.noDescription")}),c.jsx("button",{onClick:()=>{$e(o.description??""),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:edit")})]})]})]}),c.jsx(Fv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(qo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Zc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:u,loading:d}){const{t:f}=Tt(["common"]);return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:p=>t(p.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:p=>{p.key==="Escape"&&(p.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:f("common: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:p=>{p.key==="Enter"&&(t(s),i(!0))},children:d&&!s.trim()?c.jsx(ly,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(w.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:f("common:loading")}),children:c.jsx(g3,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:u})})}function Fv({teamId:s,teamName:e,onDeleted:t}){const{t:r}=Tt(["team","common","work"]),[i,n]=w.useState(!1),[a,o]=w.useState(!1),[l,h]=w.useState(!1),[u,d]=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:r("work:project.dangerZone")}),i?c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:r("team:teamProfile.deleteTeamConfirm",{name:e})}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:f=>h(f.target.checked),className:"rounded"}),r("team:modals.deleteTeam.deleteMembers")]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:a,onChange:f=>o(f.target.checked),className:"rounded"}),r("team:modals.deleteTeam.purgeFiles")]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:u,onClick:async()=>{d(!0);try{await ne.teams.delete(s,l,{purgeFiles:a}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:r(u?"common:deleting":"common:confirmDelete")}),c.jsx("button",{onClick:()=>n(!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:r("common:cancel")})]})]}):c.jsx("button",{onClick:()=>n(!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:r("team:contextMenu.deleteTeam")})]})}const O3=["chat","overview","deliverables"],x3=["chat","overview","announcements","norms","settings"];function b3(s,e){if(s==="chat")return e("page.chatTitle");if(bg.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=vg.find(i=>i.key===s);return r?e(r.labelKey):s}function v3(s){if(s==="chat")return"💬";const e=bg.find(r=>r.key===s);if(e)return e.icon;const t=vg.find(r=>r.key===s);return t?t.icon:""}function zi(s){return s!=="chat"}function Aa(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Jm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Ns{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.isStreamLiveForSession(e,Ns.NEW_CHAT_ID)||(this.buffers.delete(Ns.NEW_CHAT_ID),this.windowBounds.delete(Ns.NEW_CHAT_ID),this.actBuffers.delete(Ns.NEW_CHAT_ID),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>Ns.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(!Jm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Ns.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Ns.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(Ns.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Jm(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(Ns.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}protectedBufferIds(){const e=new Set(this.view.values());e.add(this.viewBufferId());for(const t of this.streamingSessions.values())for(const r of t)e.add(r);for(const[t,r]of this.phase)r==="streaming"&&!this.streamingSessions.get(t)?.size&&(e.add(Ns.NEW_CHAT_ID),e.add(this.view.get(t)??t));return e}evictIfNeeded(e){if(this.buffers.size<=Ns.MAX_BUFFERS)return;const t=this.protectedBufferIds();t.add(e);for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Ns.MAX_BUFFERS)break;t.has(r)||(this.deleteBuffer(r),this.actBuffers.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>Ns.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(this.protectedBufferIds().has(r)){this.bufferOrder.push(r);break}this.deleteBuffer(r),this.actBuffers.delete(r)}}}const lt=Ns.NEW_CHAT_ID;function y3(s){const e=w.useRef(new Ns),[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(E=>E+1),[]),d=w.useCallback(E=>e.current.getStreamSessions(E),[]),f=w.useCallback((E,A)=>{e.current.addStreamSession(E,A)&&u()},[u]),p=w.useCallback((E,A)=>{e.current.removeStreamSession(E,A)&&u()},[u]),v=w.useCallback((E,A)=>e.current.setActiveSession(E,A),[]),b=w.useCallback(E=>e.current.clearActiveSession(E),[]);w.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const O=w.useCallback((E,A,N)=>{const R=e.current.updateMessages(E,A,N);R.displayChanged&&R.newMessages&&r(R.newMessages)},[]),g=w.useCallback((E,A,N)=>{e.current.updateMessages(E,A,N).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const W=e.current.getMessages(E);W&&e.current.currentConvKey===E&&r([...W])}))},[]),m=w.useCallback((E,A,N)=>{const R=e.current.appendActivity(E,A,N);R.displayChanged&&R.newActivities&&o(R.newActivities)},[]),x=w.useCallback(E=>e.current.getPhase(E),[]),y=w.useCallback(E=>e.current.beginLoad(E),[]),k=w.useCallback(E=>{e.current.beginStream(E)},[]),C=w.useCallback(E=>{e.current.endStream(E)},[]),P=w.useCallback((E,A)=>{e.current.abortStream(E,A)&&u(),e.current.currentConvKey===E&&(n(!1),o([]))},[u]),_=w.useCallback((E,A)=>{e.current.resetConv(E,A)},[]),Q=w.useCallback(async(E,A,N)=>{e.current.loadingSession=E,e.current.beginLoad(A);try{const R=await N(),W=e.current.applyLoadResult(A,E,R.messages);return W.displayChanged&&W.newMessages&&r(W.newMessages),{count:R.messages.length,hasMore:R.hasMore,oldestCursor:R.oldestCursor}}catch{return e.current.currentConvKey===A&&e.current.getPhase(A)!=="streaming"&&(r([]),e.current.completeLoad(A)),{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(E){e.current.currentConvKey=E}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(E){e.current.loadingSession=E}}},updateConvMsgs:O,updateConvMsgsRaf:g,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:Q,setActiveSession:v,clearActiveSession:b,incrementSending:E=>e.current.incrementSend(E),decrementSending:E=>e.current.decrementSend(E),resetSending:E=>e.current.resetSend(E),isSendingFor:E=>e.current.isSending(E),setStreamSession:f,clearStreamSession:p,getStreamSession:d,saveSessionToCache:(E,A)=>e.current.saveToCache(),restoreSessionFromCache:(E,A)=>{const N=e.current.restoreFromCache(E,A);return r(N??[]),N},readConvMsgs:E=>e.current.getMessages(E),readSessionMsgs:E=>e.current.buffers.get(E),writeConvMsgs:(E,A)=>{const N=e.current.updateMessages(E,()=>A);N.displayChanged&&N.newMessages&&r(N.newMessages)}}}function Nf(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function Uv(){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 S3(s){const e=w.useRef(new Map),t=w.useRef(new Map),r=Ue=>{if(Ue)for(const[ve,V]of e.current)V===Ue&&e.current.delete(ve)},i=Ue=>{if(Ue)for(const[ve,V]of t.current)V===Ue&&t.current.delete(ve)},n=Ue=>{const ve=e.current.get(Ue);ve&&(ve.abort(),e.current.delete(Ue));const V=t.current.get(Ue);V&&(V.abort(),t.current.delete(Ue))},a=Ue=>{const ve=e.current.get(lt);ve&&e.current.size===1&&(e.current.delete(lt),e.current.set(Ue,ve))},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,readSessionMsgs:O,currentConvKeyRef:g,updateConvMsgs:m,updateConvMsgsRaf:x,appendConvActivity:y,beginStream:k,endStream:C,abortStream:P,clearStreamSession:_,setStreamSession:Q,getStreamSession:E,setActiveSession:A,incrementSending:N,decrementSending:R,loadAndDisplay:W,sessionSwitchSeqRef:H,setSending:Z,setActivities:B,setInput:K,setChatContext:$,setPendingImages:I,setMentionDropdown:X,setChatReplyTo:q,setActiveSessionId:ie,setStoredActiveSession:pe,setOpenSessionTabs:$e,setSessions:re,setLoadingChat:U,setWindowBounds:M,makeConvKey:te,makeDmChannel:Y,addRecentMsgId:ae,resumeChatScrollFollow:ee,loadSessions:me}=s,{t:Re}=s,_e=w.useCallback(async(Ue,ve)=>{const V=H.current,Xe=g.current===ve&&(b(ve)?.length??0)===0;Xe&&U(!0);try{const{count:Ke,hasMore:ft,oldestCursor:mt}=await W(Ue,ve,async()=>{const _t=await ne.sessions.getMessages(Ue,50);return{messages:_t.messages.map(mh).filter(dt=>dt.sender!=="agent"||dt.text||dt.segments&&dt.segments.length>0||dt.isStreaming),hasMore:_t.hasMore,oldestCursor:_t.messages[0]?new Date(_t.messages[0].createdAt).toISOString():null}});return M(Ue,{hasMore:ft,oldestCursor:mt}),Ke}finally{Xe&&g.current===ve&&H.current===V&&U(!1)}},[W,b,H]),De=()=>{const Ue=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ue){const ve=Nf(f.current.activeSessionId,lt);ve.kind==="cancel"&&ne.agents.cancelProcessing(Ue,ve.target).catch(()=>{})}n(f.current.activeSessionId??lt),Ue&&f.current.activeSessionId&&f.current.activeSessionId!==lt&&l.current.add(f.current.activeSessionId),P(g.current,f.current.activeSessionId)},Te=w.useCallback(async(Ue,ve,V)=>{if(!Ue||!ve||ve===lt||l.current.has(ve))return;let Xe=null;try{const Ke=e.current.get(ve);if(Ke&&!Ke.signal.aborted&&E(V)?.has(ve)){g.current===V&&Z(!0);return}const ft=()=>{KC({liveSessions:E(V),sessionId:ve,placeholderId:lt})&&(_(V,ve),g.current===V&&(Z(!1),m(V,ue=>gu(ue),ve)))},mt=`${Ue}:${ve}`,_t=o.current.get(mt)??0;if(Date.now()-_t<1500)return;o.current.set(mt,Date.now());let Xt;const dt=await ne.sessions.streamStatus(Ue,ve);dt.messageId&&(Xt=dt.messageId);const Dt=O(ve)??[],Me=dt.status==="streaming",jt=JC(Dt,{expectedMessageId:dt.messageId,allowCurrentTurnPartial:Me}),ye=!!dt.active&&(dt.status==="done"||dt.status==="error")&&!!jt?.isStreaming;if(O0({aborted:!1,sawTerminal:ye,serverStatus:x0(dt.status)})==="finalize"){ft();return}o.current.set(mt,Date.now());for(const ue of t.current.values())ue.abort();t.current.clear(),Xe=new AbortController,t.current.set(ve,Xe),k(V),Z(!0),Q(V,ve);const Ie=jt&&!jt.isError&&jt.sender==="agent"?Dt.findIndex(ue=>ue.id===jt.id):-1,ce=Ie>=0?Dt[Ie]:void 0,et=e2(dt);if(!ce&&!et){ft();return}const xe=ce?ce.id:et;if(!ce)m(V,ue=>[...ue,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ve);else{const ue=(ce.segments??[]).filter(Le=>Le.type==="tool").map(Le=>Le.status==="stopped"||Le.status==="running"?{...Le,status:"running"}:Le);m(V,Le=>Le.map(ke=>ke.id===xe?{...ke,text:"",isStreaming:!0,isStopped:!1,segments:ue,committedSegments:void 0}:ke),ve)}const gt=ue=>{g.current===V&&(d.current=Date.now(),x(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(J=>J.id===xe):-1,Ye=nt>=0?nt:ke.map((J,je)=>({m:J,j:je})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];return ke[Ye]={...Je,text:(Je.text??"")+ue,segments:ZO(Je.segments??[],ue),isStreaming:!0},ke},ve))},He=ue=>{g.current===V&&(d.current=Date.now(),x(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(J=>J.id===xe):-1,Ye=nt>=0?nt:ke.map((J,je)=>({m:J,j:je})).reverse().find(J=>J.m.sender==="agent"&&J.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];return ke[Ye]={...Je,segments:VO(Je.segments??[],ue),isStreaming:!0},ke},ve))},Ct=ue=>{if(g.current===V&&(d.current=Date.now(),ue.phase!=="heartbeat")){if((ue.phase==="start"||ue.phase==="end")&&y(V,{...ue,phase:ue.phase,ts:Date.now()},ve),ue.phase==="start"){const Le=`${ue.tool}_${Date.now()}`,ke=new Date().toISOString(),nt=Ye=>{const Je=[...Ye];for(let J=Je.length-1;J>=0;J--){const je=Je[J];if(je.type==="tool"&&je.tool===ue.tool&&(je.status==="running"||je.status==="stopped"))return Je[J]={...je,status:"running",args:ue.arguments??je.args},Je}return Je.push({type:"tool",key:Le,tool:ue.tool,status:"running",args:ue.arguments,createdAt:ke}),Je};m(V,Ye=>{const Je=[...Ye],J=xe?Je.findIndex(Pe=>Pe.id===xe):-1;if(J<0)return Ye;const je=nt(Je[J].segments??[]),Qe=Je[J].committedSegments,be=Qe&&nt(Qe);return Je[J]={...Je[J],segments:je,committedSegments:be,isStreaming:!0},Je},ve)}else if(ue.phase==="end"){const Le=new Date().toISOString(),ke=nt=>{const Ye=[...nt];for(let Je=Ye.length-1;Je>=0;Je--){const J=Ye[Je];if(J.type==="tool"&&J.tool===ue.tool&&(J.status==="running"||J.status==="stopped")){Ye[Je]={...J,status:ue.success===!1?"error":"done",args:ue.arguments??J.args,result:ue.result,error:ue.error,durationMs:ue.durationMs,liveOutput:void 0,createdAt:Le};break}}return Ye};m(V,nt=>{const Ye=[...nt],Je=xe?Ye.findIndex(be=>be.id===xe):-1;if(Je<0)return nt;const J=ke(Ye[Je].segments??[]),je=Ye[Je].committedSegments,Qe=je&&ke(je);return Ye[Je]={...Ye[Je],segments:J,committedSegments:Qe,isStreaming:!0},Ye},ve)}else if(ue.phase==="subagent_progress"&&ue.subagentEvent){const Le=ke=>{const nt=[...ke];for(let Ye=nt.length-1;Ye>=0;Ye--){const Je=nt[Ye];if(Je.type==="tool"&&(Je.tool==="spawn_subagent"||Je.tool==="spawn_subagents")&&(Je.status==="running"||Je.status==="stopped")){nt[Ye]={...Je,status:"running",subagentLogs:FO(Je.subagentLogs,ue.subagentEvent)};break}}return nt};x(V,ke=>{const nt=[...ke],Ye=xe?nt.findIndex(Qe=>Qe.id===xe):-1;if(Ye<0)return ke;const Je=Le(nt[Ye].segments??[]),J=nt[Ye].committedSegments,je=J&&Le(J);return nt[Ye]={...nt[Ye],segments:Je,committedSegments:je,isStreaming:!0},nt},ve)}}},vt=ue=>{g.current===V&&(d.current=Date.now(),m(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(Je=>Je.id===xe):-1;if(nt<0)return Le;const Ye=[...ke[nt].committedSegments??[]];if(ue.type==="thinking_commit")Ye.push({type:"text",content:"",thinking:ue.content,createdAt:ue.createdAt});else if(ue.type==="text_commit")Ye.push({type:"text",content:ue.content,createdAt:ue.createdAt});else return Le;return ke[nt]={...ke[nt],committedSegments:Ye,isStreaming:!0},ke},ve))},de=ue=>{if(g.current!==V)return;d.current=Date.now();const Le=(ue.segments??[]).map((ke,nt)=>ke.type==="tool"?{type:"tool",key:`${ke.tool}_${nt}`,tool:ke.tool??"tool",status:ke.status==="error"?"error":ke.status==="running"||ke.status==="stopped"?"running":"done",args:ke.arguments,result:ke.result,error:ke.error,durationMs:ke.durationMs,createdAt:ke.createdAt,...ke.subagentLogs?.length?{subagentLogs:ke.subagentLogs}:{}}:{type:"text",content:ke.content??"",thinking:ke.thinking,createdAt:ke.createdAt});m(V,ke=>{const nt=[...ke],Ye=xe?nt.findIndex(Je=>Je.id===xe):-1;return Ye<0?ke:(nt[Ye]={...nt[Ye],text:ue.content||nt[Ye].text,segments:Le,committedSegments:Le,isStreaming:!0,isStopped:!1},nt)},ve);for(const ke of Le)ke.type==="tool"&&y(V,{tool:ke.tool,phase:ke.status==="running"||ke.status==="stopped"?"start":"end",success:ke.status!=="error",arguments:ke.args,result:ke.result,error:ke.error,durationMs:ke.durationMs,ts:Date.now()},ve)},we=8;let oe=null;const st=ue=>{g.current===V&&m(V,Le=>{const ke=Le.map((Ye,Je)=>({m:Ye,j:Je})).reverse().find(Ye=>Ye.m.sender==="agent"&&Ye.m.isStreaming)?.j??-1;if(ke<0||Le[ke].reconnecting===ue)return Le;const nt=[...Le];return nt[ke]={...nt[ke],reconnecting:ue},nt},ve)};for(let ue=1;ue<=we;ue++){if(Xe.signal.aborted)return;try{oe=await ne.sessions.reattachStream(Ue,ve,{onChunk:gt,onThinking:He,onActivity:Ct,onCommit:vt,onSnapshot:de},Xe.signal,0)}catch(ke){if(Xe.signal.aborted)throw ke;oe=null}if(!oe||!oe.attached){oe=null;break}if(oe.terminal)break;st(!0);const Le=await ne.sessions.streamStatus(Ue,ve).catch(()=>null);if(Le?.messageId&&(Xt=Le.messageId),!Le||!Le.active||Le.status==="not_found"||Le.status==="idle"){st(!1),oe=null;break}await new Promise(ke=>setTimeout(ke,Math.min(800*ue,4e3))),st(!1)}if(!oe){C(V),_(V,ve),g.current===V&&(Z(!1),Xt&&xe&&m(V,ue=>_a(ue,xe,Xt),ve),_e(ve,V).catch(()=>{}).finally(()=>{m(V,ue=>gu(ue,"done"),ve)})),i(Xe);return}if(g.current===V){let ue;m(V,Le=>{const ke=[...Le],nt=xe?ke.findIndex(je=>je.id===xe):-1,Ye=nt>=0?nt:ke.map((je,Qe)=>({m:je,j:Qe})).reverse().find(je=>je.m.sender==="agent"&&je.m.isStreaming)?.j??-1;if(Ye<0)return Le;const Je=ke[Ye];if(!Je.isStreaming)return Le;ue=Je.id;const J=oe.segments?.length?UO(oe.segments,Je.segments):void 0;return ke[Ye]={...Je,text:oe.content||Je.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...J?{segments:J,committedSegments:J}:{}},ke},ve),ue&&m(V,Le=>_a(Le,ue,oe.messageId),ve),Z(!1)}C(V),_(V,ve),i(Xe)}catch(Ke){const ft=Xe?[...t.current.values()].includes(Xe):!1;i(Xe),C(V);const mt=l.current.has(ve);if(mt&&_(V,ve),g.current===V&&(Z(!1),ft&&mt&&m(V,_t=>gu(_t),ve)),Ke instanceof Error&&Ke.name==="AbortError")return}},[y,k,C,E,b,Q,m,x]),Fe=w.useCallback(async(Ue,ve)=>{const V=f.current,Xe=rP({text:V.input,chips:V.chatContext??[]}),Ke=Ue?Ue.trim():Xe.text,ft=Ue?Ue.trim():Xe.titleSource,mt=Ue?void 0:Xe.chips.length>0?Xe.chips:void 0;if(!Ke&&V.pendingImages.length===0||V.chatMode==="direct"&&!V.selectedAgent)return;ee();const _t=Date.now(),Xt=h.current;if(!ve?.isRetry&&!ve?.isResume&&Ke&&Xt&&Xt.text===Ke&&_t-Xt.at<1500)return;if(h.current={text:Ke,at:_t},ve?.isResume){const Ie=ve.sessionIdOverride??V.activeSessionId??"";if(_t-(u.current.get(Ie)??0)<2e3)return;u.current.set(Ie,_t)}if(V.chatMode==="direct"){if(t2({authorityStreaming:Cs.isServerConfirmedStreaming(V.activeSessionId),sendSessionId:V.activeSessionId})){const ce=g.current;if([...b(ce)??[]].reverse().find(He=>He.sender==="user")?.text===Ke&&!ve?.isRetry&&!ve?.isResume){n(V.activeSessionId??lt);const He=Nf(V.activeSessionId,lt);return He.kind==="cancel"&&ne.agents.cancelProcessing(V.selectedAgent,He.target).catch(()=>{}),P(ce,V.activeSessionId),m(ce,Ct=>{const vt=[...Ct];return vt.length>0&&vt[vt.length-1].sender==="agent"&&vt.pop(),vt.length>0&&vt[vt.length-1].sender==="user"&&vt[vt.length-1].text===Ke&&vt.pop(),vt}),await new Promise(Ct=>setTimeout(Ct,50)),Fe(Ke,{isRetry:!0})}n(V.activeSessionId??lt);const gt=Nf(V.activeSessionId,lt);gt.kind==="cancel"&&ne.agents.cancelProcessing(V.selectedAgent,gt.target).catch(()=>{}),P(ce,V.activeSessionId),m(ce,He=>HO(He)),await new Promise(He=>setTimeout(He,50))}}else if(V.sending){n(f.current.activeSessionId??g.current);const Ie=g.current;P(Ie),m(Ie,ce=>HO(ce)),await new Promise(ce=>setTimeout(ce,50))}const dt=V.pendingImages.length>0?V.pendingImages.map(Ie=>Ie.dataUrl):void 0,Dt=V.pendingImages.length>0?V.pendingImages.map(Ie=>Ie.name):void 0,Me=te(V.chatMode,V.selectedAgent??"",V.activeChannel??"",V.activeDmUserId),jt=V.chatReplyTo;Ue||(K(""),$([])),I([]),X(!1),q(null);const ye=V.chatMode==="dm";N(Me);const ze=V.activeSessionId??Me;if(p.set(ze,[]),g.current===Me&&!ye&&(Z(!0),B([])),V.chatMode==="dm"){const Ie=Y(V.authUser?.id??"",V.activeDmUserId),ce=`opt_${Date.now()}`,et={id:ce,sender:"user",text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};dt?.length&&(et.images=dt),jt&&(et.replyToId=jt.id,et.replyToSender=jt.sender,et.replyToText=jt.text),m(Me,xe=>[...xe,et]);try{const xe=await ne.channels.sendMessage(Ie,{text:Ke,senderName:V.authUser?.name??Re("page.fallbackYou"),senderId:V.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...dt?.length?{images:dt}:{},...Dt?.length?{fileNames:Dt}:{}});xe.userMessage&&ae(xe.userMessage.id),m(Me,gt=>{const He=gt.filter(vt=>vt.id!==ce),Ct=[];return xe.userMessage&&Ct.push(Bn(xe.userMessage,V.authUser?.id)),Ct.length>0?[...He,...Ct]:gt})}catch(xe){Vc(xe)&&Fc(),DO(xe)&&(K(Ke),I(V.pendingImages)),m(Me,gt=>[...gt.filter(Ct=>Ct.id!==ce),{id:`err_${Date.now()}`,sender:"agent",text:Re("page.errorWithMessage",{message:String(xe)}),errorRaw:String(xe),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}])}R(Me),g.current===Me&&Z(!1)}else if(V.chatMode==="channel"){const Ie=`opt_${Date.now()}`,ce={id:Ie,sender:"user",text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};jt&&(ce.replyToId=jt.id,ce.replyToSender=jt.sender,ce.replyToText=jt.text),m(Me,xe=>[...xe,ce]);const et=s2(Ke);V.groupChats.find(xe=>xe.channelKey===V.activeChannel);try{const xe=await ne.channels.sendMessage(V.activeChannel,{text:Ke,senderName:V.authUser?.name??Re("page.fallbackYou"),mentions:et,senderId:V.authUser?.id,orgId:"default",replyToId:jt?.id,...dt?.length?{images:dt}:{},...Dt?.length?{fileNames:Dt}:{}});xe.userMessage&&ae(xe.userMessage.id),xe.agentMessage&&ae(xe.agentMessage.id),xe.agentStopped&&m(Me,gt=>[...gt,{id:`stopped_${Date.now()}`,sender:"agent",text:xe.notice??Re("page.agentStopped"),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}]),m(Me,gt=>{const He=gt.filter(vt=>vt.id!==Ie),Ct=[];return xe.userMessage&&Ct.push(Bn(xe.userMessage,V.authUser?.id)),xe.agentMessage&&Ct.push(Bn(xe.agentMessage,V.authUser?.id)),Ct.length>0?[...He,...Ct]:gt})}catch(xe){Vc(xe)&&Fc();const gt=DO(xe);gt&&(K(Ke),I(V.pendingImages));const He=fh(xe,Re)||Re("page.errorWithMessage",{message:String(xe)});m(Me,Ct=>[...gt?Ct.filter(de=>de.id!==Ie):Ct,{id:`err_${Date.now()}`,sender:"agent",text:He,errorRaw:String(xe),time:new Date().toLocaleTimeString(),agentName:Re("page.systemName"),isError:!0}])}R(Me),g.current===Me&&Z(!1)}else{k(Me);const Ie=ve?.isResume?b(Me)??[]:[],ce=ve?.isResume?r2(Ie):-1,et=ce>=0?Ie[ce].id:void 0,xe=et??Uv(),gt=Uv();let He=ve?.sessionIdOverride??(V.activeSessionId===lt?null:V.activeSessionId??null);if(ve?.isResume){const J=new Date().toISOString();m(Me,je=>{if(et){const Qe=je.findIndex(be=>be.id===et);if(Qe>=0)return je.map((be,Pe)=>Pe===Qe?{...be,isStreaming:!0,isStopped:!1,isError:!1}:be)}return[...je,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:J,segments:[],isStreaming:!0}]},He)}else{const J=new Date().toISOString(),je=i2({id:gt,text:Ke,time:new Date().toLocaleTimeString(),rawCreatedAt:J,chips:mt,images:dt,replyTo:jt});m(Me,Qe=>[...Qe,je,{id:xe,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:J,segments:[],isStreaming:!0}],He)}const Ct=J=>{d.current=Date.now(),x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=Qe[be];return Qe[be]={...Pe,text:(Pe.text??"")+J,segments:ZO(Pe.segments??[],J)},Qe},He)},vt=J=>{d.current=Date.now(),x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=Qe[be];return Qe[be]={...Pe,segments:VO(Pe.segments??[],J)},Qe},He)},de=J=>{if(d.current=Date.now(),J.type==="session_start"&&J.sessionId){const je=He;if(He=J.sessionId,l.current.delete(J.sessionId),je&&je!==J.sessionId&&(_(Me,je),V.selectedAgent&&je===lt&&(Cs.applyLocalOptimistic(V.selectedAgent,je,!1),Cs.applyLocalOptimistic(V.selectedAgent,J.sessionId,!0))),Q(Me,J.sessionId),J.userMessageId&&!ve?.isResume&&m(Me,Qe=>Qe.map(be=>be.id===gt?{...be,id:J.userMessageId}:be),J.sessionId),g.current===Me){const Qe=V.activeSessionId;(!Qe||Qe===lt||Qe===J.sessionId)&&(ie(J.sessionId),A(Me,J.sessionId),a(J.sessionId),V.selectedAgent&&pe(V.selectedAgent,J.sessionId),$e(be=>be.some(Pe=>Pe.id===lt)?be.map(Pe=>Pe.id===lt?{...Pe,id:J.sessionId}:Pe):be.some(Pe=>Pe.id===J.sessionId)?be:[...be,{id:J.sessionId,agentId:V.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}m(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=[...Qe[be].committedSegments??[]];return J.type==="thinking_commit"?Pe.push({type:"text",content:"",thinking:J.content,createdAt:J.createdAt}):Pe.push({type:"text",content:J.content,createdAt:J.createdAt}),Qe[be]={...Qe[be],committedSegments:Pe},Qe},He)},we=J=>{d.current=Date.now(),J.phase!=="heartbeat"&&((J.phase==="start"||J.phase==="end")&&y(Me,{...J,phase:J.phase,ts:Date.now()},He),J.phase==="start"?m(Me,je=>{const Qe=[...je],be=Qe.findIndex(Ot=>Ot.id===xe);if(be<0)return je;const Pe=[...Qe[be].segments??[]];let tt=!1;if(J.arguments)for(let Ot=Pe.length-1;Ot>=0;Ot--){const At=Pe[Ot];if(At.type==="tool"&&At.tool===J.tool&&At.status==="running"){Pe[Ot]={...At,args:J.arguments},tt=!0;break}}const pt=`${J.tool}_${Date.now()}`,Pt=new Date().toISOString();tt||Pe.push({type:"tool",key:pt,tool:J.tool,status:"running",args:J.arguments,createdAt:Pt});const kt=[...Qe[be].committedSegments??[]];return J.arguments!==void 0&&kt.push({type:"tool",key:pt,tool:J.tool,status:"running",args:J.arguments,createdAt:Pt}),Qe[be]={...Qe[be],segments:Pe,committedSegments:kt},Qe},He):J.phase==="output"?x(Me,je=>{const Qe=[...je],be=Qe.findIndex(tt=>tt.id===xe);if(be<0)return je;const Pe=[...Qe[be].segments??[]];for(let tt=Pe.length-1;tt>=0;tt--){const pt=Pe[tt];if(pt.type==="tool"&&pt.tool===J.tool&&pt.status==="running"){Pe[tt]={...pt,liveOutput:a2(pt.liveOutput,J.output??"")};break}}return Qe[be]={...Qe[be],segments:Pe},Qe},He):J.phase==="subagent_progress"&&J.subagentEvent?x(Me,je=>{const Qe=[...je],be=Qe.findIndex(Pt=>Pt.id===xe);if(be<0)return je;const Pe=Pt=>{const kt=[...Pt];for(let Ot=kt.length-1;Ot>=0;Ot--){const At=kt[Ot];if(At.type==="tool"&&(At.tool==="spawn_subagent"||At.tool==="spawn_subagents")&&At.status==="running"){kt[Ot]={...At,subagentLogs:FO(At.subagentLogs,J.subagentEvent)};break}}return kt},tt=Pe(Qe[be].segments??[]),pt=Pe(Qe[be].committedSegments??[]);return Qe[be]={...Qe[be],segments:tt,committedSegments:pt},Qe},He):m(Me,je=>{const Qe=[...je],be=Qe.findIndex(kt=>kt.id===xe);if(be<0)return je;const Pe=new Date().toISOString(),tt=[...Qe[be].segments??[]];let pt;for(let kt=tt.length-1;kt>=0;kt--){const Ot=tt[kt];if(Ot.type==="tool"&&Ot.tool===J.tool&&Ot.status==="running"){pt=Ot.subagentLogs,tt[kt]={...Ot,status:J.success===!1?"error":"done",args:J.arguments,result:J.result,error:J.error,durationMs:J.durationMs,liveOutput:void 0,createdAt:Pe};break}}const Pt=[...Qe[be].committedSegments??[]];for(let kt=Pt.length-1;kt>=0;kt--){const Ot=Pt[kt];if(Ot.type==="tool"&&Ot.tool===J.tool&&Ot.status==="running"){Pt[kt]={...Ot,status:J.success===!1?"error":"done",args:J.arguments,result:J.result,error:J.error,durationMs:J.durationMs,liveOutput:void 0,createdAt:Pe,subagentLogs:pt??Ot.subagentLogs};break}}return Qe[be]={...Qe[be],segments:tt,committedSegments:Pt},Qe},He))},oe=new AbortController;e.current.set(f.current.activeSessionId??lt,oe);const st=He,ue=st;ue&&l.current.delete(ue),ue&&Q(Me,ue),V.selectedAgent&&Cs.applyLocalOptimistic(V.selectedAgent,ue??lt,!0);try{d.current=Date.now();const J=await ne.agents.messageStream(V.selectedAgent,Ke,{onChunk:Ct,onThinking:vt,onActivity:we,onCommit:de},{signal:oe.signal,images:dt,sessionId:st,isRetry:ve?.isRetry,isResume:ve?.isResume,fileNames:Dt,replyTo:jt,titleSource:ft,chips:mt,userMessageId:gt,assistantMessageId:xe});if(g.current===Me){if(J.merged&&m(Me,Qe=>Qe.filter(be=>be.id!==xe&&be.id!==gt),He),!J.merged&&J.segments?.length&&m(Me,Qe=>{const be=[...Qe],Pe=be.findIndex(kt=>kt.id===xe);if(Pe<0)return Qe;const tt=UO(J.segments,be[Pe].segments);let pt=J.content||be[Pe].text;pt||(pt=tt.filter(kt=>kt.type==="text").map(kt=>kt.content).join(""));const Pt=J.emptyReply===!0;return be[Pe]={...be[Pe],text:pt,segments:tt,committedSegments:tt,isStopped:J.cancelled||be[Pe].isStopped,emptyReply:J.emptyReply||Pt||void 0,isError:J.emptyReply||Pt?!0:be[Pe].isError},be},He),!J.merged&&!J.segments?.length&&m(Me,Qe=>{const be=[...Qe],Pe=be.findIndex(At=>At.id===xe);if(Pe<0)return Qe;const tt=be[Pe],pt=tt.committedSegments??[],kt=pt.filter(At=>At.type==="text"&&!!At.content).map(At=>At.content).join("")||J.content||tt.text,Ot=J.emptyReply===!0;return(pt.length>0||kt||J.cancelled||J.emptyReply||Ot)&&(be[Pe]={...tt,text:kt,segments:pt.length>0?pt:tt.segments,isStopped:J.cancelled||tt.isStopped,emptyReply:J.emptyReply||Ot||void 0,isError:J.emptyReply||Ot?!0:tt.isError}),be},He),J.sessionId){ie(be=>!be||be===lt||be===J.sessionId?J.sessionId:be);const Qe=v.get(Me);(!Qe||Qe===lt||Qe===J.sessionId)&&(A(Me,J.sessionId),a(J.sessionId)),$e(be=>be.some(Pe=>Pe.id===lt)?be.map(Pe=>Pe.id===lt?{...Pe,id:J.sessionId}:Pe):be.some(Pe=>Pe.id===J.sessionId)?be:[...be,{id:J.sessionId,agentId:V.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}me(V.selectedAgent).then(Qe=>{if(g.current===Me&&(re(Qe),J.sessionId)){const be=Qe.find(Pe=>Pe.id===J.sessionId);be&&$e(Pe=>Pe.some(pt=>pt.id===be.id)?Pe.map(pt=>pt.id===be.id?be:pt):[be,...Pe.filter(pt=>pt.id!==lt)])}});const je=J.sessionId??(ue&&ue!==lt?ue:null);if(!oe.signal.aborted&&!J.merged&&(J.softDisconnected??J.segments===void 0)&&V.chatMode==="direct"&&V.selectedAgent&&je){const Qe=V.selectedAgent;let be=!1,Pe;for(let tt=0;tt<4&&!be&&(tt>0&&await new Promise(pt=>setTimeout(pt,350*tt)),!oe.signal.aborted);tt+=1)try{const pt=await ne.sessions.streamStatus(Qe,je);if(pt.messageId&&(Pe=pt.messageId),O0({aborted:oe.signal.aborted,sawTerminal:!1,serverStatus:x0(pt.status)})==="reattach"){m(Me,kt=>kt.map(Ot=>Ot.id===xe?{...Ot,isStreaming:!0,isStopped:!1,segments:(Ot.segments??[]).map(At=>At.type==="tool"&&(At.status==="stopped"||At.status==="running")?{...At,status:"running"}:At)}:Ot),je),R(Me),r(oe),Q(Me,je),C(Me),Te(Qe,je,Me),be=!0;return}break}catch{}if(!be&&!oe.signal.aborted){Pe&&xe&&m(Me,tt=>_a(tt,xe,Pe),je);try{if(await _e(je,Me)>0){R(Me),r(oe),C(Me);return}}catch{}}}}!J.merged&&(He||g.current===Me)&&m(Me,je=>_a(je,xe,J.messageId),He)}catch(J){const je=J?.sessionId;je&&V.chatMode==="direct"&&g.current===Me&&(ie(je),A(Me,je),a(je),$e(be=>be.map(Pe=>Pe.id===lt?{...Pe,id:je}:Pe)),me(V.selectedAgent).then(be=>{if(g.current!==Me)return;re(be);const Pe=be.find(tt=>tt.id===je);Pe&&$e(tt=>tt.some(Pt=>Pt.id===Pe.id)?tt.map(Pt=>Pt.id===Pe.id?Pe:Pt):[Pe,...tt])})),Vc(J)&&Fc();const Qe=fh(J,Re);Qe?m(Me,be=>{const Pe=[...be],tt=Pe.findIndex(pt=>pt.id===xe);return tt>=0&&(Pe[tt]={...Pe[tt],text:Qe,isError:!0,errorRaw:String(J)}),Pe},He):m(Me,be=>{const Pe=[...be],tt=Pe.findIndex(pt=>pt.id===xe);if(tt>=0){const pt=YO(Pe[tt],"stopped");if(pt===null)return be.filter(Pt=>Pt.id!==xe);Pe[tt]=pt}return Pe},He)}m(Me,J=>n2(J,xe),He),oe.signal.aborted&&m(Me,J=>{const je=[...J],Qe=je.findIndex(be=>be.id===xe);if(Qe>=0){const be=YO(je[Qe],"stopped");if(be===null)return J.filter(Pe=>Pe.id!==xe);je[Qe]=be}return je},He);const ke=((He?O(He):b(Me))??[]).find(J=>J.id===xe),nt=He&&He!==lt?He:V.activeSessionId&&V.activeSessionId!==lt?V.activeSessionId:null,Ye=ke?o2(ke):!1;ke&&!Ye&&V.chatMode==="direct"&&nt&&!oe.signal.aborted&&await(async(je,Qe)=>{for(let be=0;be<je;be++){const Pe=MC(be,{baseMs:Qe,maxMs:8e3,maxAttempts:je});await new Promise(tt=>setTimeout(tt,Pe));try{const pt=(await ne.sessions.getMessages(nt,2)).messages.find(Pt=>Pt.role==="assistant");if(pt?.content){const Pt=mh(pt);m(Me,kt=>{const Ot=[...kt],At=Ot.findIndex(js=>js.id===xe);return At>=0&&(Ot[At]={...Ot[At],text:Pt.text,segments:Pt.segments}),Ot},He),m(Me,kt=>_a(kt,xe,Pt.id),He);return}}catch{}}})(5,2e3);const Je=R(Me);_(Me,He??lt),V.selectedAgent&&Cs.applyLocalOptimistic(V.selectedAgent,He??lt,!1),C(Me),[...e.current.values()].includes(oe)||e.current.size===0?(r(oe),p.delete(He??Me),g.current===Me&&(Z(Je>0),Je===0&&B([]))):p.delete(He??Me)}},[y,k,_,g,R,C,N,me,b,Z,Q,f,m,x]);return{send:Fe,stopSending:De,tryReattachActiveStream:Te,loadSessionMessages:_e}}function w3({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Tt("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,O]=w.useState(null),g=w.useRef(null),m=w.useCallback(async()=>{f(!0);try{const P=await LC(),_=P.providers?.markus;if(_?.configured&&_.enabled!==!1&&(!_.models||_.models.length===0))try{const A=await fetch("/api/models/live/markus",{credentials:"include"});if(A.ok){const N=await A.json();N.models?.length&&(_.models=N.models)}}catch{}const Q=[];for(const[A,N]of Object.entries(P.providers??{})){if(!N.configured||N.enabled===!1)continue;const R=(N.models??[]).filter(Q2).map(W=>({id:W.id,name:W.name}));R.length!==0&&Q.push({provider:A,displayName:N.displayName??A,models:R})}Q.sort((A,N)=>A.displayName.localeCompare(N.displayName)),v(Q);let E=null;if(P.routingDefaultModel?.provider&&P.routingDefaultModel?.model)E={provider:P.routingDefaultModel.provider,model:P.routingDefaultModel.model};else if(P.defaultProvider){const A=P.providers?.[P.defaultProvider];A?.model&&(E={provider:P.defaultProvider,model:A.model})}O(E)}catch{v([])}finally{f(!1)}},[]);w.useEffect(()=>{m()},[m]),w.useEffect(()=>{n&&(l("agent"),u(""),m())},[n,m]),w.useEffect(()=>{if(!n)return;const P=_=>{g.current?.contains(_.target)||a(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[n]);const x=w.useMemo(()=>{const P=h.trim().toLowerCase();return p.map(_=>({..._,models:P?_.models.filter(Q=>Q.id.toLowerCase().includes(P)||(Q.name?.toLowerCase().includes(P)??!1)||_.displayName.toLowerCase().includes(P)||_.provider.toLowerCase().includes(P)):_.models})).filter(_=>_.models.length>0)},[p,h]),y=s??b,C=(y?.model?y.model.includes("/")?y.model.split("/").pop():y.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:g,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(P=>!P),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:y?`${y.provider}: ${y.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:C}),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:P=>u(P.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(t0,{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(t0,{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(P=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:P.displayName}),P.models.slice(0,80).map(_=>{const Q=y?.provider===P.provider&&y?.model===_.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:P.provider,model:_.id},o),o==="global"&&O({provider:P.provider,model:_.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 ${Q?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:_.id}),Q&&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"})})]},`${P.provider}:${_.id}`)})]},P.provider))]})]})]})}async function Hv(s,e,t){if(e==="agent"){if(!t)return;await ne.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}}),s0(t);return}t&&await ne.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:null}}).then(()=>s0(t)).catch(()=>{}),await ne.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}}),NC()}const Yv="markus_team_sidebars_c";function ep(s,e){return s.id===lt?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Gv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):ep(s,e)}const tp=new Set;function _3(){return window.location.hash}function k3(s){return tp.add(s),()=>{tp.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>tp.forEach(s=>s()));function V3({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Tt(["team","common"]),a=w.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=ip(Ut.TEAM),[l,h]=w.useState(r?.agents??[]),[u,d]=w.useState(r?.humans??[]),[f,p]=w.useState(!r),v=rp(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),O=w.useSyncExternalStore(k3,_3),g=v&&(O.startsWith(`#${Ut.TEAM}/`)||O.startsWith("#chat/")),m=v&&O.match(/^#team\/t\/(.+)$/),x=v?m?"team":g?"chat":"roster":"roster",y=m?m[1]:null;w.useEffect(()=>(IO(v&&x==="chat"),()=>IO(!1)),[v,x]),w.useEffect(()=>(BO(Ut.TEAM,v&&x!=="roster"?1:0),()=>BO(Ut.TEAM,0)),[v,x]);const k=w.useCallback(()=>{window.location.hash=`${Ut.TEAM}/d`},[]),C=w.useCallback(S=>{window.location.hash=`${Ut.TEAM}/t/${S}`},[]);w.useEffect(()=>{if(!v)return;const S=()=>{zi(Q.current)&&_("chat")};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[v]);const[P,_]=w.useState("chat"),Q=w.useRef("chat");Q.current=P;const E=WO({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[A,N]=w.useState(()=>{try{return localStorage.getItem(Yv)==="1"}catch{return!1}}),R=w.useCallback(S=>{N(S);try{localStorage.setItem(Yv,S?"1":"0")}catch{}},[]),W=zo(),H=W?.leftCollapsed??!1,Z=W?.rightPanel??null,B=W?.rightPanelTabs??[],K=W?.activeRightPanelTabId??null,$=W?.rightPanelFullscreen??!1,I=Z?"2xl:pr-8":"2xl:pr-[280px]",X=W?.setHostAvailable,q=W?.collapseRightPanelOnly??W?.toggleRightPanel,ie=W?.openRightPanel,pe=400,$e=320,re=6,[U,M]=w.useState(typeof window<"u"?window.innerWidth:1440),[te,Y]=w.useState("auto"),ae=w.useRef(H);w.useEffect(()=>{ae.current!==H&&(ae.current=H,N(H))},[H]);const ee=W?.keyboardPane??"content",me=w.useRef(!1),Re=w.useRef(ee);w.useEffect(()=>{if(t||v||!o)return;const S=Re.current;Re.current=ee,(ee==="l1"||ee==="l2")&&S!==ee&&A&&(N(!1),W?.setLeftCollapsed(!1))},[ee,t,v,o,A,W]),w.useEffect(()=>{if(t||v||!o)return;const S=T=>{const j=W?.keyboardPane??"content";if(j==="l0"||j==="l1"||j==="l2"||T.metaKey||T.ctrlKey||T.altKey)return;if(T.target instanceof HTMLElement){const F=T.target.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||T.target.isContentEditable||T.target.closest(".xterm"))return}const D=T.key.length===1?T.key.toLowerCase():T.key;D!=="h"&&D!=="ArrowLeft"||(T.preventDefault(),A&&(R(!1),W?.setLeftCollapsed(!1)),W?.setKeyboardPane(me.current?"l2":"l1"))};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,v,o,W,A,R]),w.useEffect(()=>{if(X)return X(o&&!v),()=>X(!1)},[o,v,X]),w.useEffect(()=>t||v||!o?void 0:Rt.on("ui:right_panel",T=>{const j=T.payload;if(j.action==="collapse"){q?.();return}if(j.action!=="open"||!j.panel||!ie)return;const D=j.panel;if(D.kind==="url"&&D.url){const F=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ie({kind:"url",url:D.url,title:D.title||D.url,browserId:F});return}if(D.kind==="file"&&D.path){ie({kind:"file",path:D.path,title:D.title});return}if(D.kind==="terminal"){const F=D.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ie({kind:"terminal",terminalId:F,title:D.title||"Terminal",cwd:D.cwd});return}D.kind==="deliverable"&&D.deliverableId&&ne.deliverables.get(D.deliverableId).then(F=>{F.deliverable&&ie({kind:"deliverable",deliverable:F.deliverable})}).catch(()=>{})}),[t,v,o,q,ie]);const _e=w.useCallback((S,T)=>{const j=pd.current,D=T??Ss.current?.selectionStart??j.text.length,F=hp({text:j.text,chips:j.chips},S,D);ir(F.draft.text),pn(F.draft.chips),requestAnimationFrame(()=>{const G=Ss.current;G&&(G.focus(),G.setSelectionRange(F.caret,F.caret))})},[]),De=w.useCallback(S=>{if(!S)return;let T=0;const j=C2(S,()=>`ctx_${Date.now()}_${++T}`);if(j.length===0)return;const D=pd.current,F=nP({text:D.text,chips:D.chips},j);ir(F.draft.text),pn(F.draft.chips),requestAnimationFrame(()=>{const G=Ss.current;G&&(G.focus(),G.setSelectionRange(F.caret,F.caret))})},[]),Te=w.useRef(null),[Fe,Ue]=w.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ve=WO({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),V=w.useRef(null),[Xe,Ke]=w.useState(!1),[ft,mt]=w.useState(!1),_t=w.useCallback(()=>{Xe?mt(S=>!S):Ue(S=>{const T=!S;try{localStorage.setItem("markus_team_panel_visible",String(T))}catch{}return T})},[Xe]);w.useEffect(()=>{if(v)return;const S=V.current;if(!S)return;const T=new ResizeObserver(([j])=>{if(!j)return;const D=j.contentRect.width;if(M(D),!t){const F=D-E.width-ve.width;Ke(F<400)}});return T.observe(S),()=>T.disconnect()},[v,t,E.width,ve.width]);const Xt=Fe&&!Xe&&!ft,dt=A?0:E.width+re+(Xt?ve.width+re:0),Dt=Math.max(0,U-dt-re-8),Me=Math.min(pe,Math.floor(Dt*.4)),jt=Math.max(0,Dt-Me),ye=Math.min(Math.round(Dt/2),jt),Ie=Math.max(0,Math.min(te==="auto"?ye:te,jt)),ce=w.useRef(!1);w.useEffect(()=>{const S=(W?.rightPanel??null)!==null;S&&!ce.current&&(N(!0),Y("auto")),ce.current=S},[W?.rightPanel]);const et=w.useRef(Ie);et.current=Ie;const xe=w.useRef(jt);xe.current=jt;const gt=w.useCallback(S=>{S.preventDefault();const T=S.clientX,j=et.current,D=G=>{const se=j+(T-G.clientX),Ee=xe.current,Ze=Math.min($e,Ee);Y(Math.max(Ze,Math.min(Ee,se)))},F=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",F),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",D),document.addEventListener("mouseup",F),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);w.useEffect(()=>{if(!ft)return;const S=T=>{T.target.closest("[data-l2-floating]")||mt(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[ft]);const[He,Ct]=w.useState(null),[vt,de]=w.useState(!1),we=w.useRef(null);w.useEffect(()=>{if(!vt)return;const S=j=>{we.current&&!we.current.contains(j.target)&&de(!1)},T=j=>{j.key==="Escape"&&de(!1)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",T)}},[vt]);const[oe,st]=w.useState(),[ue,Le]=w.useState(),[ke,nt]=w.useState(),[Ye,Je]=w.useState(!1),[J,je]=w.useState(""),[Qe,be]=w.useState(!1),[Pe,tt]=w.useState(""),pt=w.useRef(null),Pt=w.useRef(null),kt=w.useCallback((S,T)=>{const j=S?dh[S]:void 0,D=j?"overview":S;Le(j),st(D),nt(T),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(D??"overview")},[v]);w.useCallback(S=>{S==="profile"?kt():zi(Q.current)?history.back():_("chat")},[kt]);const Ot=w.useCallback((S,T)=>{Mt("direct"),Xs(S),v&&k(),kt(T?.tab,T?.highlightMailboxId),Ct(null)},[v,k,kt]),At=w.useCallback((S,T)=>{const j=l.find(D=>D.name.toLowerCase()===S.toLowerCase());if(j){const D=T.target.getBoundingClientRect();Ct({agentId:j.id,top:D.bottom,left:D.left})}},[l]),js=w.useMemo(()=>l.map(S=>S.name),[l]),[he,Mt]=w.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,Xs]=w.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[yt,zs]=w.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[Zt,Ti]=w.useState(""),Rl=500,ln=w.useRef(new Set),fd=S=>{if(ln.current.add(S),ln.current.size>Rl){const T=Math.floor(Rl*.2),j=ln.current.values();for(let D=0;D<T;D++){const F=j.next().value;F&&ln.current.delete(F)}}},cn=w.useMemo(()=>{if(r?.channelMessages){const S=r.activeChannel??"custom:general";return r.channelMessages.filter(T=>T.channel===S).map(T=>Bn(T))}},[]),{manager:zt,messages:ns,setMessages:Rs,sending:hs,setSending:Qi,activities:hn,setActivities:dn,activeSessionBuffer:un,actBuffers:Gn,sessionTabsBuffer:Yo,readConvMsgs:Hs,readSessionMsgs:$i,writeConvMsgs:z,setActiveSession:Oe,currentConvKeyRef:le,updateConvMsgs:Be,updateConvMsgsRaf:rt,appendConvActivity:ot,beginLoad:ut,beginStream:Lt,endStream:St,resetConv:ss,abortStream:gs,loadAndDisplay:rr,incrementSending:ni,decrementSending:Br,isSendingFor:xr,setStreamSession:us,clearStreamSession:ji,getStreamSession:md,saveSessionToCache:Kt,restoreSessionFromCache:fn}=y3(cn),[os,ir]=w.useState(""),[mn,El]=w.useState(null),[br,pn]=w.useState([]),pd=w.useRef({text:"",chips:[]});pd.current={text:os,chips:br};const[Al,Ml]=w.useState(!!r?.streamLastMessage),gn=w.useRef(null),G_=400;w.useEffect(()=>(hs?(gn.current&&(clearTimeout(gn.current),gn.current=null),Ml(!0)):Al&&(gn.current=setTimeout(()=>{Ml(!1),gn.current=null},G_)),()=>{gn.current&&clearTimeout(gn.current)}),[hs]);const gd=w.useRef({fullText:"",timers:[]});w.useEffect(()=>{if(!t||!r?.streamLastMessage||ns.length===0)return;const S=ns[ns.length-1];if(!S||S.sender!=="agent")return;const T=S.text;gd.current.fullText=T;const j=gd.current.timers;function D(){let G=0;Rs(Ee=>Ee.map((Ze,Se)=>Se===Ee.length-1?{...Ze,text:""}:Ze)),Ml(!0);const se=setInterval(()=>{if(G+=1+Math.floor(Math.random()*2),G>=T.length){clearInterval(se),Rs(Se=>Se.map((Ce,Ne)=>Ne===Se.length-1?{...Ce,text:T}:Ce));const Ee=setTimeout(()=>Ml(!1),800);j.push(Ee);const Ze=setTimeout(D,6e3);j.push(Ze)}else Rs(Ee=>Ee.map((Ze,Se)=>Se===Ee.length-1?{...Ze,text:T.slice(0,G)}:Ze))},30);j.push(se)}const F=setTimeout(D,1500);return j.push(F),()=>{j.forEach(G=>clearTimeout(G)),gd.current.timers=[]}},[]);const[K_,yg]=w.useState(!1),[Od,Sg]=w.useState(!1),[J_,wg]=w.useState(!1);w.useEffect(()=>{if(!Od){wg(!1);return}const S=setTimeout(()=>wg(!0),250);return()=>clearTimeout(S)},[Od]);const[On,Wr]=w.useState(!0),[ek,xd]=w.useState(!0),bd=w.useRef(0),[nr,Ll]=w.useState([]),[_g,kg]=w.useState(null),vd=w.useRef(null),Ss=w.useRef(null),[tk,Ri]=w.useState(null),[sk,Cg]=w.useState(0);w.useEffect(()=>$2(S=>{S===ge&&Cg(T=>T+1)}),[ge]),w.useEffect(()=>{const S=()=>Cg(T=>T+1);return window.addEventListener("focus",S),()=>window.removeEventListener("focus",S)},[]),w.useEffect(()=>{if(!ge){Ri(null);return}let S=!1;return ne.agents.get(ge).then(T=>{if(S)return;const j=T.effectiveModel;Ri(j?.provider&&j?.model?{provider:j.provider,model:j.model}:null)}).catch(()=>{S||Ri(null)}),()=>{S=!0}},[ge,sk]);const yd=w.useRef(!1),Go=w.useCallback(()=>{const S=Ss.current;if(!S)return;const T=yd.current,j=T?36:52,D=e0(T);S.style.height="auto";const F=Math.max(j,Math.min(S.scrollHeight,D));S.style.height=`${F}px`,S.style.overflowY=F>=D?"auto":"hidden"},[]);w.useEffect(()=>{const S=requestAnimationFrame(()=>Go());return()=>cancelAnimationFrame(S)},[os,nr.length,Go]);const Sd=S=>{try{const T=localStorage.getItem(`markus_closed_tabs_${S}`);return T?new Set(JSON.parse(T)):new Set}catch{return new Set}},rk=(S,T)=>{const j=Sd(S);j.add(T);try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...j]))}catch{}},ik=(S,T)=>{const j=Sd(S);if(j.delete(T))try{localStorage.setItem(`markus_closed_tabs_${S}`,JSON.stringify([...j]))}catch{}},Pg=S=>{try{return localStorage.getItem(`markus_active_session_${S}`)}catch{return null}},Ko=(S,T)=>{if(S)try{T&&T!==lt?localStorage.setItem(`markus_active_session_${S}`,T):localStorage.removeItem(`markus_active_session_${S}`)}catch{}},[Qr,Ei]=w.useState([]),[nk,Nl]=w.useState(0),[Tg,Dl]=w.useState(1),[Il,Bl]=w.useState(!1),[Wl,Qg]=w.useState(!1),[it,Ai]=w.useState(null),[Jo,xn]=w.useState(!1),[$g,bn]=w.useState(!1),[wd,jg]=w.useState(null),[_d,kd]=w.useState(""),[Rg,Cd]=w.useState([]),[vn,Xl]=w.useState(null),[ok,Eg]=w.useState(null),[ea,Pd]=w.useState([]),[yn,ta]=w.useState(null),[ak,Ag]=w.useState(null),Mg=w.useRef(new Set),[Lg,Td]=w.useState([]),[$r,sa]=w.useState(null),Mi=$r?$r.items[$r.index]??null:null,[lk,Ng]=w.useState(null),[Dg,Qd]=w.useState([]),[qs,ck]=w.useState([]),Ys=S=>{ck(T=>{const j=typeof S=="function"?S(T):S,D=new Set,F=j.filter(G=>D.has(G.id)?!1:(D.add(G.id),!0));return F.some(G=>G.isMain)?[...F.filter(G=>G.isMain),...F.filter(G=>!G.isMain)]:F})},Ig=w.useRef(null);w.useEffect(()=>{if(!it)return;const S=Ig.current;if(!S)return;const T=S.querySelector(`[data-session-tab-id="${CSS.escape(it)}"]`);if(!T)return;const j=requestAnimationFrame(()=>{T.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(j)},[it,qs.length]);const zl=w.useRef(null),$d=w.useRef(null),[ws,ra]=w.useState(r?.groupChats??[]),jd=w.useRef(ws);jd.current=ws;const Bg=w.useRef(null),[Rd,_s]=w.useState(!1),[Ed,Kn]=w.useState(!1),[ql,Ad]=w.useState(""),[hk,ia]=w.useState(-1),[dk,Zl]=w.useState([]),[uk,Wg]=w.useState(!1),Md=w.useRef(void 0),[Es,Xg]=w.useState(r?.teams??[]),[Ld,fk]=w.useState(!!r),[mk,pk]=w.useState([]),[Nd,zg]=w.useState([]),[gk,Ok]=w.useState(null),[T3,Q3]=w.useState(!1),[$3,j3]=w.useState(""),[Jn,na]=w.useState(!1),Vl=w.useRef(null),[qg,xk]=w.useState(""),[oa,eo]=w.useState(0),[to,Fl]=w.useState(!1),[Zg,bk]=w.useState(""),[Dd,aa]=w.useState(0),[Id,vk]=w.useState([]),Vg=w.useRef(!1),Bd=w.useCallback(()=>{Vg.current||(Vg.current=!0,(async()=>{try{const{skills:S}=await ne.skills.list();vk(S.map(T=>({name:T.name,description:T.description??T.name})))}catch{}})())},[]);w.useEffect(()=>{Bd()},[Bd]);const Sn=Zg?Id.filter(S=>S.name.toLowerCase().includes(Zg.toLowerCase())):Id,[yk,Sk]=w.useState([]),Fg=w.useRef(!1),wk=w.useCallback(()=>{Fg.current||(Fg.current=!0,(async()=>{const S=[];try{const[T,j,D,F,G]=await Promise.all([ne.projects.list().catch(()=>({projects:[]})),ne.requirements.list({lean:!0}).catch(()=>({requirements:[]})),ne.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),ne.deliverables.search({limit:100}).catch(()=>({results:[]})),ne.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const se of T.projects)S.push({id:se.id,name:se.name,entityType:"project",role:se.status});for(const se of j.requirements)S.push({id:se.id,name:se.title,entityType:"requirement",role:se.priority});for(const se of D.tasks)S.push({id:se.id,name:se.title,entityType:"task",role:se.status});for(const se of F.results)S.push({id:se.id,name:se.title,entityType:"deliverable",role:se.type});for(const se of G.teams)try{const Ee=await ne.workflows.list(se.id);for(const Ze of Ee.workflows)S.push({id:Ze.name,name:Ze.displayName||Ze.name,entityType:"workflow",role:`v${Ze.version}`})}catch{}}catch{}Sk(S)})())},[]),as=he==="channel"?ws.find(S=>S.channelKey===yt)?.teamId:void 0,_k=w.useRef(null),Xr=w.useRef(null),Ug=w.useRef(void 0),la=w.useCallback((S,T)=>{Ai(T),S&&(T===null?zt.clearActiveSession(S):zt.setActiveSession(S,T))},[Ai,zt]),Hg=w.useMemo(()=>Aa(he,ge,yt,Zt),[he,ge,yt,Zt]);uh();const ca=Cs.isStreaming(it),kk=Cs.liveBubbleId(it),wn=w.useMemo(()=>po(Hg,it),[Hg,it]),Zs=w.useRef(wn);Zs.current=wn;const[ha,Ck]=w.useState(wn);if(w.useEffect(()=>{ka.save(ha,{text:os,images:nr,context:br,replyTo:mn})},[os,ha,nr,br,mn]),ha!==wn){const S={text:os,images:nr,context:br,replyTo:mn};if(os!==ka.peek(ha).text)ka.save(wn,S);else{ka.save(ha,S);const T=ka.get(wn);ir(T.text),Ll(T.images),pn(T.context),El(T.replyTo)}Ck(wn)}const Os=w.useRef(null),Wd=w.useRef(null),oi=w.useRef(null),Ul=w.useRef(null),Xd=w.useRef(null),Hl=w.useRef(0),Yl=w.useRef([]),so=w.useRef(null),Yg=w.useRef([]),zd=w.useRef(void 0),Gl=w.useRef(null),_n=w.useCallback(()=>zt.getActiveSession(le.current)??le.current,[zt]),Li=w.useCallback((S,T)=>{S&&(zt.setWindowBounds(S,T),S===_n()&&yg(T.hasMore))},[zt,_n]);w.useEffect(()=>{yg(zt.getWindowBounds(_n()).hasMore)},[zt,_n,he,ge,yt,Zt,it]),w.useEffect(()=>{if(!Jo)return;const S=T=>{$d.current&&!$d.current.contains(T.target)&&zl.current&&!zl.current.contains(T.target)&&xn(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[Jo]);const Kl=(S,T)=>{if(!T||S===T)return`notes:${S}`;const[j,D]=[S,T].sort();return`dm:${j}:${D}`};w.useEffect(()=>{localStorage.setItem("markus_chat_mode",he)},[he]),w.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),w.useEffect(()=>{localStorage.setItem("markus_chat_channel",yt)},[yt]),w.useEffect(()=>{let S=!1;if(t||!ge||he!=="direct"){Ri(null);return}return ne.agents.get(ge).then(T=>{if(S)return;const j=T.config?.llmConfig;Ri(j?.modelMode==="custom"&&j.primary&&j.defaultModel?{provider:j.primary,model:j.defaultModel}:null)}).catch(()=>{S||Ri(null)}),()=>{S=!0}},[ge,he,t]);const{counts:qd,sessionAgentMap:da,markRead:Zd,markReadMany:Gg,setActiveKey:Pk,clearActiveKeys:Tk}=DC({enabled:!t}),Jl=w.useMemo(()=>{const S={};for(const[T,j]of Object.entries(qd))T.startsWith("channel:")&&(S[T.slice(8)]=j);return S},[qd]),Vd=IC(da,qd);w.useEffect(()=>{let S=0;for(const T of Vd.values())S+=T;for(const T of Object.values(Jl))S+=T;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:S}}))},[Vd,Jl]);const ec=Vd,Qk=w.useCallback(async S=>{const T=[];for(const[j,D]of Object.entries(da))D===S&&T.push(`session:${j}`);await Gg(T)},[da,Gg]);w.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(he==="direct"&&ge&&Qk(ge),he==="channel"&&yt)Zd(`channel:${yt}`);else if(he==="direct"&&it)Zd(`session:${it}`);else if(he==="dm"&&Zt){const j=`dm:${[e?.id,Zt].sort().join(":")}`;Zd(`channel:${j}`)}const T=[];if(he==="direct"&&it){T.push(`session:${it}`);for(const[j,D]of Object.entries(da))D===ge&&T.push(`session:${j}`)}else he==="channel"&&yt?T.push(`channel:${yt}`):he==="dm"&&Zt&&e?.id&&T.push(`channel:dm:${[e.id,Zt].sort().join(":")}`);for(const j of T)Pk(j);return()=>{Tk(T)}},[t,he,yt,it,Zt,ge,x,P,da]);const or=w.useCallback(()=>ne.agents.list().then(S=>h(S.agents)).catch(()=>{}),[]),$k=w.useCallback((S,T)=>{S&&h(j=>j.map(D=>D.id===S?{...D,avatarUrl:T}:D))},[]),Gs=w.useCallback(()=>ne.teams.list().then(S=>{Xg(S.teams),fk(!0)}).catch(()=>{}),[]),ro=w.useCallback(()=>ne.groupChats.list().then(S=>ra(S.chats)).catch(()=>{}),[]),jk=w.useMemo(()=>Ou(or,3e3),[or]),tc=w.useMemo(()=>Ou(Gs,5e3),[Gs]),Fd=w.useMemo(()=>Ou(ro,3e3),[ro]),ua=w.useCallback(()=>{ne.users.list(e?.orgId).then(S=>d(S.users)).catch(()=>{})},[e?.orgId]);w.useEffect(()=>{v&&(x!=="team"||!y||GO(y,Es.map(S=>S.id),Ld)==="missing"&&(window.location.hash=Ut.TEAM))},[v,x,y,Es,Ld]),w.useEffect(()=>{t||(Promise.all([or(),Gs()]).finally(()=>p(!1)),ua(),ne.tasks.list().then(S=>zg(S.tasks)).catch(()=>{}),ne.externalAgents.list().then(S=>pk(S.agents)).catch(()=>{}),ro())},[t,ua]),w.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),d(r.humans??[]),Xg(r.teams??[]),ra(r.groupChats??[]),r.channelMessages)){const S=r.activeChannel??"custom:general";Rs(r.channelMessages.filter(T=>T.channel===S).map(T=>Bn(T)))}},[t,r]),w.useEffect(()=>{AP()},[]),w.useEffect(()=>{if(t||!o)return;const S=()=>{const G=ge,se=qs.map(Ee=>Ee.id).filter(Ee=>Ee!==lt);it&&it!==lt&&!se.includes(it)&&se.push(it),G&&se.length>0&&MP(G,se)};let T=null;const j=()=>{T||(T=setInterval(S,6e4))},D=()=>{T&&clearInterval(T),T=null},F=()=>{document.hidden?D():(S(),j())};return document.addEventListener("visibilitychange",F),document.hidden||j(),S(),()=>{D(),document.removeEventListener("visibilitychange",F)}},[t,o,qs,ge,it]),w.useEffect(()=>{if(t||!o)return;or(),Gs();const S=setInterval(or,3e4),T=setInterval(Gs,6e4),j=Rt.on("agent:update",Ne=>{const ct=Ne?.payload;if(ct?.agentId){const wt=ct.status,es=ct.currentActivity;h(Vt=>Vt.map(xs=>{if(xs.id!==ct.agentId)return xs;const bs={...xs};return wt&&(bs.status=wt),es!==void 0&&(bs.currentActivity=es),bs}))}jk(),tc()}),D=Rt.on("team:update",()=>{tc(),Fd()}),F=Rt.on("agent:removed",tc),G=Rt.on("chat:group_created",()=>{ro(),Gs(),or()}),se=Rt.on("chat:group_updated",Fd),Ee=Rt.on("chat:group_deleted",()=>{Fd(),tc()}),Ze=Rt.on("task:update",Ne=>{const ct=Ne?.payload;ct?.taskId&&zg(wt=>wt.map(es=>es.id===ct.taskId?{...es,status:ct.status??es.status}:es))}),Se=Rt.on("approval:resolved",Ne=>{const ct=Ne?.payload?.approvalId;ct&&(Xl(wt=>wt&&wt.id===ct?null:wt),ta(wt=>wt&&wt.id===ct?null:wt))}),Ce=()=>{or(),Gs(),ua()};return window.addEventListener("markus:data-changed",Ce),()=>{clearInterval(S),clearInterval(T),j(),D(),F(),G(),se(),Ee(),Ze(),Se(),window.removeEventListener("markus:data-changed",Ce)}},[t,o,ua]),w.useEffect(()=>{if(t)return;const S=Se=>{const Ce=Se.detail;if(VC(Ce.page)===Ut.TEAM){if(Ce.params?.agentId&&(Ce.params.profileTab?Ot(Ce.params.agentId,{tab:Ce.params.profileTab}):(Mt("direct"),Xs(Ce.params.agentId),_("chat"),v&&k(),Ce.params.sessionId?Te.current={agentId:Ce.params.agentId,sessionId:Ce.params.sessionId,chips:Ce.params.chatChips??null}:Ce.params.preferMain==="1"&&(oi.current={mode:"direct",agentId:Ce.params.agentId,sessionId:null,preferMain:!0}))),Ce.params?.selectAgent&&(Mt("direct"),Xs(Ce.params.selectAgent),_("chat"),v&&k()),Ce.params?.openDeliverable){const Ne=Ce.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?gr.navigate(Ut.DELIVERABLES,{openDeliverable:Ne}):ie&&ne.deliverables.get(Ne).then(ct=>{ct.deliverable&&ie({kind:"deliverable",deliverable:ct.deliverable})}).catch(()=>{})}if(Ce.params?.prefillMessage){const Ne=Ce.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Ce.params?.autoSend==="true"?setTimeout(()=>Ug.current?.(Ne),300):((Ce.params?.preferMain==="1"||Ce.params?.sessionId)&&(Ul.current=Ne),ir(Ne),setTimeout(()=>{const ct=Ss.current;ct&&(ct.focus(),ct.setSelectionRange(ct.value.length,ct.value.length))},100))}if(Ce.params?.chatChips){const Ne=Ce.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ce.params.sessionId||De(Ne)}if(Ce.params?.dm&&(Mt("dm"),Ti(Ce.params.dm),_("chat"),v&&k()),Ce.params?.channel&&(Mt("channel"),zs(Ce.params.channel),_("chat"),v&&k()),Ce.params?.selectTeam){const Ne=Ce.params.selectTeam;if(v)C(Ne);else{const ct=jd.current.find(wt=>wt.type==="team"&&wt.teamId===Ne);Mt("channel"),zs(ct?.channelKey??`group:${Ne}`),_("chat"),_s(!1),Ue(!0)}}Ce.params?.openHire}},T=localStorage.getItem("markus_nav_agentId");if(T){localStorage.removeItem("markus_nav_agentId");const Se=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),Mt("direct"),Xs(T),Se?Ot(T,{tab:Se}):(_("chat"),v&&k())}const j=localStorage.getItem("markus_nav_dm");j&&(localStorage.removeItem("markus_nav_dm"),Mt("dm"),Ti(j),_("chat"),v&&k());const D=localStorage.getItem("markus_nav_channel");D&&(localStorage.removeItem("markus_nav_channel"),Mt("channel"),zs(D),_("chat"),v&&k());const F=localStorage.getItem("markus_nav_prefillMessage");F&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ir(F),setTimeout(()=>{const Se=Ss.current;Se&&(Se.focus(),Se.setSelectionRange(Se.value.length,Se.value.length))},150));const G=localStorage.getItem("markus_nav_chatChips");G&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),De(G));const se=localStorage.getItem("markus_nav_openDeliverable");se&&(localStorage.removeItem("markus_nav_openDeliverable"),v?gr.navigate(Ut.DELIVERABLES,{openDeliverable:se}):ie&&ne.deliverables.get(se).then(Se=>{Se.deliverable&&ie({kind:"deliverable",deliverable:Se.deliverable})}).catch(()=>{}));const Ee=localStorage.getItem("markus_nav_selectAgent");Ee&&(localStorage.removeItem("markus_nav_selectAgent"),Mt("direct"),Xs(Ee),_("chat"),v&&k());const Ze=localStorage.getItem("markus_nav_selectTeam");if(Ze)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(Ze);else{const Se=jd.current.find(Ce=>Ce.type==="team"&&Ce.teamId===Ze);Mt("channel"),zs(Se?.channelKey??`group:${Ze}`),_("chat"),_s(!1),Ue(!0)}return window.addEventListener("markus:navigate",S),()=>window.removeEventListener("markus:navigate",S)},[t]),w.useEffect(()=>{const S=Bg.current;if(!S)return;const T=ws.find(j=>j.type==="team"&&j.teamId===S);Bg.current=null,Mt("channel"),zs(T?.channelKey??`group:${S}`),_("chat"),_s(!1),Ue(!0)},[ws,Es]),w.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||ge&&l.some(j=>j.id===ge))return;const S=localStorage.getItem("markus_nav_after_remove");if(S&&(localStorage.removeItem("markus_nav_after_remove"),S.startsWith("channel:"))){Mt("channel"),zs(S.slice(8)),_("chat");return}const T=l.find(j=>!j.teamId&&j.role?.toLowerCase()==="secretary")??l.find(j=>j.role?.toLowerCase()==="secretary")??l.find(j=>j.name?.toLowerCase().includes("secretary"));T?(Mt("direct"),Xs(T.id),_("chat")):l.length>0&&(Mt("direct"),Xs(l[0].id),_("chat"))},[l,ge]);const io=w.useRef(!1),kn=w.useRef(!1),fa=w.useRef(0),Ud=w.useRef("none"),Hd=w.useRef(0),sc=w.useRef(0),ai=w.useRef(null),Yd=w.useRef(null),Kg=w.useRef([]),Gd=w.useRef(0),[Rk,Cn]=w.useState(!1),no=w.useRef(0),[Jg,ma]=w.useState(0),oo=w.useCallback(()=>performance.now()<fa.current,[]),Ni=w.useCallback(()=>xP({takeover:kn.current,gestureActive:oo()}),[oo]),ar=w.useCallback(()=>{kn.current=!1,fa.current=0,Ud.current="none",Gd.current=0,sc.current+=1,io.current=!1,Cn(!1),no.current=0,ma(0)},[]),zr=w.useCallback(()=>{kn.current||(kn.current=!0,sc.current+=1,io.current=!1,ai.current!==null&&(cancelAnimationFrame(ai.current),ai.current=null),Cn(!0))},[]),rc=w.useCallback(S=>{fa.current=performance.now()+vu,S!=="none"&&(Ud.current=S);const T=Xr.current;bP(S,!!T&&c0(T))&&zr()},[zr]),ic=w.useCallback(S=>{const T=Xr.current;if(!T)return;const j=T.scrollTop-Hd.current;Hd.current=T.scrollTop;const D=OP({takeover:kn.current,gestureActive:oo(),gestureDirection:Ud.current,scrollable:c0(T),distance:Uc(T),deltaScrollTop:j,programmatic:S?.programmatic??io.current,intentPending:Os.current!==null});D==="handover"?zr():D==="resume"?ar():D==="follow"?(Cn(!1),no.current=0,ma(0)):kn.current&&Cn(!0)},[oo,zr,ar]);w.useEffect(()=>{const S=Xr.current;if(!S)return;let T=null;const j=Ce=>{rc(uP(Ce.deltaX,Ce.deltaY))},D=Ce=>{T=Ce.touches[0]?.clientY??null,fa.current=performance.now()+vu},F=Ce=>{const Ne=Ce.touches[0]?.clientY;if(Ne==null)return;const ct=gP(T,Ne);T=Ne,rc(ct)},G=()=>{T=null},se=Ce=>{np(Ce.target)||rc(pP(Ce.key))},Ee=Ce=>{const Ne=S.getBoundingClientRect();Ce.clientX-Ne.left<S.clientWidth||(fa.current=performance.now()+vu)},Ze=()=>{ic()};S.addEventListener("wheel",j,{passive:!0}),S.addEventListener("touchstart",D,{passive:!0}),S.addEventListener("touchmove",F,{passive:!0}),S.addEventListener("touchend",G,{passive:!0}),S.addEventListener("pointerdown",Ee,{passive:!0}),S.addEventListener("scroll",Ze,{passive:!0}),document.addEventListener("keydown",se);const Se=typeof ResizeObserver<"u"?new ResizeObserver(()=>ic()):null;return Se?.observe(S),Hd.current=S.scrollTop,ic(),()=>{S.removeEventListener("wheel",j),S.removeEventListener("touchstart",D),S.removeEventListener("touchmove",F),S.removeEventListener("touchend",G),S.removeEventListener("pointerdown",Ee),S.removeEventListener("scroll",Ze),document.removeEventListener("keydown",se),Se?.disconnect()}},[x,ic,rc]);const Kd=w.useMemo(()=>new Set(Dg),[Dg]),ls=w.useMemo(()=>{const S=he==="channel"?ns:ns.filter(D=>!D.isActivityLog),T=Kd.size===0?S:S.filter(D=>!(D.isNotification&&Kd.has(D.id))),j=t&&Al?T.length-1:-1;return T.filter((D,F)=>l2(D,F===j||!!D.isStreaming&&ca))},[ns,he,Kd,ca,t,Al]);w.useEffect(()=>{yd.current=P==="chat"&&ls.length>0,Go()},[P,ls.length,Go]);const ao=V2({count:ls.length,getScrollElement:()=>Xr.current,getItemKey:S=>ls[S]?.id??S,estimateSize:S=>{const T=ls[S];return T?T.segments&&T.segments.length>0?300:T.text.length>500?200:120:120},overscan:8});ao.shouldAdjustScrollPositionOnItemSizeChange=(S,T,j)=>xu()||Os.current?.priority==="jump"?!1:S.start<(j.scrollOffset??0);const lr=w.useCallback((S="instant")=>{if(!Ni()||performance.now()<Gd.current)return;const T=Xr.current;if(!T)return;const j=++sc.current,D=()=>j===sc.current&&Ni();if(S==="smooth"){Gd.current=performance.now()+hP,T.scrollTo({top:T.scrollHeight,behavior:"smooth"});return}ai.current!==null&&(cancelAnimationFrame(ai.current),ai.current=null),io.current=!0;let F=0;const G=()=>{if(ai.current=null,!D()){io.current=!1;return}if(T.scrollTop=T.scrollHeight,F+=1,F<cP&&Uc(T)>1){ai.current=requestAnimationFrame(G);return}io.current=!1};T.scrollTop=T.scrollHeight,ai.current=requestAnimationFrame(G)},[Ni]),Pn=w.useCallback(S=>{const T=Xr.current;!T||!S||T.scrollHeight<=T.clientHeight||u0.save(S,yP(d0(T),T))},[]),Tn=w.useCallback(()=>{Hl.current+=1;for(const S of Yl.current)clearTimeout(S);Yl.current=[]},[]),lo=w.useCallback(()=>{Os.current=null,Tn()},[Tn]),eO=w.useCallback(()=>{ar(),lo(),Yd.current!==null&&cancelAnimationFrame(Yd.current);for(const S of Kg.current)clearTimeout(S);lr("instant"),Yd.current=requestAnimationFrame(()=>lr("instant")),Kg.current=[60,160,320].map(S=>setTimeout(()=>lr("instant"),S))},[ar,lo,lr]),Jd=w.useCallback(S=>{const T=Os.current;if(!T||T.key!==S)return!0;if(Zs.current!==S||T.priority!=="prepend"&&oo())return Os.current=null,!0;const j=Xr.current;if(!j)return!0;if(xu())return!1;const{anchor:D}=T;if(D.kind==="bottom"){yu(T.priority)&&ar(),j.scrollTop=j.scrollHeight;const ct=Uc(j)<=1,wt=p0(ct,T.prevSettled);return T.prevSettled=ct,wt?(Os.current=null,!0):!1}const F=TP(T.at,performance.now()),G=_P(d0(j),j,D.id,D.delta),se=G===null&&!F&&(Hs(T.bufferId)??[]).some(ct=>ct.id===D.id),Ee=G!==null&&Math.abs(G)<=1,Ze=p0(Ee,T.prevSettled),Se=G===null&&!se,Ce=zt.getWindowBounds(T.bufferId).hasMore,Ne=QP({priority:T.priority,rendered:G!==null,stale:F,stable:Ze,absent:Se,canLoadMore:Ce});switch(T.prevSettled=G!==null?Ee:null,yu(T.priority)&&Ne!=="release-bottom"&&Ne!=="release-hold"&&zr(),Ne){case"apply":return Xi("intent:apply",{id:D.id,priority:T.priority,correction:G}),Os.current=null,!0;case"refine":return G!==null&&Math.abs(G)>1&&(j.scrollTop+=G),G!==null&&Math.abs(G)>8&&Xi("intent:refine",{id:D.id,priority:T.priority,correction:G}),!1;case"release-bottom":return Xi("intent:release-bottom",{id:D.id,priority:T.priority}),Os.current=null,yu(T.priority)&&ar(),j.scrollTop=j.scrollHeight,!0;case"release-hold":return Xi("intent:release-hold",{id:D.id,priority:T.priority,stale:F,absent:Se,canLoadMore:Ce,bufferId:T.bufferId}),Os.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:T.priority,anchor:D}),!0;default:{const ct=Yg.current.findIndex(wt=>wt.id===D.id);if(ct>=0){const wt=ao.getOffsetForIndex(ct,"start");wt&&(j.scrollTop=wt[0]+D.delta)}else zd.current?.();return!1}}},[ao,oo,zr,ar,Hs]),nc=w.useCallback(()=>{const S=Os.current;if(!S)return;const T=S.key;Tn();const j=Hl.current,D=G=>{Yl.current.push(setTimeout(()=>{j===Hl.current&&Os.current?.key===T&&(Jd(T)||D(m0))},G))},F=[0,60,160,320,560,900];F.forEach((G,se)=>{const Ee=se===F.length-1,Ze=()=>{if(j!==Hl.current)return;!Jd(T)&&Ee&&D(m0)};G===0?requestAnimationFrame(Ze):Yl.current.push(setTimeout(Ze,G))})},[Jd,Tn]),co=w.useCallback((S,T,j="restore",D)=>{if(!S)return!1;const F=Os.current;return CP(F,{key:S,priority:j})?(Os.current={key:S,bufferId:D??_n(),anchor:T,at:performance.now(),priority:j,prevSettled:null},nc(),!0):!1},[_n,nc]),pa=w.useCallback(S=>{S&&co(S,u0.get(S)??{kind:"bottom"})},[co]),Ek=w.useCallback(()=>{Os.current||(so.current!==null&&clearTimeout(so.current),so.current=setTimeout(()=>{so.current=null,Pn(Zs.current)},200))},[Pn]);Yg.current=ls,w.useLayoutEffect(()=>()=>{Pn(Zs.current),Tn(),so.current!==null&&clearTimeout(so.current)},[Pn,Tn]);const ga=w.useMemo(()=>$I(ls,ql),[ls,ql]);w.useEffect(()=>{ia(-1)},[ql]);const oc=w.useCallback(S=>{const T=()=>{const F=document.getElementById(`msg-${S}`);return F?(F.classList.remove("chat-find-hit"),F.offsetWidth,F.classList.add("chat-find-hit"),window.setTimeout(()=>F.classList.remove("chat-find-hit"),1600),!0):!1};let j=0;const D=()=>{T()||j++>=8||window.requestAnimationFrame(D)};D()},[]),tO=w.useCallback(async(S,T)=>{lo(),zr();const j=Zs.current,D=le.current,F=()=>(Hs(D)??[]).some(se=>se.id===S);let G=F();if(!G&&j){const se=zt.getActiveSession(D)??D,Ee=await RI({targetId:S,has:F,targetCreatedAt:T,fetchPage:async Se=>{if(!se||se===lt)return{messages:[],hasMore:!1};const Ce=await ne.sessions.getMessages(se,50,Se);return{messages:Ce.messages,hasMore:Ce.hasMore}}}),Ze=jI(Ee.messages,S);Ze.length>0&&(z(D,Ze.map(mh)),Li(se,{hasMore:Ee.hasMore,oldestCursor:Ze[0]?new Date(Ze[0].createdAt).toISOString():null})),G=Ee.found||F(),Xi("jump:collected",{messageId:S,found:Ee.found,kept:Ze.length,exhausted:Ee.exhausted})}if(Xi("jump:located",{messageId:S,loaded:G,key:j,nowKey:Zs.current}),!(j&&Zs.current!==j)){if(G&&j){co(j,h0(S),"jump",_n()),Xi("jump:scheduled",{messageId:S,key:j}),oc(S);return}j&&(Xi("jump:fallback-bottom",{messageId:S,key:j}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:S}),ar(),lr("instant"))}},[lo,zr,co,oc,Hs,zt,z,Li,ar,lr]),Ak=w.useCallback(S=>{const T=ga.matches[S];T&&(ia(S),lo(),zr(),Zs.current&&co(Zs.current,h0(T.messageId),"jump"),oc(T.messageId))},[ga.matches,lo,zr,co,oc]);w.useEffect(()=>{if(P!=="chat"||t)return;const S=T=>{T.key.toLowerCase()!=="f"||T.altKey||T.shiftKey||!(b?T.metaKey&&!T.ctrlKey:T.ctrlKey&&!T.metaKey)||(T.preventDefault(),Kn(!0))};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[P,t,b]);const sO=w.useRef(o);w.useEffect(()=>{sO.current=o},[o]),w.useLayoutEffect(()=>{const S=Wd.current;if(S&&(Wd.current=null,!Os.current&&S.key===Zs.current)){const T=Xr.current,j=T?T.scrollHeight-S.scrollHeight:0;T&&j>0&&(T.scrollTop+=j,T.dispatchEvent(new Event("scroll")))}if(Os.current){nc();return}sO.current&&Ni()&&(xu()||lr())},[ns,lr,Ni,nc]);const rO=w.useRef(P);w.useEffect(()=>{const S=rO.current!=="chat";rO.current=P,P==="chat"&&S&&pa(Zs.current)},[P,hs,lr,Ni,pa]);const iO=w.useRef(I);w.useEffect(()=>{if(iO.current===I||(iO.current=I,P!=="chat")||ls.length===0||hs||On||!Ni())return;const S=[],T=requestAnimationFrame(()=>lr("instant"));for(const j of[60,160,320])S.push(setTimeout(()=>lr("instant"),j));return()=>{cancelAnimationFrame(T);for(const j of S)clearTimeout(j)}},[I,P,ls.length,hs,On,lr,Ni]);const ac=w.useCallback(async(S,T,j)=>{const D=T??`ch:${S}`;!j?.quiet&&le.current===D&&Wr(!0);try{const F=await ne.channels.getMessages(S,50),G=F.messages.map(se=>Bn(se,e?.id));z(D,G),Li(D,{hasMore:F.hasMore,oldestCursor:F.messages[0]?new Date(F.messages[0].createdAt).toISOString():null}),le.current===D&&Rs(G)}catch{le.current===D&&Rs([])}finally{!j?.quiet&&le.current===D&&Wr(!1)}},[Li]),eu=w.useCallback(async S=>{if(!S)return Ei([]),Nl(0),Dl(1),Bl(!1),xd(!1),[];xd(!0);try{const T=await ne.sessions.listByAgent(S,20,1);return Ei(T.sessions),Nl(T.total??T.sessions.length),Dl(T.page??1),Bl(!!T.hasMore),T.sessions}catch{return Ei([]),Nl(0),Dl(1),Bl(!1),[]}finally{xd(!1)}},[]),nO=w.useRef({chatContext:[],input:"",pendingImages:[],chatMode:he,selectedAgent:ge,activeSessionId:it,activeDmUserId:Zt,authUser:e,activeChannel:yt,groupChats:ws,agents:l,humans:u,sending:hs,chatReplyTo:null});nO.current={chatContext:br,input:os,pendingImages:nr,chatMode:he,selectedAgent:ge,activeSessionId:it,activeDmUserId:Zt,authUser:e,activeChannel:yt,groupChats:ws,agents:l,humans:u,sending:hs,chatReplyTo:mn};const Mk=S3({stateRef:nO,actBuffers:Gn,activeSessionBuffer:un,readConvMsgs:Hs,readSessionMsgs:$i,currentConvKeyRef:le,updateConvMsgs:Be,updateConvMsgsRaf:rt,appendConvActivity:ot,beginStream:Lt,endStream:St,abortStream:gs,clearStreamSession:ji,setStreamSession:us,getStreamSession:md,setActiveSession:Oe,incrementSending:ni,decrementSending:Br,loadAndDisplay:rr,sessionSwitchSeqRef:bd,setSending:Qi,setActivities:dn,setInput:ir,setChatContext:pn,setPendingImages:Ll,setMentionDropdown:na,setChatReplyTo:El,setActiveSessionId:Ai,setStoredActiveSession:Ko,setOpenSessionTabs:Ys,setSessions:Ei,setLoadingChat:Wr,setWindowBounds:Li,makeConvKey:Aa,makeDmChannel:Kl,addRecentMsgId:fd,resumeChatScrollFollow:ar,loadSessions:eu,t:i}),{send:ho,stopSending:Lk,tryReattachActiveStream:Qn,loadSessionMessages:lc}=Mk;Ug.current=ho;const oO=w.useCallback(()=>{eO(),ho()},[eO,ho]),aO=w.useRef(Qn);aO.current=Qn;const Nk=uh();w.useEffect(()=>{if(!o||t||he!=="direct"||!ge)return;const S=it;!S||S===lt||Cs.isStreaming(S)&&aO.current(ge,S,le.current)},[o,t,he,ge,it,Nk]);const lO=w.useRef(()=>{});lO.current=()=>{const S=b2({isActive:o,previewMode:t,chatMode:he,selectedAgent:ge,activeSessionId:it,placeholderId:lt});if(!S||!ge)return;const T=le.current;lc(S,T).then(()=>{Qn(ge,S,T)})},w.useEffect(()=>{const S=()=>{document.visibilityState==="visible"&&lO.current()};return document.addEventListener("visibilitychange",S),window.addEventListener("pageshow",S),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("pageshow",S)}},[]);const Dk=w.useCallback(async()=>{if(Wl||!ge||!Il)return;Qg(!0);const S=Tg+1,T=ge;try{const j=await ne.sessions.listByAgent(T,20,S);Ei(D=>{const F=new Set(D.map(se=>se.id)),G=[...D,...j.sessions.filter(se=>!F.has(se.id))];return Nl(j.total??G.length),G}),Dl(S),Bl(!!j.hasMore)}catch{}Qg(!1)},[Wl,Il,Tg,ge]),cO=w.useCallback(S=>{jg(S.id),kd((S.isMain?"":S.title)||"")},[]),Oa=w.useCallback(()=>{jg(null),kd("")},[]),hO=w.useCallback(async S=>{const T=_d.trim();if(!T){Oa();return}try{const D=(await ne.sessions.renameTitle(S.id,T))?.session?.title??T;Ei(F=>F.map(G=>G.id===S.id?{...G,title:D}:G)),Ys(F=>F.map(G=>G.id===S.id?{...G,title:D}:G))}catch{}Oa()},[_d,Oa]),dO=w.useCallback(async()=>{if(Gl.current)return Gl.current;const S=le.current,T=zt.getActiveSession(S)??S,j=zt.getWindowBounds(T),D=j.oldestCursor;if(!j.hasMore||!D)return 0;const F=T&&T!==lt?T:null,se=(async()=>{Sg(!0);try{const Ee=Zs.current;let Ze=[],Se=!1,Ce=null;if(he==="channel"||he==="dm"){const xs=he==="dm"?Kl(e?.id??"",Zt):yt,bs=await ne.channels.getMessages(xs,50,D);Ze=bs.messages.map(jr=>Bn(jr,e?.id)),Se=bs.hasMore,Ce=bs.messages[0]?new Date(bs.messages[0].createdAt).toISOString():null}else if(F){const xs=await ne.sessions.getMessages(F,50,D);Ze=xs.messages.map(mh),Se=xs.hasMore,Ce=xs.messages[0]?new Date(xs.messages[0].createdAt).toISOString():null}else return 0;if(Ze.length===0)return Li(T,{hasMore:Se,oldestCursor:D}),0;if(le.current!==S||Zs.current!==Ee)return 0;const Ne=Xr.current,ct=Ne?Ne.scrollHeight:null,wt=Hs(S)??[],es=new Set(Ze.map(xs=>xs.id));let Vt=[...Ze,...wt.filter(xs=>!es.has(xs.id))];return Vt.length>500&&(Vt=Vt.slice(-500)),z(S,Vt),Li(T,{hasMore:Se,oldestCursor:Ce}),ct!==null&&(Wd.current={key:Zs.current,scrollHeight:ct}),Rs(Vt),Ze.length}catch{return 0}finally{Sg(!1)}})();Gl.current=se;try{return await se}finally{Gl.current=null}},[he,yt,e?.id,Zt,Hs,z,zt,Li]);zd.current=dO;const tu=w.useRef(!1),Ik=w.useCallback(S=>{Ek(),!tu.current&&(tu.current=!0,requestAnimationFrame(()=>{tu.current=!1,S.target.scrollTop<100&&zd.current?.()}))},[]);w.useEffect(()=>{if(t)return;const S=Aa(he,ge,yt,Zt),T=le.current;le.current=S,T&&T!==S&&(Yo.set(T,qs),it&&Jm(T)&&Oe(T,it),Pn(po(T,it))),T!==S&&(ar(),Cn(!1),no.current=0,ma(0),Kn(!1),Ad(""),ia(-1));const j=Hs(S),D=Yo.get(S),F=un.get(S)??(ge?Pg(ge)??void 0:void 0),G=F??it,se=he!=="direct"?xr(S):Cs.isStreaming(G),Ee=G??S,Ze=Gn.get(Ee)??[];dn(se?Ze:[]),Qi(se),he==="direct"&&ge&&eu(ge),D&&D.length>0&&Ys(D),xn(!1);const Se=LP(oi.current,{chatMode:he,agentId:ge});if(j!==void 0&&j.length>0)if(se||zt.completeLoad(S),Wr(!1),Rs(j),F!==void 0&&(la(S,F),pa(po(S,F))),(!D||D.length===0)&&Ys([]),he==="channel"||he==="dm"){const Ne=he==="dm"?Kl(e?.id??"",Zt):yt;ac(Ne,S)}else he==="direct"&&ge&&F&&F!==lt&&!Se&&(se?Qn(ge,F,S):lc(F,S).then(()=>{le.current===S&&ge&&Qn(ge,F,S)}));else if(ut(S),Wr(!0),Rs([]),z(S,[]),he==="channel"||he==="dm"){const Ne=he==="dm"?Kl(e?.id??"",Zt):yt;ac(Ne,S),(!D||D.length===0)&&Ys([])}else he==="direct"&&ge?eu(ge).then(Ne=>{if(le.current===S)if(Ne.length>0){const ct=Ne.find(Ms=>Ms.isMain),wt=Sd(ge),es=ct?[ct,...Ne.filter(Ms=>!Ms.isMain&&!wt.has(Ms.id)).slice(0,4)]:Ne.filter(Ms=>!wt.has(Ms.id)).slice(0,5);let Vt=D&&D.length>0?D:es;const xs=Pg(ge),bs=F!==void 0?F:xs??ct?.id??Vt[0].id;if(bs&&bs!==lt&&!Vt.some(Ms=>Ms.id===bs)){const Ms=Ne.find(fu=>fu.id===bs);Ms&&(Vt=[...Vt,Ms])}const jr=bs&&Vt.some(Ms=>Ms.id===bs)?bs:Vt[0].id,ci=oi.current;if(ci&&ci.mode==="direct"&&ci.agentId===ge&&(ci.sessionId||ci.preferMain)){Ys(Vt);return}la(S,jr),pa(po(S,jr)),Ko(ge,jr),Ys(Vt),lc(jr,S).then(()=>{le.current===S&&ge&&Qn(ge,jr,S)})}else la(S,null),Wr(!1),(!D||D.length===0)&&Ys([])}).catch(()=>{le.current===S&&Wr(!1)}):Wr(!1)},[t,he,ge,yt,Zt,n.language,i]),w.useEffect(()=>t?void 0:Rt.on("chat:message",T=>{const j=T.payload,D=j.channel??"";if(!D)return;const F=j.senderType??"agent",G=j.text??j.message??"",se=j.senderId??j.agentId??"",Ee=j.senderName??j.agentId??i("page.fallbackAgent"),Ze=j.metadata,Se=j.messageId??j.id??"";if(Se&&ln.current.has(Se))return;const Ce=F==="human"&&se===(e?.id??""),Ne={id:Se||`ws_${Date.now()}_${se}`,sender:Ce?"user":"agent",text:G,time:new Date().toLocaleTimeString(),rawCreatedAt:T.timestamp??new Date().toISOString(),agentName:Ce?void 0:Ee,agentId:Ce?void 0:se,replyToId:j.replyToId??void 0,replyToSender:j.replyToSender??void 0,replyToText:j.replyToText??void 0};if(Ze&&F==="agent"){const wt=[];if(Ze.thinking?.length&&wt.push({type:"text",content:"",thinking:Ze.thinking.join(`
89
89
 
90
90
  `)}),Ze.toolCalls?.length)for(let es=0;es<Ze.toolCalls.length;es++){const Vt=Ze.toolCalls[es];wt.push({type:"tool",key:`${Vt.tool}_${es}`,tool:Vt.tool,status:Vt.status==="error"?"error":"done",args:Vt.arguments,result:Vt.result,durationMs:Vt.durationMs})}wt.length>0&&(wt.push({type:"text",content:G}),Ne.segments=wt)}let ct;if(D.startsWith("notes:"))ct=`dm:${D.slice(6)}`;else if(D.startsWith("dm:")){const wt=D.slice(3).split(":");ct=`dm:${wt.find(Vt=>Vt!==(e?.id??""))??wt[0]??""}`}else ct=`ch:${D}`;Be(ct,wt=>bu(wt,Ne)),ct===le.current&&kn.current&&(no.current+=1,ma(no.current),Cn(!0))}),[t,Be,e?.id,yt]);const uO=w.useRef(!1);w.useEffect(()=>t?void 0:Rt.on("connected",()=>{const T=!uO.current;uO.current=!0,!T&&he==="channel"&&yt&&ac(yt,void 0,{quiet:!0})}),[t,he,yt,ac]),w.useEffect(()=>t?void 0:Rt.on("session:title_updated",T=>{const j=T.payload;if(!j)return;const D=j.sessionId,F=j.title;!D||typeof F!="string"||(Ei(G=>G.map(se=>se.id===D?{...se,title:F}:se)),Ys(G=>G.map(se=>se.id===D?{...se,title:F}:se)))}),[t]),w.useEffect(()=>t?void 0:Rt.on("chat:proactive_message",T=>{const j=T.payload,D=j.targetUserId;if(D&&D!==e?.id)return;const F=j.agentId??"",G=j.agentName??i("page.fallbackAgent"),se=j.message??"",Ee=j.sessionId??"",Ze=j.messageId??"",Se=j.metadata??{};if(!F||!se||se==="[cancelled]"||se==="[Stream cancelled]")return;const Ce=Se.role==="user",Ne=!Ce&&(!!Se.activityLog||se.startsWith("[ACTIVITY:")),{cleaned:ct,priority:wt}=c2(se),es=!Ce&&(!!Se.notifyUser||ct!==se),Vt=Aa("direct",F,"","");if(Ee&&le.current===Vt){const Rr=it;if(Rr&&Rr!==lt&&Rr!==Ee)return}const xs=!!Se.isMainSession&&!Ce,bs=Ee||it,jr=typeof Se.userText=="string"?Se.userText:"",ci=typeof Se.userMessageId=="string"?Se.userMessageId:"",Ms=typeof Se.createdAt=="string"&&Se.createdAt||(typeof T.timestamp=="string"?T.timestamp:void 0)||new Date().toISOString(),fu=(()=>{try{return new Date(Ms).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Ii={id:Ze||`proactive_${Date.now()}`,sender:Ce?"user":"agent",text:ct,time:fu,rawCreatedAt:Ms,...Ce?{}:{agentName:G,agentId:F,...es?{isNotification:!0,notifyPriority:Se.priority??wt}:{},...Ne?{isActivityLog:!0,activityType:Se.activityType,outcome:Se.outcome,mailboxItemId:Se.mailboxItemId,taskId:Se.taskId,requirementId:Se.requirementId}:{},...!Ne&&Se.taskId?{taskId:Se.taskId}:{},...!Ne&&Se.requirementId?{requirementId:Se.requirementId}:{}}};es&&Ii.id&&Qd(Rr=>Rr.includes(Ii.id)?Rr:[...Rr,Ii.id]),Be(Vt,Rr=>{if(Rr.some(An=>An.id===Ii.id))return Rr;let En=Rr;if(!Ce&&jr&&(En.some(Bi=>ci&&Bi.id===ci||Bi.sender==="user"&&Bi.text===jr)||(En=bu(En,{id:ci||`feishu_user_${Ii.id}`,sender:"user",text:jr,time:new Date().toLocaleTimeString(),rawCreatedAt:Ii.rawCreatedAt}))),xs)for(let An=En.length-1;An>=0;An--){const Bi=En[An];if(Bi.sender==="agent"&&Bi.agentId===F&&Bi.isStopped){const RO=[...En];return RO[An]={...Ii,id:Bi.id},RO}}return bu(En,Ii)},bs||void 0)}),[t,Be,i,it]),Nd.find(S=>S.id===gk),w.useEffect(()=>{Ok(null)},[ge]);const[vr,su]=w.useState(null),[fO,mO]=w.useState(!1),[Bk,pO]=w.useState(null),[Di,ru]=w.useState(null),Wk=w.useMemo(()=>{for(let S=ns.length-1;S>=0;S--)if(ns[S]?.sender==="agent"&&!ns[S]?.isActivityLog)return ns[S].id;return null},[ns]),Xk=w.useCallback(S=>{const T=S.segments?S.segments.filter(j=>j.type==="text").map(j=>j.content).join(`
91
91
  `):S.text;navigator.clipboard.writeText(T),pO(S.id),setTimeout(()=>pO(j=>j===S.id?null:j),2e3)},[]),iu=w.useCallback((S,T,j)=>{const D=le.current,F=Hs(D)??ns,G=F.findIndex(Ee=>Ee.id===S.id);if(G<0)return;const se=T&&G>0&&F[G-1]?.id===T.id;Be(D,Ee=>{const Ze=Ee.findIndex(Se=>Se.id===(se?T.id:S.id));return Ze>=0?Ee.slice(0,Ze):Ee}),ho(j,{isRetry:!0})},[ns,Be]),zk=w.useCallback(S=>{const T=le.current,j=Hs(T)??ns,D=j.findIndex(Ee=>Ee.id===S.id);if(D<0)return;let F=null;for(let Ee=D-1;Ee>=0;Ee--)if(j[Ee]?.sender==="user"){F=j[Ee];break}const G=F?.text??"";if(!G)return;if(D<j.length-1){const Ee=j.length-1-D;ru({retryMsg:S,userMsg:F,retryText:G,followCount:Ee});return}iu(S,F,G)},[ns,iu]),qk=w.useCallback(S=>{const T=le.current;if((Hs(T)??ns).findIndex(G=>G.id===S.id)<0)return;Be(T,G=>{const se=[...G],Ee=se.findIndex(Ce=>Ce.id===S.id);if(Ee<0)return G;const Ze=se[Ee],Se=[...Ze.segments??[]];for(;Se.length>0;){const Ce=Se[Se.length-1];if(Ce.type==="tool"&&(Ce.status==="stopped"||Ce.status==="running"))Se.pop();else if(Ce.type==="text"&&!Ce.content)Se.pop();else break}return se[Ee]={...Ze,segments:Se,isStopped:!1,isError:!1},se});const F=un.get(T)??(it&&it!==lt?it:null);if(!F){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:F})},[ns,Be,it]),Zk=w.useCallback(S=>{const T=S.sender==="user"?e?.name??i("page.fallbackYou"):S.agentName??i("page.fallbackAgent");if(El({id:S.id,sender:T,text:S.text}),he==="channel"&&S.sender==="agent"&&S.agentName){const j=`@${S.agentName} `;ir(D=>D.startsWith(j)?D:j+D)}Ss.current?.focus()},[e?.name,he,i]),Vk=async S=>{if(!vr||!ge||he!=="direct")return;const T=it;if(!(!T||T===lt)){mO(!0);try{const j=await ne.agents.evolveFromMessage(ge,{parentSessionId:T,sourceMessageId:vr.isStreaming===!0||vr.id.startsWith("a_")||vr.id.startsWith("u_")?void 0:vr.id,sourceText:(vr.text||"").slice(0,500)||void 0,userNote:S.trim()||void 0}),D=new Date().toISOString(),F={id:j.sessionId,agentId:ge,userId:e?.id??null,title:"Remember / Evolution",isMain:!1,metadata:{kind:"evolution",parentSessionId:j.parentSessionId,sourceMessageId:vr.id,sourceAgentId:ge,createdFrom:"remember_button"},createdAt:D,lastMessageAt:D};su(null),Ei(se=>[F,...se.filter(Ee=>Ee.id!==F.id)]),Ys(se=>se.some(Ee=>Ee.id===F.id)?se:[...se,F]),Ai(F.id);const G=Aa("direct",ge,yt,Zt);ss(G,F.id),Ko(ge,F.id),Rs([]),await ho(j.seedPrompt,{sessionIdOverride:j.sessionId})}catch(j){console.error("evolve-from-message failed",j)}finally{mO(!1)}}},li=async S=>{const T=++bd.current,j=it,D=le.current;Pn(po(D,j)),la(D,S.id),pa(po(D,S.id)),xn(!1),ar(),Cn(!1),no.current=0,ma(0);const F=Cs.isStreaming(S.id);Qi(F),dn(F?Gn.get(S.id)??[]:[]),ge&&Ko(ge,S.id),j&&j!==lt&&Kt(D,j);const G=fn(D,S.id);(!G||G.length===0)&&S.id!==lt&&Wr(!0),Ys(se=>se.some(Ee=>Ee.id===S.id)?se:[...se,S]),ge&&ik(ge,S.id),le.current!==D&&(le.current=D);try{await lc(S.id,D)}finally{bd.current===T&&Wr(!1)}ge&&Qn(ge,S.id,D)};w.useEffect(()=>{const S=Te.current;!S||ge!==S.agentId||(Te.current=null,(async()=>{try{const{sessions:T}=await ne.sessions.listByAgent(S.agentId,50),j=T.find(D=>D.id===S.sessionId);if(!j){S.chips&&De(S.chips);return}await li(j),S.chips&&De(S.chips)}catch{S.chips&&De(S.chips)}})())},[ge,li,De]);const Fk=S=>{if(Ys(T=>T.filter(j=>j.id!==S)),ge&&S!==lt&&rk(ge,S),it===S){const T=qs.filter(j=>j.id!==S);T.length>0?li(T[T.length-1]):xa()}},gO=w.useCallback(async S=>{if(S.trim().length<2){Zl([]);return}Wg(!0);try{const T=he==="channel"?"channel":he==="direct"?"direct":"all",j=he==="channel"?yt:void 0,{results:D}=await ne.messages.search(S,{scope:T,channel:j,limit:30});Zl(D)}catch{Zl([])}Wg(!1)},[he,yt]),Uk=w.useCallback(S=>{Ad(S),Md.current&&clearTimeout(Md.current),Md.current=setTimeout(()=>{gO(S)},300)},[gO]),cc=w.useRef(null),Hk=w.useCallback(S=>{if(Kn(!1),Ad(""),Zl([]),S.source==="channel"&&S.channel){Mt("channel"),zs(S.channel),_("chat"),oi.current={messageId:S.id,mode:"channel",channel:S.channel};return}S.source==="direct"&&S.agentId&&(Mt("direct"),_("chat"),S.agentId!==ge&&Xs(S.agentId),oi.current={messageId:S.id,mode:"direct",agentId:S.agentId,sessionId:S.sessionId??null,createdAt:S.createdAt})},[ge]);w.useEffect(()=>{const S=oi.current;if(!S){Ul.current=null;return}const T=()=>{if(Xd.current=null,oi.current!==S)return;oi.current=null;const D=Ul.current;D!=null&&(Ul.current=null,ir(D)),S.messageId&&tO(S.messageId,S.createdAt)};if(S.mode==="channel"){if(he!=="channel"||yt!==S.channel||On)return;T();return}if(he!=="direct"||P!=="chat"||S.agentId&&S.agentId!==ge)return;const j=S.preferMain?(Qr.find(D=>D.isMain)??qs.find(D=>D.isMain))?.id:S.sessionId;if(!(S.preferMain&&!j)){if(j&&j!==it){if(Xd.current===S)return;const D=Qr.find(F=>F.id===j)??qs.find(F=>F.id===j)??(Qr.length===0?null:void 0);if(D===null)return;Xd.current=S,(async()=>{const F=new Date().toISOString();await li(D??{id:j,agentId:S.agentId??ge??"",userId:null,title:null,createdAt:F,lastMessageAt:F}),T()})();return}On||T()}},[he,yt,ge,it,Qr,Il,qs,On,P,ls,tO,li]);const xa=()=>{Pn(Zs.current),Tn(),Os.current=null,Ai(lt);const S=le.current;ss(S,lt),Rs([]),xn(!1),Ys(j=>{const D=j.filter(F=>F.id!==lt);return[{id:lt,agentId:ge??"",userId:null,title:i("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...D]});const T=ge;T&&ne.sessions.create(T).then(j=>{const D=j?.session;if(!D?.id)return;const F=D.id;if(le.current!==S)return;const G=un.get(S);G!==void 0&&G!==lt||(la(S,F),Ko(T,F),Ys(se=>se.map(Ee=>Ee.id===lt?{...Ee,id:F,title:D.title??Ee.title}:Ee)))}).catch(()=>{})},ba=w.useCallback(()=>{t||!o||P==="chat"&&(wd||Ye||Qe||Jn||to||Di||vr||requestAnimationFrame(()=>{const S=Ss.current;S&&!S.disabled&&(S.focus(),S.setSelectionRange(S.value.length,S.value.length))}))},[t,o,P,wd,Ye,Qe,Jn,to,Di,vr]),OO=w.useRef(o),xO=w.useRef(ge),bO=w.useRef(it);w.useEffect(()=>{const S=o&&!OO.current,T=ge!==xO.current,j=it!==bO.current;OO.current=o,xO.current=ge,bO.current=it,!v&&(S||T||j)&&ba()},[o,ge,it,v,ba]),w.useEffect(()=>{if(t||!o||v)return;const S=T=>{if(Di||vr||Jn||to||FC(T.target))return;const j=v2({key:T.key,metaKey:T.metaKey,ctrlKey:T.ctrlKey,altKey:T.altKey,shiftKey:T.shiftKey},b);if(j==="new-conversation"){if(he!=="direct"||!ge||P!=="chat")return;const D=T.target;if(D&&D!==Ss.current&&(D.tagName==="INPUT"||D.tagName==="TEXTAREA"||D.isContentEditable))return;T.preventDefault(),xa(),ba();return}if(j==="cycle-session-next"||j==="cycle-session-prev"){if(he!=="direct"||!ge||P!=="chat"||qs.length<2)return;const D=j==="cycle-session-prev"?-1:1,F=y2(qs.map(se=>se.id),it,D);if(!F)return;T.preventDefault();const G=qs.find(se=>se.id===F);if(!G)return;if(G.id===lt){Ai(lt);const se=le.current;ss(se,lt),Rs([])}else li(G);ba()}};return document.addEventListener("keydown",S,!0),()=>document.removeEventListener("keydown",S,!0)},[t,o,v,b,he,ge,P,qs,it,Jn,to,Di,vr,xa,li,ba,Ai,ss,Rs,le]);const Yk=S=>{const T=eP({text:os,chips:br},S);ir(T.text),pn(T.chips);const j=Ss.current?.selectionStart??S.length,D=S.slice(0,j),F=D.lastIndexOf("@");if(F>=0){const G=F===0?"":D[F-1];if(F===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(G)){const Ee=D.slice(F+1);if(!Ee.includes(" ")&&!Ee.includes(`