@markus-global/cli 0.9.0-rc.8 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +60 -11
- package/dist/commands/start.js.map +1 -1
- package/dist/markus.mjs +3456 -1469
- package/dist/web-ui/assets/{CommentInput-BJmv0Rha.js → CommentInput-Ccv0KCzc.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-DJQo68Rq.js → ContentRenderer-BbN7QT3E.js} +2 -2
- package/dist/web-ui/assets/Deliverables-Dzfujlqv.js +6 -0
- package/dist/web-ui/assets/{Notifications-BTkCe_FT.js → Notifications-DMI9cmK5.js} +1 -1
- package/dist/web-ui/assets/{Search-DJMnvmW4.js → Search-Va12fH-V.js} +1 -1
- package/dist/web-ui/assets/{Settings-Bo7g6_tg.js → Settings-D_0MEUGb.js} +2 -2
- package/dist/web-ui/assets/{Store-B_9bFi_v.js → Store-dRlOlppM.js} +1 -1
- package/dist/web-ui/assets/Team-D8m98W3b.js +40 -0
- package/dist/web-ui/assets/{Work-CBpfr_rN.js → Work-C6pfFbRU.js} +5 -5
- package/dist/web-ui/assets/{arc-FGZKJEo5.js → arc-w52qYN0j.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DrHriKKt.js → architectureDiagram-3BPJPVTR-Dq5t04Vy.js} +3 -3
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-B1KrBMG4.js → blockDiagram-GPEHLZMM-dMSQ7RYP.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-CB3d18fE.js → c4Diagram-AAUBKEIU-yG4K-xPW.js} +1 -1
- package/dist/web-ui/assets/channel-0x_SxlyN.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-yhAAZF8B.js → chunk-2J33WTMH-BMCCyFP7.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-DhGfeR_u.js → chunk-4BX2VUAB-DrZE__0f.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-B4ZyaFdf.js → chunk-55IACEB6-BHAPJ9Eo.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-DiEJq1Wh.js → chunk-727SXJPM-Ctfjl9vK.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-DJgXMRvd.js → chunk-AQP2D5EJ-SVZPGzSA.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-DLzapSRw.js → chunk-FMBD7UC4-DeTpOrnv.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-KaWi6H4E.js → chunk-ND2GUHAM-CudW1r3G.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-CedM3HE_.js → chunk-QZHKN3VN-CJSQIoVy.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D4o-x8Tr.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D4o-x8Tr.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DGOMWPFW.js → cose-bilkent-S5V4N54A-CcCOSPt7.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-CsB6PNx2.js → dagre-BM42HDAG-F3l9565T.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-dsKr5CnT.js → diagram-2AECGRRQ-B5Ep5hBX.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-CfKFUiA0.js → diagram-5GNKFQAL-Ba-Xi40Z.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-C-iYqWwv.js → diagram-KO2AKTUF-nq3nvV52.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-VrnDGieS.js → diagram-LMA3HP47-BLQG5suI.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-2CPw94I0.js → diagram-OG6HWLK6-BZwEfL_A.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-B2CXjopz.js → erDiagram-TEJ5UH35-x0d6Urzc.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-uYZBII8i.js → flowDiagram-I6XJVG4X-Bps4iInm.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DX__je4a.js → ganttDiagram-6RSMTGT7-BQhqabZG.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-ClWVZgy5.js → gitGraphDiagram-PVQCEYII-CZsFUtiG.js} +1 -1
- package/dist/web-ui/assets/index-BDWvYwl1.css +1 -0
- package/dist/web-ui/assets/{index-Dgg0L65t.js → index-BVZKeNvh.js} +76 -72
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-0bE4Z9ff.js → infoDiagram-5YYISTIA-bUkRpixn.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-nCIQcUlM.js → ishikawaDiagram-YF4QCWOH-C71uSHjN.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-Bc1umCm3.js → journeyDiagram-JHISSGLW-CH4cq7H3.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BqkpB1pF.js → kanban-definition-UN3LZRKU-B1plHCmn.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-CSfwY1-0.js → mermaid.core-BtKFJxef.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-nQyDFxhc.js → mindmap-definition-RKZ34NQL-BRinAMnx.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-5HVdrqjx.js → pieDiagram-4H26LBE5-B8r7cm8D.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-NuRh23Sl.js → quadrantDiagram-W4KKPZXB-BlYE_3Bv.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-BGztYPcI.js → requirementDiagram-4Y6WPE33-XHqns5Oh.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-bjpwDt_z.js → sankeyDiagram-5OEKKPKP--WceN9u7.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-DyTeuxtF.js → sequenceDiagram-3UESZ5HK-NXQDJA2d.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BHPWZwpF.js → stateDiagram-AJRCARHV-Cs8Vl8wX.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-Cmof_fUq.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-LPx8DOxK.js → timeline-definition-PNZ67QCA-V9TBhcGA.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Dy6cnqv-.js → vennDiagram-CIIHVFJN-BkrjAkwE.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BtpmXexA.js → wardley-L42UT6IY-DnYl7xFk.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-BsyOd3d4.js → wardleyDiagram-YWT4CUSO-Bgjk8gUy.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BcIF0Smp.js → xychartDiagram-2RQKCTM6-DVv-I1Er.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/package.json +1 -1
- package/templates/roles/SHARED.md +5 -5
- package/templates/roles/ai-engineer/agent.json +15 -3
- package/templates/roles/content-writer/HEARTBEAT.md +1 -1
- package/templates/roles/data-engineer/HEARTBEAT.md +1 -1
- package/templates/roles/data-engineer/POLICIES.md +5 -5
- package/templates/roles/data-engineer/ROLE.md +2 -3
- package/templates/roles/data-engineer/agent.json +15 -3
- package/templates/roles/developer/HEARTBEAT.md +2 -2
- package/templates/roles/devops/HEARTBEAT.md +1 -1
- package/templates/roles/finance/ROLE.md +0 -1
- package/templates/roles/finance/agent.json +9 -2
- package/templates/roles/hr/ROLE.md +0 -1
- package/templates/roles/hr/agent.json +10 -2
- package/templates/roles/marketing/ROLE.md +0 -1
- package/templates/roles/marketing/agent.json +11 -2
- package/templates/roles/operations/ROLE.md +0 -1
- package/templates/roles/operations/agent.json +9 -2
- package/templates/roles/org-manager/HEARTBEAT.md +1 -1
- package/templates/roles/product-manager/HEARTBEAT.md +1 -1
- package/templates/roles/project-manager/HEARTBEAT.md +1 -1
- package/templates/roles/qa-engineer/HEARTBEAT.md +1 -1
- package/templates/roles/research-assistant/HEARTBEAT.md +1 -1
- package/templates/roles/reviewer/HEARTBEAT.md +1 -1
- package/templates/roles/secretary/HEARTBEAT.md +1 -1
- package/templates/roles/skill-architect/HEARTBEAT.md +1 -1
- package/templates/roles/sre/ROLE.md +0 -4
- package/templates/roles/support/ROLE.md +0 -1
- package/templates/roles/support/agent.json +9 -2
- package/templates/roles/tech-writer/HEARTBEAT.md +1 -1
- package/templates/skills/cursor-agent/SKILL.md +1 -1
- package/templates/skills/skill-building/SKILL.md +1 -1
- package/templates/teams/content-team/team.json +25 -7
- package/templates/teams/dev-squad/NORMS.md +1 -1
- package/templates/teams/dev-squad/team.json +25 -6
- package/templates/teams/engineering-pod/team.json +24 -6
- package/templates/teams/research-lab/team.json +14 -5
- package/templates/teams/startup-team/team.json +15 -4
- package/dist/web-ui/assets/ChatHelpers-DDWzuvqW.js +0 -5
- package/dist/web-ui/assets/Deliverables-DCXoaQpj.js +0 -6
- package/dist/web-ui/assets/Team-Bp5j4tGQ.js +0 -40
- package/dist/web-ui/assets/channel-Dn6ohvAA.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BNcvQTsC.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BNcvQTsC.js +0 -1
- package/dist/web-ui/assets/index-Bsf1pYmq.css +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-56cdLVMt.js +0 -1
- package/templates/skills/self-evolution/SKILL.md +0 -267
- package/templates/skills/self-evolution/skill.json +0 -20
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Dgg0L65t.js","assets/index-Bsf1pYmq.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as n,e as ko,u as Ue,j as e,t as No,a as Kr,m as hi,P as ut,f as M,w as We,M as So,A as yt,n as xs,C as An,v as Co,x as To,b as pi,y as bi,h as yi,g as ir,l as or,E as Mo,D as Po,z as _a,B as Eo,F as Ao,G as vi,H as ji,J as _o,K as Io,L as Lo,_ as wi,o as Ia,O as Ro,Q as Do,R as $o,U as La,V as Oo,W as Fo,X as Ra,k as Bo,Y as zo,Z as Wo,$ as Ho,a0 as Vo,p as qo,a1 as rr,a2 as ar}from"./index-Dgg0L65t.js";import{r as Da,p as Uo}from"./CommentInput-BJmv0Rha.js";import{resolveFormat as Go,ContentRenderer as $a}from"./ContentRenderer-DJQo68Rq.js";import{h as Bs,t as Br,i as Ko,d as zr,e as Oa,a as Fa,s as Yo,g as Ba,f as Xo,b as Qo,c as Zo}from"./ChatHelpers-DDWzuvqW.js";function en(i,a,s){let r=s.initialDeps??[],o,l=!0;function u(){var m,f,y;let w;s.key&&((m=s.debug)!=null&&m.call(s))&&(w=Date.now());const j=i();if(!(j.length!==r.length||j.some((v,D)=>r[D]!==v)))return o;r=j;let b;if(s.key&&((f=s.debug)!=null&&f.call(s))&&(b=Date.now()),o=a(...j),s.key&&((y=s.debug)!=null&&y.call(s))){const v=Math.round((Date.now()-w)*100)/100,D=Math.round((Date.now()-b)*100)/100,T=D/16,C=(p,S)=>{for(p=String(p);p.length<S;)p=" "+p;return p};console.info(`%c⏱ ${C(D,5)} /${C(v,5)} ms`,`
|
|
3
|
-
font-size: .6rem;
|
|
4
|
-
font-weight: bold;
|
|
5
|
-
color: hsl(${Math.max(0,Math.min(120-120*T,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(l&&s.skipInitialOnChange)&&s.onChange(o),l=!1,o}return u.updateDeps=m=>{r=m},u}function za(i,a){if(i===void 0)throw new Error("Unexpected undefined");return i}const Jo=(i,a)=>Math.abs(i-a)<1.01,el=(i,a,s)=>{let r;return function(...o){i.clearTimeout(r),r=i.setTimeout(()=>a.apply(this,o),s)}},Wa=i=>{const{offsetWidth:a,offsetHeight:s}=i;return{width:a,height:s}},tl=i=>i,sl=i=>{const a=Math.max(i.startIndex-i.overscan,0),s=Math.min(i.endIndex+i.overscan,i.count-1),r=[];for(let o=a;o<=s;o++)r.push(o);return r},nl=(i,a)=>{const s=i.scrollElement;if(!s)return;const r=i.targetWindow;if(!r)return;const o=u=>{const{width:m,height:f}=u;a({width:Math.round(m),height:Math.round(f)})};if(o(Wa(s)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const m=()=>{const f=u[0];if(f?.borderBoxSize){const y=f.borderBoxSize[0];if(y){o({width:y.inlineSize,height:y.blockSize});return}}o(Wa(s))};i.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()});return l.observe(s,{box:"border-box"}),()=>{l.unobserve(s)}},Ha={passive:!0},Va=typeof window>"u"?!0:"onscrollend"in window,rl=(i,a)=>{const s=i.scrollElement;if(!s)return;const r=i.targetWindow;if(!r)return;let o=0;const l=i.options.useScrollendEvent&&Va?()=>{}:el(r,()=>{a(o,!1)},i.options.isScrollingResetDelay),u=w=>()=>{const{horizontal:j,isRtl:A}=i.options;o=j?s.scrollLeft*(A&&-1||1):s.scrollTop,l(),a(o,w)},m=u(!0),f=u(!1);s.addEventListener("scroll",m,Ha);const y=i.options.useScrollendEvent&&Va;return y&&s.addEventListener("scrollend",f,Ha),()=>{s.removeEventListener("scroll",m),y&&s.removeEventListener("scrollend",f)}},al=(i,a,s)=>{if(a?.borderBoxSize){const r=a.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}return i[s.options.horizontal?"offsetWidth":"offsetHeight"]},il=(i,{adjustments:a=0,behavior:s},r)=>{var o,l;const u=i+a;(l=(o=r.scrollElement)==null?void 0:o.scrollTo)==null||l.call(o,{[r.options.horizontal?"left":"top"]:u,behavior:s})};class ol{constructor(a){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var s,r,o;return((o=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:o.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(l=>{const u=()=>{const m=l.target,f=this.indexFromElement(m);if(!m.isConnected){this.observer.unobserve(m);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(m,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var o;(o=r())==null||o.disconnect(),s=null},observe:o=>{var l;return(l=r())==null?void 0:l.observe(o,{box:"border-box"})},unobserve:o=>{var l;return(l=r())==null?void 0:l.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([r,o])=>{typeof o>"u"&&delete s[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:tl,rangeExtractor:sl,onChange:()=>{},measureElement:al,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...s}},this.notify=s=>{var r,o;(o=(r=this.options).onChange)==null||o.call(r,this,s)},this.maybeNotify=en(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const 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=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,l)=>{this.scrollAdjustments=0,this.scrollDirection=l?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=l,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(s,r)=>{const o=new Map,l=new Map;for(let u=r-1;u>=0;u--){const m=s[u];if(o.has(m.lane))continue;const f=l.get(m.lane);if(f==null||m.end>f.end?l.set(m.lane,m):m.end<f.end&&o.set(m.lane,!0),o.size===this.options.lanes)break}return l.size===this.options.lanes?Array.from(l.values()).sort((u,m)=>u.end===m.end?u.index-m.index:u.end-m.end)[0]:void 0},this.getMeasurementOptions=en(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(s,r,o,l,u,m,f)=>(this.prevLanes!==void 0&&this.prevLanes!==m&&(this.lanesChangedFlag=!0),this.prevLanes=m,this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:r,scrollMargin:o,getItemKey:l,enabled:u,lanes:m,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=en(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:r,scrollMargin:o,getItemKey:l,enabled:u,lanes:m,laneAssignmentMode:f},y)=>{if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);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(b=>{this.itemSizeCache.set(b.key,b.size)}));const w=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1);const j=this.measurementsCache.slice(0,w),A=new Array(m).fill(void 0);for(let b=0;b<w;b++){const v=j[b];v&&(A[v.lane]=b)}for(let b=w;b<s;b++){const v=l(b),D=this.laneAssignments.get(b);let T,C;const p=f==="estimate"||y.has(v);if(D!==void 0&&this.options.lanes>1){T=D;const R=A[T],k=R!==void 0?j[R]:void 0;C=k?k.end+this.options.gap:r+o}else{const R=this.options.lanes===1?j[b-1]:this.getFurthestMeasurement(j,b);C=R?R.end+this.options.gap:r+o,T=R?R.lane:b%this.options.lanes,this.options.lanes>1&&p&&this.laneAssignments.set(b,T)}const S=y.get(v),E=typeof S=="number"?S:this.options.estimateSize(b),B=C+E;j[b]={index:b,start:C,size:E,end:B,key:v,lane:T},A[T]=b}return this.measurementsCache=j,j},{key:!1,debug:()=>this.options.debug}),this.calculateRange=en(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,o,l)=>this.range=s.length>0&&r>0?ll({measurements:s,outerSize:r,scrollOffset:o,lanes:l}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=en(()=>{let s=null,r=null;const o=this.calculateRange();return o&&(s=o.startIndex,r=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,o,l,u)=>l===null||u===null?[]:s({startIndex:l,endIndex:u,overscan:r,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,o=s.getAttribute(r);return o?parseInt(o,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(o!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,o-l),m=Math.min(this.options.count-1,o+l);return s>=u&&s<=m}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((u,m)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(m))});return}const r=this.indexFromElement(s),o=this.options.getItemKey(r),l=this.elementsCache.get(o);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(o,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var o;const l=this.measurementsCache[s];if(!l)return;const u=this.itemSizeCache.get(l.key)??l.size,m=r-u;m!==0&&(((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(l,m,this):l.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=m,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(l.index),this.itemSizeCache=new Map(this.itemSizeCache.set(l.key,r)),this.notify(!1))},this.getVirtualItems=en(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const o=[];for(let l=0,u=s.length;l<u;l++){const m=s[l],f=r[m];o.push(f)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length!==0)return za(r[ki(0,r.length-1,o=>za(r[o]).start,s)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(s,r,o=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=s>=u+l?"end":"start"),r==="center"?s+=(o-l)/2:r==="end"&&(s-=l);const m=this.getMaxScrollOffset();return Math.max(Math.min(m,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[s];if(!u)return;if(r==="auto")if(u.end>=l+o-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const m=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(m,r,u.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:o="auto"}={})=>{const l=this.getOffsetForAlignment(s,r),u=this.now();this.scrollState={index:null,align:r,behavior:o,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:o="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const l=this.getOffsetForIndex(s,r);if(!l)return;const[u,m]=l,f=this.now();this.scrollState={index:s,align:m,behavior:o,startedAt:f,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const o=this.getScrollOffset()+s,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let o;if(r.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=r[r.length-1])==null?void 0:s.end)??0;else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(m=>m===null);){const m=r[u];l[m.lane]===null&&(l[m.lane]=m.end),u--}o=Math.max(...l.filter(m=>m!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:r,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(a)}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,o=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=o!==this.scrollState.lastTargetOffset;if(!u&&Jo(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.scrollState=null;return}}else this.scrollState.stableFrames=0,u&&(this.scrollState.lastTargetOffset=o,this.scrollState.behavior="auto",this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const ki=(i,a,s,r)=>{for(;i<=a;){const o=(i+a)/2|0,l=s(o);if(l<r)i=o+1;else if(l>r)a=o-1;else return o}return i>0?i-1:0};function ll({measurements:i,outerSize:a,scrollOffset:s,lanes:r}){const o=i.length-1,l=f=>i[f].start;if(i.length<=r)return{startIndex:0,endIndex:o};let u=ki(0,o,l,s),m=u;if(r===1)for(;m<o&&i[m].end<s+a;)m++;else if(r>1){const f=Array(r).fill(0);for(;m<o&&f.some(w=>w<s+a);){const w=i[m];f[w.lane]=w.end,m++}const y=Array(r).fill(s+a);for(;u>=0&&y.some(w=>w>=s);){const w=i[u];y[w.lane]=w.start,u--}u=Math.max(0,u-u%r),m=Math.min(o,m+(r-1-m%r))}return{startIndex:u,endIndex:m}}const qa=typeof document<"u"?n.useLayoutEffect:n.useEffect;function cl({useFlushSync:i=!0,...a}){const s=n.useReducer(()=>({}),{})[1],r={...a,onChange:(l,u)=>{var m;i&&u?ko.flushSync(s):s(),(m=a.onChange)==null||m.call(a,l,u)}},[o]=n.useState(()=>new ol(r));return o.setOptions(r),qa(()=>o._didMount(),[]),qa(()=>o._willUpdate()),o}function dl(i){return cl({observeElementRect:nl,observeElementOffset:rl,scrollToFn:il,...i})}function Pn({children:i,onClose:a,title:s,width:r="w-[440px]"}){return e.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:a,children:e.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:o=>o.stopPropagation(),children:[e.jsx("h3",{className:"text-base font-semibold mb-5",children:s}),i]})})}function sn({label:i,children:a}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:i}),a]})}function ul({onClose:i,onCreate:a}){const{t:s}=Ue(["team","common"]),[r,o]=n.useState(""),[l,u]=n.useState("");return e.jsx(Pn,{onClose:i,title:s("team:modals.createTeam.title"),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(sn,{label:s("team:modals.createTeam.teamName"),children:e.jsx("input",{value:r,onChange:m=>o(m.target.value),placeholder:s("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:m=>{m.key==="Enter"&&r.trim()&&a(r.trim(),l.trim()||void 0)}})}),e.jsx(sn,{label:s("team:modals.createTeam.description"),children:e.jsx("textarea",{value:l,onChange:m=>u(m.target.value),placeholder:s("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("team:modals.createTeam.hint")}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:e.jsx(No,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:e.jsx("span",{className:"text-brand-400 font-medium"}),1:e.jsx("span",{className:"text-brand-400"})}})}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:()=>r.trim()&&a(r.trim(),l.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:s("team:modals.createTeam.createTeam")})]})]})})}function ml({onClose:i,onAdd:a}){const{t:s}=Ue(["team","common"]),[r,o]=n.useState(""),[l,u]=n.useState("member"),[m,f]=n.useState(""),[y,w]=n.useState(""),[j,A]=n.useState(!1),[b,v]=n.useState(null),[D,T]=n.useState(!1),C=b?.inviteToken?`${window.location.origin}/#invite?token=${b.inviteToken}`:null,p=async()=>{if(w(""),!r.trim()){w(s("team:modals.addHuman.nameRequired"));return}if(!m.trim()){w(s("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){w(s("team:modals.addHuman.invalidEmail"));return}A(!0);try{const E=await a(r.trim(),l,m.trim());v({...E,userName:r.trim()})}catch(E){w(E instanceof Error?E.message:String(E))}finally{A(!1)}},S=()=>{C&&(navigator.clipboard.writeText(C),T(!0),setTimeout(()=>T(!1),2e3))};return b?e.jsxs(Pn,{onClose:i,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx("div",{className:"text-base font-medium mb-1",children:s("team:modals.addHuman.memberCreated",{name:b.userName})}),C?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:s("team:modals.addHuman.inviteHint")}),e.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:s("team:modals.addHuman.inviteLink")}),e.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:C})]}),e.jsx("button",{onClick:S,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${D?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(D?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):e.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:s("team:modals.addHuman.memberCreatedNoInvite")})]}),e.jsx("div",{className:"flex justify-end pt-3",children:e.jsx("button",{onClick:i,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("common:done")})})]}):e.jsx(Pn,{onClose:i,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[e.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:s("team:modals.addHuman.sharedInstanceTitle")}),s("team:modals.addHuman.sharedInstanceDesc"),e.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[s("team:modals.addHuman.orgHint")," ",e.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:s("team:modals.addHuman.orgLink")})]})]}),e.jsx(sn,{label:s("team:modals.addHuman.name"),children:e.jsx("input",{value:r,onChange:E=>o(E.target.value),placeholder:s("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),e.jsx(sn,{label:s("team:modals.addHuman.role"),children:e.jsxs("select",{value:l,onChange:E=>u(E.target.value),className:"input",children:[e.jsx("option",{value:"owner",children:s("common:role.owner")}),e.jsx("option",{value:"admin",children:s("common:role.admin")}),e.jsx("option",{value:"member",children:s("common:role.member")}),e.jsx("option",{value:"guest",children:s("common:role.guest")})]})}),e.jsx(sn,{label:s("team:modals.addHuman.emailRequired"),children:e.jsx("input",{value:m,onChange:E=>f(E.target.value),type:"email",placeholder:s("team:modals.addHuman.emailPlaceholder"),className:"input"})}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:s("team:modals.addHuman.inviteFlowHint")}),y&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:y}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:p,disabled:j,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:s(j?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function xl({teamId:i,ungrouped:a,onClose:s,onAdd:r}){const{t:o}=Ue(["team","common"]);return e.jsx(Pn,{onClose:s,title:o("team:modals.addExisting.title"),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("team:modals.addExisting.hint")}),a.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:o("team:modals.addExisting.allInTeam")}):e.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:a.map(l=>e.jsxs("button",{onClick:()=>r(l.id,l.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${l.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:l.name.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:l.name}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[l.role," · ",l.type==="agent"?o("team:modals.addExisting.typeAgent"):o("team:modals.addExisting.typeHuman")]})]}),l.status&&e.jsx("span",{className:`w-2 h-2 rounded-full ${l.status==="idle"?"bg-green-400":l.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},l.id))}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:o("common:close")})})]})})}function fl({onClose:i,onConnected:a}){const{t:s}=Ue(["team","common"]),[r,o]=n.useState(""),[l,u]=n.useState(""),[m,f]=n.useState(!1),[y,w]=n.useState(null),[j,A]=n.useState(null),b=async()=>{if(!r.trim()){u(s("team:modals.openClaw.agentNameRequired"));return}const D=r.trim().toLowerCase().replace(/\s+/g,"-");f(!0),u("");try{const T=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:D,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!T.ok){const p=await T.json().catch(()=>({}));throw new Error(p.error??`HTTP ${T.status}`)}const C=await T.json();w({externalAgentId:D,markusAgentId:C.registration?.markusAgentId,token:C.token,gatewayUrl:C.gatewayUrl})}catch(T){u(String(T))}f(!1)},v=(D,T)=>{navigator.clipboard.writeText(D),A(T),setTimeout(()=>A(null),2e3)};return e.jsx(Pn,{onClose:i,title:s("team:modals.openClaw.title"),width:"w-[560px]",children:y?(()=>{const D=y.gatewayUrl??`${window.location.origin}/api/gateway`,T=y.token?s("team:modals.openClaw.bearerTokenLine",{token:y.token}):"",C=s("team:modals.openClaw.connectionPromptBody",{gwUrl:D,externalAgentId:y.externalAgentId,tokenSection:T});return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),e.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:s("team:modals.openClaw.agentRegistered")}),e.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:e.jsx("strong",{children:r})})]}),e.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:s("team:modals.openClaw.copyInstruction")}),e.jsx("button",{onClick:()=>v(C,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${j==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(j==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),e.jsx("div",{className:"flex justify-end pt-5",children:e.jsx("button",{onClick:()=>{a()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("team:modals.openClaw.done")})})]})})():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:s("team:modals.openClaw.description")}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(sn,{label:s("team:modals.openClaw.agentName"),children:e.jsx("input",{className:"input",placeholder:s("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:D=>o(D.target.value),autoFocus:!0})}),l&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:l}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:b,disabled:m,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:s(m?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let tr=new Map;function gl({agents:i,humans:a,authUser:s,onClose:r,onCreate:o}){const{t:l}=Ue(["team","common"]),[u,m]=n.useState(""),[f,y]=n.useState(new Set),[w,j]=n.useState(""),[A,b]=n.useState(!1),v=n.useMemo(()=>{const p=[];for(const S of i)p.push({id:S.id,name:S.name,type:"agent",subtitle:S.role||"Agent"});for(const S of a)S.id!==s?.id&&p.push({id:S.id,name:S.name,type:"human",subtitle:S.email||S.role||"Human"});return p},[i,a,s]),D=n.useMemo(()=>{if(!w)return v;const p=w.toLowerCase();return v.filter(S=>S.name.toLowerCase().includes(p)||S.subtitle.toLowerCase().includes(p))},[v,w]),T=p=>{y(S=>{const E=new Set(S);return E.has(p)?E.delete(p):E.add(p),E})},C=async()=>{if(!u.trim()||f.size===0)return;b(!0);const p=[...f],S={},E={};for(const B of p){const R=v.find(k=>k.id===B);R&&(S[B]=R.type,E[B]=R.name)}await o(u.trim(),p,S,E),b(!1)};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("modals.createGroupChat.title")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:l("modals.createGroupChat.subtitle")})]}),e.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:e.jsx("input",{value:u,onChange:p=>m(p.target.value),placeholder:l("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),e.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:e.jsx("input",{value:w,onChange:p=>j(p.target.value),placeholder:l("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[D.length===0&&e.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:l("modals.createGroupChat.noMembersFound")}),D.map(p=>e.jsxs("button",{onClick:()=>T(p.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${f.has(p.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${f.has(p.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:f.has(p.id)&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx(yt,{name:p.name,size:20,bgClass:p.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate text-[11px] font-medium block",children:p.name}),e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:p.subtitle})]}),e.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${p.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:p.type==="agent"?l("modals.addExisting.typeAgent"):l("modals.addExisting.typeHuman")})]},p.id))]}),e.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modals.createGroupChat.selected",{count:f.size})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:l("common:cancel")}),e.jsx("button",{onClick:C,disabled:!u.trim()||f.size===0||A,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:l(A?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const hl=n.memo(function({authUser:a,agents:s,teams:r,humans:o,tasks:l,externalAgents:u,groupChats:m,chatMode:f,selectedAgent:y,activeChannel:w,activeDmUserId:j,onSelectAgent:A,onSelectChannel:b,onSelectDm:v,onSelectTeam:D,selectedTeamId:T,onRefreshTeams:C,onRefreshAgents:p,onRefreshHumans:S,onRefreshGroupChats:E,onViewProfile:B,onManageGroupMembers:R,unreadByAgent:k,unreadByChannel:_,width:pe,onResizeStart:$e,hidden:ne,onCollapse:$,initialLoading:Ce,previewMode:de}){const{t:I}=Ue(["team","common"]),Q=Kr(),H=hi(ut.TEAM),ee=a?.role==="owner"||a?.role==="admin",g=n.useMemo(()=>new Set(u.map(h=>h.markusAgentId).filter(Boolean)),[u]),[V,oe]=n.useState([]),[be,ge]=n.useState(new Set),[ye,Ye]=n.useState(!1),[Je,Gt]=n.useState(!1),[fs,zt]=n.useState(null),[ss,gs]=n.useState(!1),[zs,Kt]=n.useState(!1),[vt,mt]=n.useState(null),[ie,He]=n.useState(null),[qe,Be]=n.useState(null),[jt,nn]=n.useState(!1),[_n,rn]=n.useState(""),[Yt,an]=n.useState(null),[on,Qr]=n.useState(null),[ks,hs]=n.useState(null),[ps,Xt]=n.useState(!1),In=n.useRef(null),[cr,Ns]=n.useState(null),ns=n.useRef(null),Ln=n.useRef(null),[ln,cn]=n.useState(null),Ss=(h,W="success")=>{cn({message:h,type:W}),setTimeout(()=>cn(null),3e3)},[It,Wt]=n.useState(null),[Rn,dn]=n.useState(!1),Ws=n.useRef(!1);n.useEffect(()=>{if(de)return;M.governance.getSystemStatus().then(U=>{Ws.current=!0,Wt(U.globalPaused)}).catch(()=>{Ws.current=!0,Wt(!1)});const h=We.on("system:pause-all",()=>{Ws.current&&Wt(!0)}),W=We.on("system:resume-all",()=>{Ws.current&&Wt(!1)});return()=>{h(),W()}},[]),n.useEffect(()=>{if(!de)return;const h=setTimeout(()=>{const W=Ln.current,U=ns.current;W&&U&&U.scrollTo({top:W.offsetTop-U.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(h)},[de]);const un=n.useCallback(()=>{It!==null&&Cs({title:I(It?"modals.resumeAll.title":"modals.pauseAll.title"),message:I(It?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:I(It?"chat.resume":"chat.pause"),onConfirm:async()=>{dn(!0);try{It?(await M.governance.resumeAll(),Wt(!1)):(await M.governance.pauseAll(),Wt(!0))}catch{}dn(!1)}})},[It]),[Qt,Cs]=n.useState(null),Hs=(h,W,U,me,ke)=>{Cs({title:h,message:W,onConfirm:U,confirmLabel:me,checkboxes:ke})},[Lt,bs]=n.useState(null),[Ts,mn]=n.useState(null),Rt=n.useRef(null),wt=n.useRef(null),[Ht,xn]=n.useState(!1),[L,Oe]=n.useState(null),[J,ot]=n.useState(""),Ae=n.useCallback((h,W=176,U=220)=>{const me=window.innerWidth,ke=window.innerHeight,Fe=8;let Ke=h.clientX,ze=h.clientY;return Ke+W>me-Fe&&(Ke=Math.max(Fe,me-W-Fe)),ze+U>ke-Fe&&(ze=Math.max(Fe,ke-U-Fe)),Ke=Math.max(Fe,Math.min(Ke,me-W-Fe)),ze=Math.max(Fe,Math.min(ze,ke-U-Fe)),{x:Ke,y:ze}},[]),[kt,rt]=n.useState(tr),Ms=n.useMemo(()=>s.map(h=>h.id).sort().join(","),[s]);n.useEffect(()=>{if(!s.length||!H)return;let h=!1;(async()=>{const ze=[];await Promise.allSettled(s.map(async Ie=>{if(!tr.has(Ie.id))try{const{sessions:tt}=await M.sessions.listByAgent(Ie.id,1);if(!tt.length)return;const{messages:ft}=await M.sessions.getMessages(tt[0].id,1);if(ft.length){const ct=ft[0],qt=ct.metadata?.segments;let it=ct.content;if(qt&&qt.length>0){const Et=[...qt].reverse().find(ys=>ys.type==="text");Et&&Et.type==="text"&&(it=Et.content)}const st=it.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);st&&ze.push([Ie.id,st])}}catch{}})),!h&&ze.length&&rt(Ie=>{const tt=new Map(Ie);for(const[ft,ct]of ze)tt.set(ft,ct);return tr=tt,tt})})();const U=new Set(s.map(ze=>ze.id)),me=ze=>ze.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),ke=(ze,Ie)=>{if(!ze||!Ie||!U.has(ze))return;const tt=me(Ie);tt&&rt(ft=>{const ct=new Map(ft);return ct.set(ze,tt),tr=ct,ct})},Fe=We.on("chat:proactive_message",ze=>{const Ie=ze.payload;ke(Ie.agentId??"",Ie.message??"")}),Ke=We.on("chat:message",ze=>{const Ie=ze.payload,tt=Ie.senderId??Ie.agentId??"",ft=Ie.text??Ie.message??"";ke(tt,ft)});return()=>{h=!0,Fe(),Ke()}},[Ms,H]);const Nt=n.useCallback(()=>{de||M.teams.list().then(h=>oe(h.ungrouped)).catch(()=>{})},[de]);n.useEffect(()=>{Nt()},[Nt]),n.useEffect(()=>{if(!H)return;const h=We.on("team:update",Nt),W=We.on("agent:removed",Nt);return()=>{h(),W()}},[Nt,H]),n.useEffect(()=>{if(!ie&&!qe&&!Yt&&!ps&&!ks)return;const h=()=>{He(null),Be(null),an(null),hs(null),Xt(!1)},W=setTimeout(()=>document.addEventListener("click",h),0);return()=>{clearTimeout(W),document.removeEventListener("click",h)}},[ie,qe,Yt,ps,ks]);const Ps=(h,W)=>{Hs(`${I("common:delete")} "${W}"?`,I("modals.deleteTeam.message"),async U=>{const me=U?.deleteMembers??!0,ke=U?.purgeFiles??!1;await M.teams.delete(h,me,{purgeFiles:ke}),C(),Nt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},I("contextMenu.deleteTeam"),[{id:"deleteMembers",label:I("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:I("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Vs=async(h,W)=>{try{const me=await(W==="start"?M.teams.startAll:M.teams.stopAll)(h),ke=me.success?.length??0,Fe=me.failed?.length??0;Fe>0?Ss(I("batchAction.failed",{action:I(`batchAction.operation.${W}`),ok:ke,fail:Fe}),"error"):ke>0&&Ss(I("batchAction.succeeded",{count:ke,action:I(`batchAction.past.${W}`)}),"success"),p()}catch(U){Ss(I("batchAction.failedToRun",{action:I(`batchAction.operation.${W}`),error:U instanceof Error?U.message:String(U)}),"error")}},dr=async(h,W,U)=>{await M.teams.update(h,{managerId:W,managerType:U}),C()},Dn=async h=>{if(!J.trim()){Oe(null);return}await M.teams.update(h,{name:J.trim()}),Oe(null),C()},Ge=async(h,W)=>{W==="offline"?await M.agents.start(h):await M.agents.stop(h),p()},St=(h,W)=>{Hs(I("modals.removeFromTeam.title"),I("modals.removeFromTeam.message"),async()=>{await M.teams.removeMember(h,W),C(),Nt()},I("common:remove"))},Ct=(h,W,U)=>{Hs(`${I("common:remove")} "${W}"?`,I(U==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async me=>{if(U==="agent"){const ke=me?.purgeFiles??!1;await M.agents.remove(h,{purgeFiles:ke})}else await M.users.remove(h);p(),C(),S?.(),Nt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},I("common:remove"),U==="agent"?[{id:"purgeFiles",label:I("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},lt=h=>{if(h.isOrgSecretary||h.protected)return!0;if(h.teamId)return!1;const W=(h.role??"").toLowerCase().trim(),U=(h.name??"").trim();return U==="Secretary"||U==="秘书"||W==="secretary"||W.startsWith("secretary")},ur=(h,W,U)=>{const me=s.find(ke=>ke.id===W);me&<(me)||(wt.current={x:h.clientX,y:h.clientY},Rt.current=setTimeout(()=>{bs({agentId:W,fromTeamId:U}),xn(!0)},200))},Vt=h=>{if(!wt.current||!Rt.current)return;const W=Math.abs(h.clientX-wt.current.x),U=Math.abs(h.clientY-wt.current.y);(W>5||U>5)&&(Ht||(clearTimeout(Rt.current),Rt.current=null))},xt=async()=>{if(Rt.current&&(clearTimeout(Rt.current),Rt.current=null),wt.current=null,Ht&&Lt&&Ts){const h=Ts==="_ungrouped"?void 0:Ts;try{if(Lt.fromTeamId&&Lt.fromTeamId!==h&&await M.teams.removeMember(Lt.fromTeamId,Lt.agentId),h&&h!==Lt.fromTeamId){const W=s.find(U=>U.id===Lt.agentId);await M.teams.addMember(h,Lt.agentId,"agent")}C(),p(),Nt()}catch(W){Ss(I("batchAction.moveFailed",{error:W instanceof Error?W.message:String(W)}),"error")}}bs(null),mn(null),xn(!1)},Es=n.useMemo(()=>new Map(r.map(h=>[h.id,h])),[r]),Pt=n.useMemo(()=>{const h=new Map,W=[];for(const U of s)if(U.teamId&&Es.has(U.teamId)){const me=h.get(U.teamId)??[];me.push(U),h.set(U.teamId,me)}else W.push(U);return{byTeam:h,ungrouped:W}},[s,Es]),Dt=(h,W)=>{const U=f==="direct"&&y===h.id,me=g.has(h.id),ke=h.status==="offline",Fe=h.status==="idle"?"bg-green-500":h.status==="working"?"bg-blue-500 animate-pulse":h.status==="error"?"bg-red-500":"bg-gray-600",ze=(void 0)?.managerId===h.id,Ie=h.role?.toLowerCase().replace(/[-_]/g," ").trim(),tt=h.name.toLowerCase().trim(),ft=Ie&&Ie!==tt,ct=kt.get(h.id)||h.currentActivity?.label?.slice(0,60)||"",qt=h.status==="idle"?I("common:status.online"):h.status==="working"?I("common:status.working"):h.status==="error"?I("common:status.error"):I("common:status.offline");return e.jsx("div",{className:`relative mb-0.5 ${Ht&&Lt?.agentId===h.id?"opacity-40":""}`,onPointerDown:it=>ur(it,h.id,W),onPointerMove:Vt,onPointerUp:xt,children:e.jsxs("button",{onClick:()=>{Ht||A(h.id)},onContextMenu:it=>{if(!ee)return;it.preventDefault();const st=Ae(it);nn(!1),rn(""),Be({agentId:h.id,teamId:W,...st})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${Q?"":"touch-none"} ${ke?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${U?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(yt,{name:h.name,avatarUrl:h.avatarUrl,size:28,bgClass:ke?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:h.name}),ft&&e.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",h.role,")"]}),ze&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),me&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),ke&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:I("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:ct||" "})]}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(k?.get(h.id)??0)>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:k.get(h.id)}),h.mailboxDepth!=null&&h.mailboxDepth>0&&e.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:h.mailboxDepth}),e.jsx("span",{title:qt,onClick:it=>{it.stopPropagation(),B(h.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Fe}`}),Q&&ee&&e.jsx("span",{role:"button",tabIndex:0,onClick:it=>{if(it.stopPropagation(),qe?.agentId===h.id)Be(null);else{const st=Ae(it);nn(!1),rn(""),Be({agentId:h.id,teamId:W,...st})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:I("chat.moreOptions"),children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},h.id)},$n=(h,W,U,me)=>{const ke=Ht&&Ts===h&&Lt?.fromTeamId!==h,Fe=cr===h,Ke=T===h,ze=k?(Pt.byTeam.get(h)??[]).reduce((Xe,Zt)=>Xe+(k.get(Zt.id)??0),0):0,Ie=m.find(Xe=>Xe.type==="team"&&Xe.teamId===h),tt=Ie&&_?_[Ie.channelKey]??0:0,ft=ze+tt,ct=Pt.byTeam.get(h)??[],qt=ct.filter(Xe=>Xe.status==="offline").length,it=ct.length,st=it>0&&qt===it,Et=qt>0&&!st,ys=st?"bg-gray-500":Et?"bg-amber-500":"bg-green-500";return e.jsxs("div",{"data-team-id":h,className:`mb-0.5 rounded-lg transition-all duration-500 ${ke?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Fe?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{Ht&&mn(h)},onPointerLeave:()=>{Ht&&Ts===h&&mn(null)},children:[e.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[e.jsxs("button",{onClick:()=>{D&&h!=="_ungrouped"&&D(h)},onContextMenu:Xe=>{if(!ee||!W)return;Xe.preventDefault();const Zt=Ae(Xe);He({teamId:h,...Zt})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${st?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ke?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${st?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),it>0&&e.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${ys}`})]}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[L===h?e.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:J,onChange:Xe=>ot(Xe.target.value),onBlur:()=>Dn(h),onKeyDown:Xe=>{Xe.key==="Enter"&&Dn(h),Xe.key==="Escape"&&Oe(null)},onClick:Xe=>Xe.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:me}),e.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[I("chat.members_other",{count:U}),st&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:I("common:status.offline")}),Et&&e.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[qt,"/",it]})]})]}),ft>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:ft}),e.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),ee&&W&&e.jsx("button",{onClick:Xe=>{if(Xe.stopPropagation(),ie?.teamId===h)He(null);else{const Zt=Ae(Xe);He({teamId:h,...Zt})}},className:"w-7 h-7 flex items-center justify-center text-fg-muted hover:text-fg-primary rounded-md hover:bg-white/[0.08] transition-colors shrink-0",title:I("chat.moreOptions"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),ke&&Ht&&e.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:I("chat.dropHere")})]},h)},ve=n.useMemo(()=>{const h=new Map,W=[],U=[],me=[];for(const ke of m)if(ke.channelKey.startsWith("dm:a2a:"))me.push(ke);else if(ke.type==="custom")U.push(ke);else if(ke.teamId){const Fe=h.get(ke.teamId)??[];Fe.push(ke),h.set(ke.teamId,Fe)}else{const Fe=r.find(Ke=>ke.name.toLowerCase().includes(Ke.name.toLowerCase())||Ke.name.toLowerCase().includes(ke.name.toLowerCase()));if(Fe){const Ke=h.get(Fe.id)??[];Ke.push(ke),h.set(Fe.id,Ke)}else W.push(ke)}return{byTeam:h,unmatched:W,custom:U,dmChannels:me}},[m,r]),[_e,rs]=n.useState(!1),As=f==="channel"&&ve.dmChannels.some(h=>h.channelKey===w);return n.useEffect(()=>{As&&rs(!0)},[As]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`bg-surface-primary flex flex-col ${pe!=null?"shrink-0":"flex-1 min-w-0"}`,style:ne?{display:"none"}:pe!=null?{width:pe}:void 0,children:[e.jsxs("div",{className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[Q&&e.jsx(So,{}),!Q&&$&&e.jsx("button",{onClick:$,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsx("h2",{className:"text-lg font-semibold",children:I("chat.title")}),ee&&e.jsxs("div",{className:"ml-auto relative",ref:In,children:[e.jsxs("button",{onClick:()=>Xt(!ps),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[e.jsx("span",{className:"text-brand-500",children:"+"})," ",I("chat.manage"),e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${ps?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),ps&&e.jsxs("div",{ref:h=>{if(!h)return;const W=h.getBoundingClientRect(),U=window.innerWidth,me=8;W.right>U-me&&(h.style.left="auto",h.style.right="0"),W.left<me&&(h.style.left="0",h.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-secondary border border-border-default rounded-lg shadow-xl z-30 overflow-hidden",children:[e.jsxs("button",{onClick:()=>{Xt(!1),mt("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("circle",{cx:"12",cy:"5",r:"2"}),e.jsx("path",{d:"M12 7v4"}),e.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),I("chat.addAgent")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:I("chat.addAgentDesc")})]}),e.jsxs("button",{onClick:()=>{Xt(!1),mt("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),e.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),I("chat.newTeam")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:I("chat.newTeamDesc")})]}),e.jsxs("button",{onClick:()=>{Xt(!1),Gt(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M20 8v6"}),e.jsx("path",{d:"M23 11h-6"})]}),I("chat.addHuman")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:I("chat.addHumanDesc")})]}),e.jsxs("button",{onClick:()=>{Xt(!1),Kt(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),e.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),I("chat.newGroupChat")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:I("chat.newGroupChatDesc")})]}),It!==null&&e.jsxs("button",{onClick:()=>{Xt(!1),un()},disabled:Rn,className:`w-full text-left px-4 py-2.5 text-xs hover:bg-surface-elevated border-t border-border-default transition-colors disabled:opacity-50 ${It?"text-green-600":"text-red-500"}`,children:[e.jsx("div",{className:"font-medium flex items-center gap-1.5",children:It?e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",I("chat.resume")]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",I("contextMenu.stopAll")]})}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:I(It?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),e.jsxs("div",{ref:ns,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:I("chat.people")}),a&&e.jsxs("button",{onClick:()=>v(a.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="dm"&&(j===a.id||!j)?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(yt,{name:a.name,avatarUrl:a.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:a.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:I("chat.myNotes")})]}),e.jsx("span",{className:"text-fg-secondary shrink-0",children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),o.filter(h=>h.id!==a?.id).map(h=>{const W=a?.id?`dm:${[a.id,h.id].sort().join(":")}`:"",U=W&&_?_[W]??0:0;return e.jsxs("button",{onClick:()=>v(h.id),onContextMenu:me=>{if(!ee||h.id===a?.id)return;me.preventDefault();const ke=Ae(me);an({userId:h.id,...ke})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="dm"&&j===h.id?"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[e.jsx(yt,{name:h.name,avatarUrl:h.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:h.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:h.email||h.role})]}),U>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:U}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},h.id)})]}),ve.custom.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:I("chat.groups")}),ve.custom.map(h=>{const W=f==="channel"&&w===h.channelKey;return e.jsxs("button",{onClick:()=>b(h.channelKey),onContextMenu:U=>{U.preventDefault();const me=Ae(U);hs({gcId:h.id,...me})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${W?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:h.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:I("chat.members_other",{count:h.memberCount??0})})]})]},h.id)})]}),Ce?e.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((h,W)=>e.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[e.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),e.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},W))}):s.length===0&&r.length===0?e.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:I("chat.noAgentsYet")}):null,ve.unmatched.map(h=>{const W=_?.[h.channelKey]??0;return e.jsxs("button",{onClick:()=>b(h.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${f==="channel"&&w===h.channelKey?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:h.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:I("chat.groupChat")})]}),W>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:W}):h.memberCount!==void 0&&h.memberCount>0?e.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:h.memberCount}):null]},h.id)}),Pt.ungrouped.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:I("chat.agents")}),Pt.ungrouped.map(h=>Dt(h))]}),r.length>0&&e.jsxs("div",{className:"mb-2",ref:Ln,children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:I("chat.teams")}),r.map(h=>{const W=Pt.byTeam.get(h.id)??[],U=h.members?.length||W.length;return $n(h.id,h,U,h.name)})]}),r.length===0&&Pt.ungrouped.length===0&&s.length>0&&s.map(h=>Dt(h)),ve.dmChannels.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsxs("button",{onClick:()=>rs(h=>!h),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${_e?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),I("chat.agentDMs"),e.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:ve.dmChannels.length})]}),_e&&ve.dmChannels.map(h=>{const W=f==="channel"&&w===h.channelKey,U=_?.[h.channelKey]??0,me=h.name.replace(/^DM:\s*/,"");return e.jsxs("button",{onClick:()=>b(h.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${W?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:me}),U>0&&e.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:U})]},h.id)})]})]})]}),$e&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:$e,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),ie&&(()=>{const h=Pt.byTeam.get(ie.teamId)??[],W=h.some(me=>me.status==="offline"),U=h.some(me=>me.status!=="offline");return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:ie.x,top:ie.y},onClick:me=>me.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{const me=Es.get(ie.teamId);me&&(Oe(ie.teamId),ot(me.name)),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),I("contextMenu.renameTeam")]}),W&&e.jsxs("button",{onClick:()=>{Vs(ie.teamId,"start"),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),I("contextMenu.startAll")]}),U&&e.jsxs("button",{onClick:()=>{Vs(ie.teamId,"stop"),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),I("contextMenu.stopAll")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{He(null),xs.navigate(ut.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),I("chat.addAgent")]}),V.length>0&&e.jsxs("button",{onClick:()=>{He(null),zt(ie.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),e.jsx("polyline",{points:"17 11 19 13 23 9"})]}),I("contextMenu.addExisting")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{const me=Es.get(ie.teamId);me&&Ps(ie.teamId,me.name),He(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),I("contextMenu.deleteTeam")]})]})})(),qe&&(()=>{const h=s.find(Fe=>Fe.id===qe.agentId);if(!h||!ee)return null;const U=(qe.teamId?Es.get(qe.teamId):void 0)?.managerId===h.id,me=h.id===a?.id,ke=lt(h);return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:qe.x,top:qe.y,maxHeight:Math.max(160,window.innerHeight-qe.y-8)},onClick:Fe=>Fe.stopPropagation(),children:[ke&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:I("contextMenu.orgSecretaryProtected")}),e.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),e.jsxs("button",{onClick:()=>{Be(null),B(h.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),I("contextMenu.viewProfile")]}),h.status==="offline"?e.jsxs("button",{onClick:()=>{Ge(h.id,"offline"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),I("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{Ge(h.id,h.status??"idle"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),I("contextMenu.stop")]}),!ke&&qe.teamId&&!U&&e.jsxs("button",{onClick:()=>{dr(qe.teamId,h.id,"agent"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),I("contextMenu.setAsManager")]}),!ke&&qe.teamId&&e.jsxs("button",{onClick:()=>{St(qe.teamId,h.id),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),I("contextMenu.removeFromTeam")]}),!ke&&(()=>{const Fe=r.filter(Ie=>Ie.id!==qe.teamId);if(Fe.length===0)return null;const Ke=_n.trim().toLowerCase(),ze=Ke?Fe.filter(Ie=>Ie.name.toLowerCase().includes(Ke)):Fe;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>nn(Ie=>!Ie),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:I("contextMenu.moveTo")}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${jt?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),jt&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:Ie=>Ie.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:_n,onChange:Ie=>rn(Ie.target.value),onKeyDown:Ie=>Ie.stopPropagation(),placeholder:I("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:ze.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:I("contextMenu.moveToEmpty")}):ze.map(Ie=>e.jsx("button",{type:"button",onClick:async()=>{qe.teamId&&await M.teams.removeMember(qe.teamId,h.id),await M.teams.addMember(Ie.id,h.id,"agent"),C(),p(),Nt(),Be(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Ie.name,children:Ie.name},Ie.id))})]})]})})(),!ke&&!me&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{Ct(h.id,h.name,"agent"),Be(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),I("contextMenu.removeFromOrg")]})]})]})})(),Yt&&(()=>{const h=o.find(W=>W.id===Yt.userId);return!h||!ee?null:e.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Yt.x,top:Yt.y},onClick:W=>W.stopPropagation(),children:e.jsxs("button",{onClick:()=>{Ct(h.id,h.name,"human"),an(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),I("contextMenu.removeFromOrg")]})})})(),ye&&e.jsx(ul,{onClose:()=>Ye(!1),onCreate:async(h,W)=>{try{const{team:U}=await M.teams.create(h,W);Ye(!1),C(),Ns(U.id),setTimeout(()=>{document.querySelector(`[data-team-id="${U.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>Ns(null),3e3)}catch(U){Ss(I("chat.failedToCreateTeam",{message:U instanceof Error?U.message:String(U)}),"error")}}}),Je&&e.jsx(ml,{onClose:()=>{Gt(!1),S?.()},onAdd:async(h,W,U)=>{const{inviteToken:me}=await M.users.create(h,W,void 0,U);return S?.(),{inviteToken:me}}}),fs!==null&&e.jsx(xl,{teamId:fs,ungrouped:V,onClose:()=>zt(null),onAdd:async(h,W)=>{await M.teams.addMember(fs,h,W),zt(null),C(),Nt()}}),ss&&e.jsx(fl,{onClose:()=>gs(!1),onConnected:()=>{gs(!1),p(),C()}}),ks&&(()=>{const h=m.find(W=>W.id===ks.gcId);return h?e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:ks.x,top:ks.y},onClick:W=>W.stopPropagation(),children:[h.type==="custom"&&e.jsxs("button",{onClick:()=>{hs(null),R?R(h.channelKey):b(h.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),I("contextMenu.manageMembers")]}),e.jsxs("button",{onClick:async()=>{hs(null),Hs(I("modals.deleteGroupChat.title"),I("modals.deleteGroupChat.message",{name:h.name}),async()=>{await M.groupChats.delete(h.id),E()},I("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),I("modals.deleteGroupChat.menuLabel")]})]}):null})(),zs&&e.jsx(gl,{agents:s,humans:o,authUser:a,onClose:()=>Kt(!1),onCreate:async(h,W,U,me)=>{await M.groupChats.create({name:h,memberIds:W,memberTypes:U,memberNames:me,creatorId:a?.id,creatorName:a?.name}),Kt(!1),E()}}),vt&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>mt(null),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:I(vt==="agent"?"chat.addAgent":"chat.newTeam")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:I("chat.methodChoiceSubtitle")})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>{const h=vt;mt(null);const W=s.find(U=>U.role==="secretary")??s.find(U=>U.name?.toLowerCase().includes("secretary"));W?(A(W.id),xs.navigate(ut.TEAM,{agentId:W.id,prefillMessage:I(h==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):h==="agent"?xs.navigate(ut.STORE):Ye(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),e.jsx("path",{d:"M20 3v4"}),e.jsx("path",{d:"M22 5h-4"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:I("chat.methodSecretary")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:I("chat.methodSecretaryDesc")})]}),e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:I("chat.recommended")})]}),e.jsxs("button",{onClick:()=>{const h=vt;mt(null),h==="agent"?xs.navigate(ut.STORE):Ye(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:I("chat.methodManual")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:I(vt==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),e.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:e.jsx("button",{onClick:()=>mt(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:I("common:cancel")})})]})}),Qt&&e.jsx(An,{title:Qt.title,message:Qt.message,confirmLabel:Qt.confirmLabel,checkboxes:Qt.checkboxes,onConfirm:h=>{Qt.onConfirm(h),Cs(null)},onCancel:()=>Cs(null)}),ln&&e.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${ln.type==="error"?"bg-red-500/10 text-red-500 border border-red-500/30":"bg-surface-elevated/95 text-fg-primary border border-border-default/50"}`,children:ln.message})]})});function Ua({team:i,agents:a,humans:s,authUser:r,groupChat:o,chatMode:l,selectedAgent:u,activeChannel:m,teams:f,onSelectAgent:y,onSelectChannel:w,onSelectDm:j,onBack:A,onViewProfile:b,onRefreshAgents:v,onRefreshTeams:D,unreadByAgent:T,width:C,onResizeStart:p}){const{t:S}=Ue(["team","common"]),E=r?.role==="owner"||r?.role==="admin",B=n.useMemo(()=>a.filter(g=>g.teamId===i.id),[a,i.id]),R=n.useMemo(()=>{const g=new Set((i.members??[]).filter(V=>V.type==="human").map(V=>V.id));return s.filter(V=>g.has(V.id))},[i.members,s]),k=o&&l==="channel"&&m===o.channelKey,[_,pe]=n.useState(null),[$e,ne]=n.useState(!1),[$,Ce]=n.useState(""),de=n.useCallback((g,V=176,oe=220)=>{const be=window.innerWidth,ge=window.innerHeight,ye=8;let Ye=g.clientX,Je=g.clientY;return Ye+V>be-ye&&(Ye=Math.max(ye,be-V-ye)),Je+oe>ge-ye&&(Je=Math.max(ye,ge-oe-ye)),Ye=Math.max(ye,Math.min(Ye,be-V-ye)),Je=Math.max(ye,Math.min(Je,ge-oe-ye)),{x:Ye,y:Je}},[]);n.useEffect(()=>{if(!_)return;const g=()=>pe(null),V=setTimeout(()=>document.addEventListener("click",g),0);return()=>{clearTimeout(V),document.removeEventListener("click",g)}},[_]);const I=n.useCallback(async(g,V)=>{V==="offline"?await M.agents.start(g):await M.agents.stop(g),v()},[v]),Q=n.useCallback(async g=>{await M.teams.update(i.id,{managerId:g,managerType:"agent"}),D()},[i.id,D]),H=n.useCallback(async g=>{await M.teams.removeMember(i.id,g),D(),v()},[i.id,D,v]),ee=n.useCallback(async(g,V)=>{await M.teams.removeMember(i.id,g),await M.teams.addMember(V,g,"agent"),D(),v()},[i.id,D,v]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-surface-primary flex flex-col shrink-0",style:C!=null?{width:C}:{width:260},children:[e.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:A,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:S("common:back",{defaultValue:"Back"}),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"truncate font-semibold text-sm",children:i.name}),i.description&&e.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:i.description})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[o&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:S("chat.groupChat",{defaultValue:"Group Chat"})}),e.jsxs("button",{onClick:()=>w(o.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${k?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:i.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:S("chat.members_other",{count:o.memberCount||B.length+R.length})})]})]})]}),B.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[S("chat.agents",{defaultValue:"Agents"}),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:B.length})]}),B.map(g=>{const V=l==="direct"&&u===g.id,oe=i.managerId===g.id,be=g.status==="offline",ge=g.status==="idle"?"bg-green-500":g.status==="working"?"bg-blue-500 animate-pulse":g.status==="error"?"bg-red-500":"bg-gray-600";return e.jsxs("button",{onClick:()=>y(g.id),onContextMenu:ye=>{if(!E)return;ye.preventDefault();const Ye=de(ye);ne(!1),Ce(""),pe({agentId:g.id,...Ye})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${be?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${V?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(yt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:be?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:g.name}),oe&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),be&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:S("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:g.role||" "})]}),(T?.get(g.id)??0)>0&&e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:T.get(g.id)}),e.jsx("span",{title:g.status,onClick:ye=>{ye.stopPropagation(),b(g.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${ge}`})]},g.id)})]}),R.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[S("chat.people"),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:R.length})]}),R.map(g=>{const V=g.id===r?.id;return e.jsxs("button",{onClick:()=>j(g.id),className:"w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary hover:bg-white/[0.08]",children:[e.jsx(yt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[g.name,V?` (${S("chat.you",{defaultValue:"You"})})`:""]}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:g.email||g.role})]}),e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},g.id)})]}),B.length===0&&R.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:S("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),p&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:p,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),_&&(()=>{const g=B.find(oe=>oe.id===_.agentId);if(!g||!E)return null;const V=i.managerId===g.id;return e.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:_.x,top:_.y,maxHeight:Math.max(160,window.innerHeight-_.y-8)},onClick:oe=>oe.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{pe(null),b(g.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),S("contextMenu.viewProfile")]}),g.status==="offline"?e.jsxs("button",{onClick:()=>{I(g.id,"offline"),pe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),S("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{I(g.id,g.status??"idle"),pe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),S("contextMenu.stop")]}),!V&&e.jsxs("button",{onClick:()=>{Q(g.id),pe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),S("contextMenu.setAsManager")]}),e.jsxs("button",{onClick:()=>{H(g.id),pe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),S("contextMenu.removeFromTeam")]}),(()=>{const oe=f.filter(ye=>ye.id!==i.id);if(oe.length===0)return null;const be=$.trim().toLowerCase(),ge=be?oe.filter(ye=>ye.name.toLowerCase().includes(be)):oe;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>ne(ye=>!ye),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:S("contextMenu.moveTo")}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${$e?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),$e&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:ye=>ye.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:$,onChange:ye=>Ce(ye.target.value),onKeyDown:ye=>ye.stopPropagation(),placeholder:S("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:ge.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:S("contextMenu.moveToEmpty")}):ge.map(ye=>e.jsx("button",{type:"button",onClick:()=>{ee(g.id,ye.id),pe(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:ye.name,children:ye.name},ye.id))})]})]})})(),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:async()=>{await M.agents.remove(g.id),v(),pe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),S("contextMenu.removeFromOrg")]})]})})()]})}function pl(i){const a=i.trim();return!a||a==="about:blank"?a:/^[a-z][a-z0-9+.-]*:/i.test(a)?/^file:/i.test(a)?yl(a):a:bl(a)?Ni(a):`https://${a}`}function bl(i){return!!(i.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(i)||i.startsWith("\\\\"))}function Ni(i){const a=i.replace(/\\/g,"/");return a.startsWith("//")?`file:${Wr(a)}`:/^[a-zA-Z]:\//.test(a)?`file:///${Wr(a)}`:`file://${Wr(a)}`}function yl(i){try{return new URL(i).href}catch{let a=i.replace(/^file:/i,"").replace(/\\/g,"/");return a.startsWith("//")&&(a=a.replace(/^\/\/(localhost)?/i,""),!a.startsWith("/")&&!/^[a-zA-Z]:\//.test(a)&&(a=`/${a}`)),/^\/[a-zA-Z]:\//.test(a)&&(a=a.slice(1)),!a.startsWith("/")&&!/^[a-zA-Z]:\//.test(a)&&(a=`/${a}`),Ni(a)}}function Wr(i){return encodeURI(i).replace(/#/g,"%23")}function vl({url:i,browserId:a,className:s}){const{t:r}=Ue("common"),o=n.useId().replace(/:/g,""),l=a||`eb_${o}`,u=!a,m=n.useRef(null),f=n.useRef(null),y=n.useRef(null),[w,j]=n.useState(i==="about:blank"?"":i),[A,b]=n.useState(!1),[v,D]=n.useState(!1),[T,C]=n.useState(!1),[p,S]=n.useState(null),[E,B]=n.useState(null),[R,k]=n.useState(!1),_=typeof window<"u"?window.markusDesktop?.browser:void 0,pe=typeof window<"u"?window.markusDesktop?.platform:void 0;y.current=E;const $e=r(pe==="darwin"?"browserFolderAppFinder":pe==="win32"?"browserFolderAppExplorer":"browserFolderAppGeneric");return n.useEffect(()=>{if(!_)return;let ne=!1;return(async()=>{const $=await _.getState(l);if(ne||($.ok?i&&$.url!==i&&!$.directoryPath?(C(!0),await _.navigate(l,i)):i&&$.directoryPath&&$.url!==i&&await _.navigate(l,i):(C(!0),await _.create(l,i)),ne))return;const Ce=await _.getState(l);ne||!Ce.ok||(document.activeElement!==f.current&&j(Ce.url&&Ce.url!=="about:blank"?Ce.url:i==="about:blank"?"":i),C(!!Ce.isLoading),S(Ce.loadError??null),B(Ce.directoryPath??null))})(),()=>{ne=!0,u&&_.destroy(l)}},[_,l,i,u]),n.useEffect(()=>{if(i!=="about:blank")return;const ne=window.setTimeout(()=>{f.current?.focus(),f.current?.select()},0);return()=>clearTimeout(ne)},[i,l]),n.useEffect(()=>{if(_?.onPageEvent)return _.onPageEvent(ne=>{if(ne.browserId===l){if(ne.type==="directory"){B(ne.directoryPath||null),C(!1),S(null),ne.url&&document.activeElement!==f.current&&j(ne.url);return}if(ne.type==="loading"){C(!0),S(null),B(null);return}if(ne.type==="loaded"){if(C(!1),y.current)return;ne.url&&document.activeElement!==f.current&&j(ne.url==="about:blank"?"":ne.url);return}if(ne.type==="load-failed"){if(C(!1),y.current)return;S(ne.error||"Load failed"),ne.url&&document.activeElement!==f.current&&j(ne.url==="about:blank"?"":ne.url);return}ne.type==="navigated"&&ne.url&&document.activeElement!==f.current&&(y.current||j(ne.url==="about:blank"?"":ne.url))}})},[_,l]),n.useEffect(()=>{if(!_||!m.current)return;const ne=m.current;let $=!0;const Ce=()=>{let ee=ne;for(;ee;){const g=getComputedStyle(ee);if(g.visibility==="hidden"||g.display==="none")return!1;ee=ee.parentElement}return!0},de=()=>{if(!$)return;if(!To()||!Ce()||Co()||y.current){_.setBounds(l,{x:0,y:0,width:0,height:0},!1);return}const ee=ne.getBoundingClientRect();_.setBounds(l,{x:Math.round(ee.left),y:Math.round(ee.top),width:Math.round(ee.width),height:Math.round(ee.height)},ee.width>2&&ee.height>2)};de();const I=new ResizeObserver(de);I.observe(ne),window.addEventListener("resize",de),window.addEventListener("scroll",de,!0),window.addEventListener("markus:embedded-browser-resync",de),window.addEventListener("markus:native-browser-overlay",de),window.addEventListener("markus:native-browser-page",de);const Q=setInterval(()=>{$&&_.getState(l).then(ee=>{if(!$||!ee.ok)return;const g=ee.directoryPath??null;B(g),ee.url&&document.activeElement!==f.current&&(g||ee.url!=="about:blank")&&j(ee.url==="about:blank"?"":ee.url),b(!!ee.canGoBack),D(!!ee.canGoForward),C(!!ee.isLoading),ee.loadError!==void 0&&S(g?null:ee.loadError??null)})},800),H=()=>{_.setBounds(l,{x:0,y:0,width:0,height:0},!1)};return window.addEventListener("pagehide",H),()=>{$=!1,I.disconnect(),window.removeEventListener("resize",de),window.removeEventListener("scroll",de,!0),window.removeEventListener("markus:embedded-browser-resync",de),window.removeEventListener("markus:native-browser-overlay",de),window.removeEventListener("markus:native-browser-page",de),window.removeEventListener("pagehide",H),clearInterval(Q),_.setBounds(l,{x:0,y:0,width:0,height:0},!1)}},[_,l]),n.useEffect(()=>{window.dispatchEvent(new Event("markus:embedded-browser-resync"))},[E]),_?e.jsxs("div",{className:`flex flex-col h-full min-h-0 min-w-0 w-full ${s??""}`,children:[e.jsxs("div",{className:"shrink-0 relative mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5 border border-border-default rounded-lg bg-surface-elevated",children:[e.jsx("button",{disabled:!A,onClick:()=>{_.action(l,"back")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Back",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("button",{disabled:!v,onClick:()=>{_.action(l,"forward")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Forward",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})}),e.jsx("button",{onClick:()=>{T?_.action(l,"stop"):_.action(l,"reload")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay",title:T?"Stop":"Reload",children:T?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"animate-spin",children:e.jsx("path",{d:"M12 2a10 10 0 0 1 10 10",strokeLinecap:"round"})}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),e.jsx("form",{className:"flex-1 min-w-0",onSubmit:ne=>{ne.preventDefault();let $=w.trim();$&&($=pl($),C(!0),S(null),B(null),_.navigate(l,$),j($))},children:e.jsx("input",{ref:f,value:w,onChange:ne=>j(ne.target.value),placeholder:r("browserUrlPlaceholder"),spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md text-fg-primary outline-none focus:border-brand-500"})}),T&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary px-1 select-none",children:r("browserLoading")})]}),e.jsx("div",{className:`absolute left-2 right-2 bottom-0 h-0.5 overflow-hidden rounded-full transition-opacity ${T?"opacity-100":"opacity-0"}`,"aria-hidden":!T,children:e.jsx("div",{className:"h-full w-1/3 bg-brand-500 animate-[browser-load_1.1s_ease-in-out_infinite]"})})]}),p&&!T&&!E&&e.jsx("div",{className:"shrink-0 mb-2 px-2.5 py-1.5 text-[11px] text-amber-600 dark:text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg",children:p}),e.jsx("div",{ref:m,className:"flex-1 min-h-0 min-w-0 w-full rounded-lg border border-border-default bg-surface-elevated/30 overflow-hidden",children:E&&e.jsxs("div",{className:"h-full w-full flex flex-col items-center justify-center gap-4 px-6 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-surface-elevated border border-border-default flex items-center justify-center text-fg-secondary",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z",strokeLinejoin:"round"})})}),e.jsxs("div",{className:"space-y-1.5 max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-fg-primary",children:r("browserFolderTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary break-all",children:E})]}),e.jsx("button",{type:"button",disabled:R,onClick:()=>{k(!0),M.system.openPath(E).catch(()=>M.files.reveal(E)).finally(()=>k(!1))},className:"px-3.5 py-2 text-xs rounded-lg bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white transition-colors",children:R?r("browserFolderOpening"):r("browserFolderOpen",{app:$e})})]})}),e.jsx("style",{children:`
|
|
6
|
-
@keyframes browser-load {
|
|
7
|
-
0% { transform: translateX(-120%); }
|
|
8
|
-
100% { transform: translateX(360%); }
|
|
9
|
-
}
|
|
10
|
-
`})]}):e.jsxs("div",{className:`space-y-3 ${s??""}`,children:[e.jsx("p",{className:"text-sm text-fg-secondary break-all",children:i}),e.jsx("button",{onClick:()=>window.open(i,"_blank","noopener,noreferrer"),className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:"Open in browser"})]})}function Ga(i){return/^https?:\/\//i.test(i)}function jl(i){return i.kind==="deliverable"?i.deliverable.reference??"":i.kind==="url"?i.url:i.path}function wl(i){return i.kind==="deliverable"?i.deliverable.title||i.deliverable.reference||"":i.kind==="url"?i.title||i.url:i.title||i.path.split(/[/\\]/).pop()||i.path}function kl(i,a){if(i.kind==="file")return`file:${i.path}:${a??""}`;if(i.kind==="url")return`url:${i.browserId||i.url}:${a??""}`;const s=i.deliverable;return`deliverable:${s.id||s.reference||s.title||"unknown"}:${a??""}`}function Hr(i){return i==null||!Number.isFinite(i)?"":i<1024?`${i} B`:i<1024*1024?`${(i/1024).toFixed(1)} KB`:`${(i/(1024*1024)).toFixed(1)} MB`}function Nl({payload:i,onClose:a,width:s,onResizeStart:r,onAddToChat:o,tabs:l,activeTabId:u,onSelectTab:m,onCloseTab:f,onNewTab:y,fullscreen:w,onToggleFullscreen:j}){const{t:A}=Ue(["deliverables","agent","common"]),[b,v]=n.useState({mode:"loading"}),[D,T]=n.useState(!1),[C,p]=n.useState(null),S=n.useRef(null),E=n.useRef(null),B=n.useRef(null),R=jl(i),k=wl(i),_=(l?.length??0)>=1,pe=kl(i,u);n.useEffect(()=>{if(!u)return;const H=B.current,ee=E.current;if(!H||!ee)return;const g=requestAnimationFrame(()=>{H.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(g)},[u,l?.length]),n.useEffect(()=>{const H=ee=>{ee.key==="Escape"&&(w&&j?j():a())};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[a,w,j]),n.useEffect(()=>{let H=!1;return p(null),v({mode:"loading"}),i.kind==="deliverable"&&i.deliverable.artifactType&&i.deliverable.artifactData?(v({mode:"artifact",summary:i.deliverable.summary||i.deliverable.title||""}),()=>{H=!0}):i.kind==="url"?(v({mode:"url",url:i.url,browserId:i.browserId}),()=>{H=!0}):R?Ga(R)?(v({mode:"url",url:R}),()=>{H=!0}):i.kind==="deliverable"&&i.deliverable.type==="directory"?(v({mode:"unpreviewable",reference:R,isDirectory:!0}),()=>{H=!0}):(M.files.preview(R).then(g=>{if(H)return;if(g.type==="image"){const oe=g.content?`data:${g.mimeType||"image/png"};base64,${g.content}`:g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(R));v({mode:"image",src:oe,name:g.name||k});return}if(g.type==="audio"){const oe=g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(R));v({mode:"audio",src:oe,name:g.name||k,mimeType:g.mimeType||"audio/mpeg",size:g.size});return}if(g.type==="video"){const oe=g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(R));v({mode:"video",src:oe,name:g.name||k,mimeType:g.mimeType||"video/mp4",size:g.size});return}if(g.type==="binary"){v({mode:"binary",name:g.name||k,reference:g.path||R,size:g.size,extension:g.extension});return}if(typeof g.content!="string"){v({mode:"unpreviewable",reference:R,isDirectory:!1});return}const V=Go({format:i.kind==="deliverable"?i.deliverable.format:void 0,reference:R,content:g.content});v({mode:"content",content:g.content,format:V})}).catch(()=>{H||v({mode:"unpreviewable",reference:R,isDirectory:!1})}),()=>{H=!0}):(v({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{H=!0})},[pe,i,R,k]);const $e=k||R,ne=n.useCallback((H,ee)=>{const g=H.length>40?`${H.slice(0,24)}…${H.slice(-12)}`:H;return ee?{label:`🌐 ${g}`,content:["[html-selection]",`Text: "${H}"`,`CSS Selector: ${ee.cssSelector}`,`XPath: ${ee.xpath}`,R?`File: ${R}`:""].filter(Boolean).join(`
|
|
11
|
-
`)}:{label:`“${g}”`,content:`${A("deliverables:chat.selectedFrom",{defaultValue:"Selected from"})} ${$e}:
|
|
12
|
-
|
|
13
|
-
"""
|
|
14
|
-
${H}
|
|
15
|
-
"""`}},[R,$e,A]),$=n.useCallback((H,ee)=>{!H.trim()||!o||(o(ne(H.trim(),ee)),p(null),window.getSelection()?.removeAllRanges())},[o,ne]),Ce=n.useCallback(H=>{if(!H.text.trim()||!o)return;const ee=S.current?.querySelector("iframe")?.getBoundingClientRect(),g=(ee?.left??0)+H.rect.x+H.rect.width/2,V=(ee?.top??0)+H.rect.y;p({x:g,y:V,text:H.text,htmlMeta:{xpath:H.xpath,cssSelector:H.cssSelector}})},[o]);n.useEffect(()=>{const H=S.current;if(!H||!o)return;const ee=()=>{requestAnimationFrame(()=>{const V=window.getSelection(),oe=V?.toString().trim();if(!oe||!V?.rangeCount){p(null);return}const be=V.getRangeAt(0);if(!H.contains(be.commonAncestorContainer)){p(null);return}const ge=be.getBoundingClientRect();p({x:ge.left+ge.width/2,y:ge.top,text:oe})})},g=V=>{const oe=document.getElementById("right-panel-selection-toolbar");oe&&oe.contains(V.target)||p(null)};return H.addEventListener("mouseup",ee),document.addEventListener("mousedown",g),()=>{H.removeEventListener("mouseup",ee),document.removeEventListener("mousedown",g)}},[o,b.mode]);const de=()=>{M.files.reveal(R).catch(()=>{})},I=()=>{navigator.clipboard?.writeText(R).then(()=>{T(!0),setTimeout(()=>T(!1),1500)}).catch(()=>{})},Q=!!R&&!Ga(R)&&(i.kind==="file"||i.kind==="deliverable");return e.jsxs(e.Fragment,{children:[!w&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:e.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),e.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${w?"flex-1 min-w-0":"shrink-0"}`,style:w?void 0:{width:s},"data-right-panel":!0,children:[e.jsxs("header",{className:"h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default",children:[_||y?e.jsxs("div",{ref:E,className:"flex-1 min-w-0 flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-thin",onWheel:H=>{const ee=H.currentTarget;ee.scrollWidth<=ee.clientWidth||Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(ee.scrollLeft+=H.deltaY,H.preventDefault())},children:[l?.map(H=>{const ee=H.id===u;return e.jsxs("button",{type:"button",ref:ee?B:void 0,className:`group shrink-0 flex items-center gap-1 max-w-[160px] pl-2.5 pr-1 py-1 rounded-md text-[11px] cursor-pointer border transition-colors ${ee?"bg-surface-elevated border-border-default text-fg-primary":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>m?.(H.id),title:H.title,children:[e.jsx("span",{className:"truncate min-w-0",children:H.title}),f&&e.jsx("span",{role:"button",tabIndex:0,onClick:g=>{g.stopPropagation(),f(H.id)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),f(H.id))},className:`shrink-0 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ee?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:A("common:closeTab",{defaultValue:"Close tab"}),"aria-label":A("common:closeTab",{defaultValue:"Close tab"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},H.id)}),y&&e.jsx("button",{type:"button",onClick:y,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:A("common:newTab",{defaultValue:"New Tab"}),"aria-label":A("common:newTab",{defaultValue:"New Tab"}),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):e.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:R||k,children:k}),e.jsxs("div",{className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[i.kind==="deliverable"&&e.jsx("button",{onClick:()=>xs.navigate(ut.DELIVERABLES,{openDeliverable:i.deliverable.id}),title:A("agent:deliverables.openInPage",{defaultValue:"Open in page"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),Q&&e.jsx("button",{onClick:de,title:A("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":A("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),j&&e.jsx("button",{onClick:j,title:w?A("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):A("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:w?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"4 14 10 14 10 20"}),e.jsx("polyline",{points:"20 10 14 10 14 4"}),e.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("polyline",{points:"9 21 3 21 3 15"}),e.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),e.jsx("button",{onClick:a,title:A("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":A("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),e.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${b.mode==="url"?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[b.mode==="loading"&&e.jsxs("div",{className:"animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),e.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),b.mode==="image"&&e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("img",{src:b.src,alt:b.name,className:"max-w-full rounded-lg object-contain"}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:b.name})]}),b.mode==="audio"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 18V5l12-2v13"}),e.jsx("circle",{cx:"6",cy:"18",r:"3"}),e.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:b.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[b.mimeType,b.size!=null?` · ${Hr(b.size)}`:""]})]})]}),e.jsx("audio",{controls:!0,preload:"metadata",src:b.src,className:"w-full"})]}),b.mode==="video"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[e.jsx("video",{controls:!0,preload:"metadata",src:b.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:[b.name,b.size!=null?` · ${Hr(b.size)}`:""]})]}),b.mode==="binary"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(b.extension||"file").replace(/^\./,"")||"file"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:b.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[A("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),b.size!=null?` · ${Hr(b.size)}`:""]})]})]}),b.reference&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:()=>{M.files.reveal(b.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:A("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),b.mode==="content"&&e.jsx("div",{ref:S,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:e.jsx($a,{content:b.content,format:b.format,className:"text-fg-secondary text-sm",onHtmlSelection:Ce})}),b.mode==="artifact"&&e.jsx("div",{ref:S,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:e.jsx($a,{content:b.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),b.mode==="url"&&e.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:e.jsx(vl,{url:b.url,browserId:b.browserId,className:"flex-1 min-h-0"})}),b.mode==="unpreviewable"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-fg-secondary",children:b.isDirectory?A("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):A("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),b.reference&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:de,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:A("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:b.reference}),e.jsx("button",{onClick:de,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:A("common:open",{defaultValue:"Open"})}),e.jsx("button",{onClick:I,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${D?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:D?A("common:copied",{defaultValue:"Copied"}):A("common:copy",{defaultValue:"Copy"})})]})]})]},pe)]}),C&&o&&e.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden",style:{left:C.x,top:C.y-8},children:e.jsxs("button",{onMouseDown:H=>{H.preventDefault(),H.stopPropagation(),$(C.text,C.htmlMeta)},className:"px-3 py-1.5 text-xs text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),A("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const Sl=n.lazy(()=>wi(()=>import("./index-Dgg0L65t.js").then(i=>i.am),__vite__mapDeps([0,1])).then(i=>({default:i.MarkdownMessage}))),Yr=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function Ur(i,a){return a(`agent:profilePage.taskStatus.${i}`,{defaultValue:i.replace(/_/g," ")})}function Si(i,a){const r={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[i];return r?a(r):i}const Ci={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function tn(i){return i>=1e6?`${(i/1e6).toFixed(1)}M`:i>=1e3?`${(i/1e3).toFixed(1)}K`:i.toLocaleString()}function Ka({agentId:i,onBack:a,inline:s,defaultTab:r,onSwipeBack:o,highlightMailboxId:l,authUser:u,headless:m,activeTab:f}){const{t:y}=Ue(["agent","common"]),w=Kr(),[j,A]=n.useState(null),[b,v]=n.useState(null),[D,T]=n.useState(r??"overview"),C=m&&f?f:D,[p,S]=n.useState(null),E=n.useMemo(()=>Yr.map($=>({...$,label:y(`agent:tabs.${$.key}`)})),[y]),B=n.useMemo(()=>E.map($=>({id:$.key})),[E]),R=n.useMemo(()=>({onSwipeOutLeft:o}),[o]),k=pi(B,D,T,R),_=n.useRef(null);n.useEffect(()=>{const $=_.current;if(!$)return;$.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[D]);const pe=n.useCallback(()=>{M.agents.get(i).then(A).catch(()=>{})},[i]);if(n.useEffect(()=>(T(r??"overview"),S(null),pe(),M.externalAgents.list().then(Ce=>{const de=Ce.agents.find(I=>I.markusAgentId===i);S(de??null)}).catch(()=>{}),We.on("agent:update",Ce=>{Ce.payload.agentId===i&&pe()})),[i,pe]),!j)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:y("agent:profilePage.loadingAgent")});const $e=Ci[j.state.status]??"bg-gray-500",ne=u?.role==="owner"||u?.role==="admin";return m?e.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:e.jsxs("div",{className:"p-5",children:[(C==="overview"||C==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(Ya,{agent:j,onUpdate:pe,externalInfo:p,t:y,canManageAgents:ne}),e.jsx("div",{className:"mt-6",children:e.jsx(ci,{agentId:i,highlightId:l,agentStatus:j.state.status,canManageAgents:ne,onAgentStateChange:pe})})]}),C==="files"&&e.jsx(Za,{agentId:i}),C==="tools"&&e.jsx(Ja,{tools:j.tools??[],agent:j}),C==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(ti,{agentId:i,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(ei,{agentId:i})})]}),C==="deliverables"&&e.jsx(di,{agentId:i})]})}):e.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yt,{name:j.name,avatarUrl:j.avatarUrl,size:40,className:"rounded-xl"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:j.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${$e}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:Si(j.state.status,y)}),p&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:y("agent:profilePage.badges.external")}),j.agentRole==="manager"&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:y("agent:profilePage.badges.manager")})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[j.role,j.roleDescription?` — ${j.roleDescription}`:""]})]}),e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!s&&e.jsxs("button",{onClick:()=>xs.navigate(ut.TEAM,{agentId:i}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[e.jsx("span",{children:"◈"})," ",y("agent:profilePage.chat")]}),ne&&e.jsxs("button",{onClick:async()=>{if(j)try{const{filesMap:$}=await M.agents.getFilesMap(i),Ce={type:"agent",name:bi(j.name,j.name),displayName:j.name,version:"1.0.0",description:j.roleDescription??j.role,author:"",category:"general",tags:[],agent:{roleName:j.role,agentRole:j.agentRole},dependencies:{skills:j.skills??[]}};await yi.publishViaProxy({itemType:"agent",name:j.name,description:Ce.description,category:"general",config:Ce,files:$}),v({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishSuccess",{name:j.name}),variant:"primary"})}catch($){v({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishFailed",{error:String($)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:y("agent:profilePage.publishTitle"),children:[e.jsx("span",{children:"↑"})," ",y("agent:profilePage.hub")]}),s&&e.jsx("button",{onClick:a,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),e.jsx("div",{ref:_,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:E.filter($=>!p||["overview","mind"].includes($.key)).map($=>e.jsxs("button",{onClick:()=>T($.key),"data-active":D===$.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${D===$.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{className:"mr-1",children:$.icon}),$.label]},$.key))})]}),e.jsxs("div",{className:"p-5",onTouchStart:w?k.onTouchStart:void 0,onTouchEnd:w?k.onTouchEnd:void 0,children:[(D==="overview"||D==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(Ya,{agent:j,onUpdate:pe,externalInfo:p,t:y,canManageAgents:ne}),e.jsx("div",{className:"mt-6",children:e.jsx(ci,{agentId:i,highlightId:l,agentStatus:j.state.status,canManageAgents:ne,onAgentStateChange:pe})})]}),D==="files"&&e.jsx(Za,{agentId:i}),D==="tools"&&e.jsx(Ja,{tools:j.tools??[],agent:j}),D==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(ti,{agentId:i,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(ei,{agentId:i})})]}),D==="deliverables"&&e.jsx(di,{agentId:i})]}),b&&e.jsx(An,{alertOnly:!0,variant:b.variant??"primary",title:b.title,message:b.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Ya({agent:i,onUpdate:a,externalInfo:s,t:r,canManageAgents:o}){const[l,u]=n.useState(null),[m,f]=n.useState([]),[y,w]=n.useState(null),[j,A]=n.useState(null),[b,v]=n.useState(""),[D,T]=n.useState([]);n.useEffect(()=>{M.usage.agents().then(k=>{const _=k.agents.find(pe=>pe.agentId===i.id);_&&u(_)}).catch(()=>{}),M.agents.getRecentActivities(i.id).then(k=>f(k.activities)).catch(()=>{}),M.system.storage().then(k=>{v(k.dataDir+"/agents/"+i.id);const _=k.agents.find(pe=>pe.id===i.id);_&&A(_)}).catch(()=>{}),i.state.activeTaskIds?.length&&M.tasks.list({assignedAgentId:i.id}).then(k=>{T(k.tasks.filter(_=>i.state.activeTaskIds?.includes(_.id)))}).catch(()=>{})},[i.id,i.state.activeTaskIds]);const C=()=>{i.state.status==="offline"?M.agents.start(i.id).then(a):M.agents.stop(i.id).then(a)},p=n.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),S=n.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(s)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(at,{title:r("agent:profilePage.overview.identity"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(Mt,{label:r("agent:profilePage.overview.labels.name"),children:i.name}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:i.agentRole==="manager"?"text-amber-600":"text-blue-600",children:i.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:i.role}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:i.id}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.organization"),children:i.config?.orgId??"default"}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.created"),children:i.config?.createdAt?new Date(i.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),e.jsx(at,{title:r("agent:profilePage.overview.connectionStatus"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(dt,{label:r("agent:profilePage.overview.labels.connection"),value:s.connected?r("common:status.online"):r("common:status.offline"),color:s.connected?"green":"gray"}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(i.state.activeTaskIds?.length??0)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.lastSync"),value:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),e.jsx(at,{title:r("agent:profilePage.overview.externalAgentDetails"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(Mt,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:s.externalAgentId}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(s.registeredAt).toLocaleString()}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.capabilities"),children:s.capabilities.length>0?s.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),e.jsx(at,{title:r("agent:profilePage.overview.syncContextTitle"),children:e.jsx("div",{className:"space-y-1.5",children:S.map(k=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:k.field}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:k.desc})]},k.field))})}),e.jsx(at,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:e.jsx("div",{className:"space-y-1.5",children:p.map(k=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${k.method==="POST"?"text-amber-600":"text-green-600"}`,children:k.method}),e.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:k.path}),e.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:k.desc})]},k.path))})})]});const E=m.filter(k=>k.type==="heartbeat").length,B=m.filter(k=>k.type==="chat").length,R=i.state.activeTaskIds?.length??0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(Mt,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:i.role}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:i.agentRole==="manager"?"text-amber-600":"text-blue-600",children:i.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:i.id}),e.jsx(Mt,{label:r("agent:profilePage.overview.labels.created"),children:i.config?.createdAt?new Date(i.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Ci[i.state.status]||"bg-gray-500"}`}),e.jsx("span",{className:`text-sm font-semibold ${i.state.status==="idle"?"text-green-500":i.state.status==="working"?"text-blue-400":i.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:Si(i.state.status,r)})]}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.tokensToday"),value:tn(i.state.tokensUsedToday)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(R),color:R>0?"blue":void 0}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:i.state.lastHeartbeat?new Date(i.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),o&&e.jsx("button",{onClick:C,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:i.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),i.state.status==="error"&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),i.state.lastErrorAt&&e.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(i.state.lastErrorAt).toLocaleString()})]}),e.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:ir(i.state.lastError,r)||i.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),i.state.status==="working"&&R>0&&e.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:e.jsx("div",{className:"space-y-1",children:D.map(k=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsx("span",{className:"text-fg-secondary truncate flex-1",children:k.title}),e.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Ur(k.status,r)})]},k.id))})}),l&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(dt,{label:r("agent:profilePage.overview.labels.totalTokens"),value:tn(l.totalTokens)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.requests"),value:String(l.requestCount)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(l.toolCalls)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.promptTokens"),value:tn(l.promptTokens)}),e.jsx(dt,{label:r("agent:profilePage.overview.labels.completionTokens"),value:tn(l.completionTokens)}),e.jsx(dt,{label:"CU Used",value:tn(l.cuUsed??0)})]})]}),j&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(dt,{label:r("agent:profilePage.overview.storage"),value:ai(j.size)}),j.subItems.filter(k=>k.size>0).map(k=>e.jsx(dt,{label:k.name,value:ai(k.size)},k.name)),e.jsxs("button",{onClick:()=>{M.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),E>0&&e.jsx(at,{title:r("agent:profilePage.overview.recentHeartbeats"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:E})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(k=>k.type==="heartbeat").map(k=>{const _=y===k.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>w(_?null:k.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:k.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(k.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:_?"▲":"▼"})]}),_&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(En,{agentId:i.id,activityId:k.id})})]},k.id)})})}),B>0&&e.jsx(at,{title:r("agent:profilePage.overview.recentA2A"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:B})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(k=>k.type==="chat").map(k=>{const _=y===k.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>w(_?null:k.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:k.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(k.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:_?"▲":"▼"})]}),_&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(En,{agentId:i.id,activityId:k.id})})]},k.id)})})})]})}function Cl(i,a){const s=i.split(`
|
|
16
|
-
`),r=a.split(`
|
|
17
|
-
`),o=s.length,l=r.length,u=Array.from({length:o+1},()=>new Array(l+1).fill(0));for(let A=o-1;A>=0;A--)for(let b=l-1;b>=0;b--)u[A][b]=s[A]===r[b]?u[A+1][b+1]+1:Math.max(u[A+1][b],u[A][b+1]);const m=[];let f=0,y=0,w=1,j=1;for(;f<o||y<l;)f<o&&y<l&&s[f]===r[y]?(m.push({type:"equal",content:s[f],oldLineNum:w++,lineNum:j++}),f++,y++):y<l&&(f>=o||u[f][y+1]>=u[f+1][y])?(m.push({type:"add",content:r[y],lineNum:j++}),y++):(m.push({type:"remove",content:s[f],oldLineNum:w++}),f++);return m}function Xa(i){return i.match(/\S+|\s+/g)??[""]}function Qa({oldText:i,newText:a,mode:s}){const r=Xa(i),o=Xa(a),l=r.length,u=o.length,m=Array.from({length:l+1},()=>new Array(u+1).fill(0));for(let j=l-1;j>=0;j--)for(let A=u-1;A>=0;A--)m[j][A]=r[j]===o[A]?m[j+1][A+1]+1:Math.max(m[j+1][A],m[j][A+1]);const f=[];let y=0,w=0;for(;y<l||w<u;)y<l&&w<u&&r[y]===o[w]?(f.push({text:s==="remove"?r[y]:o[w],changed:!1}),y++,w++):w<u&&(y>=l||m[y][w+1]>=m[y+1][w])?(s==="add"&&f.push({text:o[w],changed:!0}),w++):(s==="remove"&&f.push({text:r[y],changed:!0}),y++);return e.jsx("span",{children:f.map((j,A)=>j.changed?e.jsx("span",{className:s==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:j.text},A):e.jsx("span",{children:j.text},A))})}function Tl({agent:i,template:a,templateId:s}){const{t:r}=Ue(["agent","common"]),o=n.useMemo(()=>Cl(i,a),[i,a]),[l,u]=n.useState(!0),m=3,f=n.useMemo(()=>{const b=o.map((C,p)=>C.type!=="equal"?p:-1).filter(C=>C>=0);if(b.length===0)return[];const v=[];let D=Math.max(0,b[0]-m),T=Math.min(o.length-1,b[0]+m);for(let C=1;C<b.length;C++){const p=Math.max(0,b[C]-m),S=Math.min(o.length-1,b[C]+m);p<=T+1||(v.push({start:D,end:T}),D=p),T=S}return v.push({start:D,end:T}),v},[o]),y=(b,v,D)=>{const T=b.type==="add"?"+":b.type==="remove"?"-":" ",C=b.type==="add"?"bg-green-500/8":b.type==="remove"?"bg-red-500/8":"",p=b.type==="add"?"text-green-600/90":b.type==="remove"?"text-red-500/80":"text-fg-tertiary",S=b.type==="add"?"text-green-500":b.type==="remove"?"text-red-500":"text-fg-muted",E=b.type==="remove"?b.oldLineNum:b.lineNum;let B=null;return b.type==="remove"&&v+1<D.length&&D[v+1].type==="add"?B=e.jsx(Qa,{oldText:b.content,newText:D[v+1].content,mode:"remove"}):b.type==="add"&&v>0&&D[v-1].type==="remove"&&(B=e.jsx(Qa,{oldText:D[v-1].content,newText:b.content,mode:"add"})),e.jsxs("div",{className:`flex ${C} hover:brightness-95 transition-colors`,children:[e.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:E??""}),e.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${S} select-none leading-[20px]`,children:T}),e.jsxs("span",{className:`flex-1 text-[11px] font-mono ${p} whitespace-pre-wrap break-words leading-[20px]`,children:[B??b.content,b.content===""&&" "]})]},v)},w=o.filter(b=>b.type==="add").length,j=o.filter(b=>b.type==="remove").length,A=l?f.flatMap(b=>{const v=[];for(let D=b.start;D<=b.end;D++)v.push({...o[D],_idx:D});return v}):o.map((b,v)=>({...b,_idx:v}));return e.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:s})}),e.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",w]}),e.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",j]})]}),e.jsx("button",{onClick:()=>u(b=>!b),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(l?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),e.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[l&&f.length>0&&f[0].start>0&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:f[0].start})}),A.map((b,v)=>{const D=v>0?A[v-1]:null,T=l&&D&&b._idx-D._idx>1;return e.jsxs("div",{children:[T&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),y(b,b._idx,o)]},v)}),l&&f.length>0&&f[f.length-1].end<o.length-1&&e.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:o.length-1-f[f.length-1].end})}),f.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function Ml(i,a){const s=i.split(`
|
|
18
|
-
`),r=a.split(`
|
|
19
|
-
`),o=[],l=Math.max(s.length,r.length);for(let u=0;u<l;u++){const m=s[u],f=r[u];if(m===f){o.push(` ${m??""}`);continue}m!==void 0&&(f===void 0||m!==f)&&o.push(`- ${m}`),f!==void 0&&(m===void 0||m!==f)&&o.push(`+ ${f}`)}if(o.length>80){const u=o.filter(m=>m.startsWith("+ ")||m.startsWith("- "));if(u.length>0)return u.join(`
|
|
20
|
-
`)}return o.join(`
|
|
21
|
-
`)}function Za({agentId:i}){const{t:a}=Ue(["agent","common"]),[s,r]=n.useState([]),[o,l]=n.useState(!0),[u,m]=n.useState(null),[f,y]=n.useState(""),[w,j]=n.useState(""),[A,b]=n.useState(!1);n.useEffect(()=>{M.system.storage().then(Q=>{j(Q.dataDir+"/agents/"+i+"/role")}).catch(()=>{})},[i]);const[v,D]=n.useState(!1),[T,C]=n.useState(!1),[p,S]=n.useState(null),[E,B]=n.useState(null),R=n.useCallback(()=>{l(!0),Promise.all([M.agents.getFiles(i),M.agents.roleStatus(i).catch(()=>null)]).then(([Q,H])=>{r(Q.files),S(H),Q.files.length>0&&!u&&(m(Q.files[0].name),y(Q.files[0].content))}).catch(()=>{}).finally(()=>l(!1))},[i]);n.useEffect(()=>{R()},[R]);const k=Q=>{const H=s.find(ee=>ee.name===Q);H&&(m(Q),y(H.content),C(!1),B(null))},_=async()=>{if(u){D(!0);try{await M.agents.updateFile(i,u,f),r(Q=>Q.map(H=>H.name===u?{...H,content:f}:H)),C(!1),u==="ROLE.md"&&await M.agents.updateSystemPrompt(i,f)}catch{}D(!1)}},pe=p?.files.filter(Q=>Q.status==="modified"||Q.status==="added_in_template")??[],$e=async Q=>{const H=Q?pe.filter(V=>V.file===Q):pe;if(H.length===0)return;const ee=[];for(const V of H)try{const oe=await M.agents.roleDiff(i,V.file);oe.agentContent!=null&&oe.templateContent!=null&&ee.push(`## ${V.file}
|
|
22
|
-
|
|
23
|
-
**Template file path:** built-in template \`${p?.templateId??"unknown"}\`
|
|
24
|
-
|
|
25
|
-
**Key changes in the new template version:**
|
|
26
|
-
\`\`\`diff
|
|
27
|
-
`+Ml(oe.agentContent,oe.templateContent)+"\n```\n")}catch{}if(ee.length===0)return;const g=`Your role configuration files have been updated in the latest template (\`${p?.templateId??""}\`). Please review the following changes and decide whether to update your files accordingly.
|
|
28
|
-
|
|
29
|
-
`+ee.join(`
|
|
30
|
-
---
|
|
31
|
-
|
|
32
|
-
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";xs.navigate(ut.TEAM,{agentId:i,prefillMessage:g})},ne=async Q=>{if(E?.file===Q){B(null);return}try{const H=await M.agents.roleDiff(i,Q);H.agentContent!=null&&H.templateContent!=null&&B({file:Q,agent:H.agentContent,template:H.templateContent})}catch{}};if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.filesTab.loading")});const $={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},Ce=Q=>{const H=$[Q];return H?a(`agent:profilePage.filesTab.fileLabels.${H}`):Q},de=p?.hasTemplate&&!p.isUpToDate,I=u?pe.some(Q=>Q.file===u):!1;return e.jsxs("div",{className:"space-y-4",children:[de&&e.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[e.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-amber-600 font-medium",children:a("agent:profilePage.filesTab.templateUpdateAvailable")}),e.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[a("agent:profilePage.filesTab.filesDiffer",{count:pe.length,templateId:p.templateId})," ",pe.map(Q=>Q.file).join(", ")]})]}),e.jsx("button",{onClick:()=>$e(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:a("agent:profilePage.filesTab.sendToAgent")})]}),e.jsxs(at,{title:a("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[a("agent:profilePage.filesTab.templateLabel")," ",e.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?a("agent:profilePage.filesTab.upToDate"):a("agent:profilePage.filesTab.updatesAvailable")]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:a("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[e.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:s.map(Q=>{const H=pe.some(ee=>ee.file===Q.name);return e.jsxs("button",{onClick:()=>k(Q.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${u===Q.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[Q.name,H&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},Q.name)})}),u&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:Ce(u)}),e.jsxs("div",{className:"flex gap-2 items-center",children:[I&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>ne(u),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:E?.file===u?a("agent:profilePage.filesTab.hideDiff"):a("agent:profilePage.filesTab.viewDiff")}),e.jsx("button",{onClick:()=>$e(u),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:a("agent:profilePage.filesTab.sendToAgentTitle"),children:a("agent:profilePage.filesTab.sendToAgent")})]}),v&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("common:saving")})]})]}),w&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[e.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${w}/${u}`,children:[w,"/",u]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${w}/${u}`),b(!0),setTimeout(()=>b(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:a("agent:profilePage.filesTab.copyPath"),children:a(A?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),e.jsx("button",{onClick:()=>{M.system.openPath(w)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:a("agent:profilePage.filesTab.openInFinder"),children:a("agent:profilePage.filesTab.openInFinder")})]}),E?.file===u&&e.jsx(Tl,{agent:E.agent,template:E.template,templateId:p?.templateId??""}),e.jsx(Pl,{content:s.find(Q=>Q.name===u)?.content??"",editContent:f,setEditContent:Q=>{y(Q),C(!0)},dirty:T,onSave:_}),u==="ROLE.md"&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:a("agent:profilePage.filesTab.roleMdHint")})]}),s.length===0&&e.jsx(lr,{text:a("agent:profilePage.filesTab.noConfigFiles")})]})]})}function Pl({content:i,editContent:a,setEditContent:s,dirty:r,onSave:o}){const[l,u]=n.useState(!1),m=n.useRef(null);return n.useEffect(()=>{l&&m.current?.focus()},[l]),n.useEffect(()=>{u(!1)},[i]),l||r?e.jsx("textarea",{ref:m,value:a,onChange:f=>s(f.target.value),onBlur:()=>{a!==i&&o(),u(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),s(i),u(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):e.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>u(!0),role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&u(!0)},children:[e.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),a.trim()?e.jsx(n.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(Sl,{content:a,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const El=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_"]}];function Al(i,a){const s=new Map,r=new Set;for(const{id:u,prefixes:m}of El){const f=a(`agent:toolCategories.${u}`),y=i.filter(w=>!r.has(w.name)&&m.some(j=>w.name.startsWith(j)));y.length>0&&(s.set(f,y),y.forEach(w=>r.add(w.name)))}const o=i.filter(u=>!r.has(u.name));for(const u of o){const m=u.name.indexOf("__");if(m>0){const f=u.name.slice(0,m),y=a("agent:toolCategories.mcp",{server:f});s.has(y)||s.set(y,[]),s.get(y).push(u),r.add(u.name)}}const l=i.filter(u=>!r.has(u.name));return l.length>0&&s.set(a("agent:toolCategories.other"),l),[...s.entries()].map(([u,m])=>({category:u,tools:m}))}function _l(i){return i.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function Il({tools:i}){const{t:a}=Ue(["agent","common"]),s=Al(i,a);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:a("agent:profilePage.toolsTab.registeredCount",{count:i.length})}),s.map(r=>e.jsx(at,{title:`${r.category} (${r.tools.length})`,children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(o=>{const l=Io(o.name),u=a(`common:execution.tools.${l.key}`,{defaultValue:l.label}),m=o.name.includes("__"),f=m?o.name.split("__").pop():o.name,y=_l(o.description||"");return e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[e.jsx(Lo,{name:l.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:u}),m&&e.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),f!==u&&e.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:f}),y&&e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:y,children:y})]})]},o.name)})})},r.category)),i.length===0&&e.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:a("agent:profilePage.toolsTab.noToolsRegistered")})]})}function Ll({agent:i}){const{t:a}=Ue(["agent","common"]),s=i.proficiency??{},[r,o]=n.useState(null),[l,u]=n.useState(null),[m,f]=n.useState(!1),y=i.availableSkills??[],w=new Map;for(const T of y){const C=T.category||"custom";w.has(C)||w.set(C,[]),w.get(C).push(T)}const j=async T=>{if(r===T){o(null),u(null);return}o(T),f(!0);try{const C=await fetch(`/api/skills/${encodeURIComponent(T)}`);if(C.ok){const p=await C.json();u(p.skill)}else u(null)}catch{u(null)}f(!1)},A={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},b=T=>{const C=s[T.name],p=C&&C.uses>0?Math.round(C.successes/C.uses*100):null,S=C&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[a("agent:profilePage.skillsTab.usesStats",{uses:C.uses,successes:C.successes}),C.lastUsed&&a("agent:profilePage.skillsTab.lastUsed",{date:new Date(C.lastUsed).toLocaleDateString()})]}),E=r===T.name;return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${E?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>j(T.name),children:[e.jsx("span",{className:`text-sm transition-transform ${E?"rotate-90":""}`,children:"▶"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:T.name}),T.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:a("agent:profilePage.skillsTab.alwaysOn")}),T.builtIn&&!T.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:a("agent:profilePage.skillsTab.builtIn")}),!T.builtIn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:a("agent:profilePage.skillsTab.installed")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:T.description}),S]}),p!==null&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),E&&e.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:m?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.skillsTab.loadingDetails")}):l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${A[l.category]??A.custom}`,children:l.category}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",l.version]}),l.author&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("agent:profilePage.skillsTab.byAuthor",{author:l.author})}),l.requiredPermissions?.map(B=>e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:B},B))]}),l.description&&e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:l.description}),l.tags&&l.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap",children:l.tags.map(B=>e.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",B]},B))}),(l.toolDetails??l.tools??[]).length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:a("agent:profilePage.skillsTab.toolsHeading",{count:(l.toolDetails??l.tools??[]).length})}),e.jsx("div",{className:"space-y-1.5",children:(l.toolDetails??l.tools??[]).map(B=>e.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:B.name}),B.description&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:B.description})]},B.name))})]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.skillsTab.detailsUnavailable")})})]},T.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],D=[...w.entries()].sort((T,C)=>{const p=v.indexOf(T[0]),S=v.indexOf(C[0]);return(p===-1?999:p)-(S===-1?999:S)});return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{className:"text-xs text-fg-tertiary",children:a("agent:profilePage.skillsTab.installedCount",{count:y.length})})}),D.map(([T,C])=>e.jsx(at,{title:e.jsxs("span",{className:"capitalize",children:[T," ",e.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",C.length,")"]})]}),children:e.jsx("div",{className:"space-y-2",children:C.map(p=>b(p))})},T)),y.length===0&&e.jsx(lr,{text:a("agent:profilePage.skillsTab.noSkills")})]})}function Ja({tools:i,agent:a}){const{t:s}=Ue(["agent","common"]),[r,o]=n.useState("tools");return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(l=>e.jsx("button",{onClick:()=>o(l),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===l?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:l==="tools"?`${s("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${i.length})`:`${s("agent:tabs.skills")} (${a.availableSkills?.length??0})`},l))}),r==="tools"?e.jsx(Il,{tools:i}):e.jsx(Ll,{agent:a})]})}function ei({agentId:i}){const{t:a}=Ue(["agent","common"]),[s,r]=n.useState(null),[o,l]=n.useState(!0),[u,m]=n.useState("longterm"),[f,y]=n.useState(""),[w,j]=n.useState(""),[A,b]=n.useState(!1),[v,D]=n.useState(null),[T,C]=n.useState(null),[p,S]=n.useState([]),[E,B]=n.useState(!1),R=n.useCallback(()=>{l(!0),M.agents.getMemory(i).then($=>{r($),y($.recentDailyLogs??""),j($.longTermMemory??"")}).catch(()=>{}).finally(()=>l(!1))},[i]);n.useEffect(()=>{R()},[R]);const k=async()=>{b(!0),await M.agents.updateDailyMemory(i,f).catch(()=>{}),b(!1),R()},_=async()=>{b(!0),await M.agents.updateLongTermMemory(i,a("agent:profilePage.memoryTab.userEditedSource"),w).catch(()=>{}),b(!1),R()},pe=f!==(s?.recentDailyLogs??""),$e=w!==(s?.longTermMemory??"");if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loading")});if(!s)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loadFailed")});const ne=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${s.entries.length})`},{key:"sessions",label:a("agent:profilePage.memoryTab.sessions",{count:s.sessions.length})},{key:"daily",label:a("agent:profilePage.memoryTab.dailyLogs")}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex gap-2",children:ne.map($=>e.jsx("button",{onClick:()=>m($.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${u===$.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:$.label},$.key))}),u==="entries"&&e.jsx(at,{title:a("agent:profilePage.memoryTab.recentEntries"),children:s.entries.length===0?e.jsx(lr,{text:a("agent:profilePage.memoryTab.noEntries")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.entries.map(($,Ce)=>{const de=v===Ce;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>D(de?null:Ce),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${$.type==="fact"?"bg-blue-500/15 text-blue-600":$.type==="task"?"bg-green-500/15 text-green-600":$.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:$.type}),e.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${de?"":"line-clamp-2"}`,children:$.content}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[$.importance!=null&&e.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${$.importance>=7?"bg-red-500/15 text-red-500":$.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",$.importance]}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date($.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:de?"▲":"▼"})]})]}),de&&e.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[e.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:$.content}),e.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[e.jsxs("span",{children:[a("agent:profilePage.overview.labels.type"),": ",$.type]}),$.importance!=null&&e.jsxs("span",{children:[a("agent:profilePage.overview.labels.importance"),": ",$.importance]}),e.jsx("span",{children:new Date($.timestamp).toLocaleString()})]})]})]},Ce)})})}),u==="sessions"&&e.jsx(at,{title:a("agent:profilePage.memoryTab.chatSessions"),children:s.sessions.length===0?e.jsx(lr,{text:a("agent:profilePage.memoryTab.noSessions")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.sessions.map($=>{const Ce=T===$.id,de=async()=>{if(Ce){C(null),S([]);return}C($.id),B(!0);try{const I=await M.agents.getMemorySession(i,$.id);S(I.messages)}catch{S([])}B(!1)};return e.jsxs("div",{children:[e.jsxs("button",{onClick:de,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[e.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:$.id}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[$.messageCount," ",a("agent:profilePage.memoryTab.msgs")]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date($.updatedAt).toLocaleDateString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:Ce?"▲":"▼"})]}),Ce&&e.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:E?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const I=new Map;for(const Q of p)Q.role==="tool"&&Q.toolCallId&&I.set(Q.toolCallId,Q.content);return e.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(Q=>Q.role!=="tool").map((Q,H)=>e.jsxs("div",{className:"px-3 py-2",children:[(Q.role==="user"||Q.role==="system")&&e.jsxs("div",{children:[e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${Q.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:a(`agent:profilePage.memoryTab.roles.${Q.role}`,{defaultValue:Q.role})}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx(or,{content:Q.content,className:"text-xs text-fg-secondary"})})]}),Q.role==="assistant"&&e.jsxs("div",{className:"space-y-1",children:[Q.content&&e.jsxs("div",{children:[e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:a("agent:profilePage.memoryTab.roles.assistant")}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx(or,{content:Q.content,className:"text-xs text-fg-secondary"})})]}),Q.toolCalls&&Q.toolCalls.length>0&&e.jsx("div",{className:"space-y-0.5",children:Q.toolCalls.map(ee=>{let g;try{g=JSON.parse(ee.arguments)}catch{}const V={tool:ee.name,status:"done",args:g,result:I.get(ee.id)};return e.jsx(Mo,{entry:{type:"tool",info:V}},ee.id)})})]})]},H))})})()})]},$.id)})})}),u==="daily"&&e.jsx(at,{title:a("agent:profilePage.memoryTab.dailyLogs"),action:pe?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>y(s?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:k,disabled:A,className:"text-xs text-brand-500",children:a(A?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:f,onChange:$=>y($.target.value),placeholder:a("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),u==="longterm"&&e.jsx(at,{title:a("agent:profilePage.memoryTab.longTermTitle"),action:$e?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>j(s?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:_,disabled:A,className:"text-xs text-brand-500",children:a(A?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:w,onChange:$=>j($.target.value),placeholder:a("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function ti({agentId:i,initialData:a}){const{t:s}=Ue(["agent","common"]),[r,o]=n.useState(a??null),[l,u]=n.useState(!a),[m,f]=n.useState([]),[y,w]=n.useState(null),[j,A]=n.useState(!1),[b,v]=n.useState(null),D=n.useCallback(()=>Promise.all([M.agents.getHeartbeat(i).then(o).catch(()=>{}),M.agents.getRecentActivities(i).then(E=>{f(E.activities.filter(B=>B.type==="heartbeat"))}).catch(()=>{})]),[i]);n.useEffect(()=>{u(!0),D().finally(()=>u(!1))},[D]),n.useEffect(()=>We.on("agent:update",B=>{B.payload?.agentId===i&&D()}),[i,D]);const T=async()=>{A(!0),v(null);try{const E=await M.agents.triggerHeartbeat(i);v(E.message),setTimeout(()=>v(null),4e3),setTimeout(D,2e3)}catch(E){v(String(E).replace("Error: ",""))}A(!1)},C=async E=>{try{await M.agents.cancelWakeup(i,E),D()}catch{}};if(l)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.loading")});if(!r)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.noData")});const p=E=>E?E<1e3?`${E}ms`:E<6e4?`${(E/1e3).toFixed(1)}s`:`${(E/6e4).toFixed(1)}m`:null,S=E=>{if(!E)return null;const B=Date.now()-new Date(E).getTime();if(B<0){const R=Math.abs(B);return R<6e4?s("agent:profilePage.relative.inSeconds",{count:Math.ceil(R/1e3)}):R<36e5?s("agent:profilePage.relative.inMinutes",{count:Math.ceil(R/6e4)}):s("agent:profilePage.relative.inHours",{hours:(R/36e5).toFixed(1)})}return B<6e4?s("agent:profilePage.relative.secondsAgo",{count:Math.floor(B/1e3)}):B<36e5?s("agent:profilePage.relative.minutesAgo",{count:Math.floor(B/6e4)}):s("agent:profilePage.relative.hoursAgo",{hours:(B/36e5).toFixed(1)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(at,{title:s("agent:profilePage.heartbeatTab.scheduler"),action:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:D,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:s("common:refresh")}),e.jsx("button",{onClick:T,disabled:j||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsx(dt,{label:s("agent:profilePage.overview.labels.status"),value:r.running?s("agent:profilePage.heartbeatTab.running"):s("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),e.jsx(Dl,{agentId:i,intervalMs:r.intervalMs,onChanged:D}),e.jsx(dt,{label:s("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?S(r.lastHeartbeat)??s("agent:profilePage.emDash"):s("agent:profilePage.never")}),e.jsx(dt,{label:s("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?S(r.nextWakeAt)??s("agent:profilePage.emDash"):r.running?s("agent:profilePage.heartbeatTab.pending"):s("agent:profilePage.emDash")})]}),e.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:s("agent:profilePage.heartbeatTab.rhythmHint")}),b&&e.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:b})]}),r.wakeups&&r.wakeups.length>0&&e.jsx(at,{title:s("agent:profilePage.heartbeatTab.wakeupsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(E=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate",children:E.note||s("agent:profilePage.heartbeatTab.wakeupNoNote")}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[S(E.wakeAt)??new Date(E.wakeAt).toLocaleString(),E.recurringMs?` · ${s("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${E.deliveryMode==="in_session"?s("agent:profilePage.heartbeatTab.deliveryInSession"):s("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),e.jsx("button",{onClick:()=>C(E.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:s("agent:profilePage.heartbeatTab.cancelWakeup")})]},E.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&e.jsx(at,{title:s("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(E=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:E.type==="background_exec"?"⚙":"↔"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:E.label}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[s(`agent:profilePage.heartbeatTab.callbackType.${E.type}`),` · ${s("agent:profilePage.heartbeatTab.timesOut")} ${S(E.timeoutAt)??new Date(E.timeoutAt).toLocaleString()}`]})]})]},E.id))})}),r.lastSummary&&e.jsx(at,{title:s("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:e.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:e.jsx(or,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),m.length>0?e.jsx(at,{title:s("agent:profilePage.heartbeatTab.recentRuns"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.runsThisSession",{count:m.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...m].reverse().map(E=>{const B=y===E.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>w(B?null:E.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:E.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:s("agent:profilePage.heartbeatTab.actionsCount",{count:E.logCount})}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(E.startedAt).toLocaleString()}),e.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${B?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:e.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),B&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(En,{agentId:i,activityId:E.id})})]},E.id)})})}):r.lastHeartbeat?null:e.jsx(at,{title:s("agent:profilePage.heartbeatTab.recentRuns"),children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.noRunsYet")}),e.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?s("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??s("agent:profilePage.heartbeatTab.soon")}):s("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&e.jsx("button",{onClick:T,disabled:j,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function Rl({taskId:i,isLive:a}){const{t:s}=Ue("agent"),[r,o]=n.useState([]),[l,u]=n.useState(""),[m,f]=n.useState(!0),[y,w]=n.useState("compact");if(n.useEffect(()=>{f(!0),u(""),M.tasks.getLogs(i).then(b=>{o(b.logs),f(!1)}).catch(()=>f(!1))},[i]),n.useEffect(()=>{if(!a)return;const b=We.on("task:log",D=>{const T=D.payload;if(T.taskId!==i)return;const C={id:T.id,taskId:T.taskId,agentId:T.agentId,seq:T.seq,type:T.logType,content:T.content,metadata:T.metadata,createdAt:T.createdAt};o(p=>C.id&&p.some(S=>S.id===C.id)?p:[...p,C]),C.type==="text"&&u("")}),v=We.on("task:log:delta",D=>{const T=D.payload;T.taskId===i&&u(C=>C+T.text)});return()=>{b(),v()}},[i,a]),m)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.loading")});if(r.length===0&&!l)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.noLogs")});const j=r.map(b=>_o(b)),A=new Set(j.filter(b=>b.executionRound!=null).map(b=>b.executionRound)).size>1;return e.jsx("div",{className:"px-3 py-2",children:y==="compact"?e.jsx(vi,{entries:j,streamingText:l,isActive:a,onExpand:()=>w("full"),showRounds:A}):e.jsx(ji,{entries:j,streamingText:l,isActive:a,onCollapse:()=>w("compact"),showRounds:A})})}function En({agentId:i,activityId:a,isLive:s=!1}){const{t:r}=Ue("agent"),[o,l]=n.useState([]),[u,m]=n.useState(!0),[f,y]=n.useState("compact");if(n.useEffect(()=>{m(!0),M.agents.getActivityLogs(i,a).then(j=>{l(j.logs),m(!1)}).catch(()=>m(!1))},[i,a]),n.useEffect(()=>s?We.on("agent:activity_log",A=>{const b=A.payload;if(b.agentId!==i||b.activityId!==a)return;const v={seq:b.seq,type:b.type,content:b.content,metadata:b.metadata,createdAt:b.createdAt};l(D=>D.some(T=>T.seq===v.seq)?D:[...D,v])}):void 0,[i,a,s]),u)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(o.length===0)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const w=o.map(j=>Ao(j,a,i)).filter(j=>j!==null);return e.jsx("div",{className:"px-3 py-2",children:f==="compact"?e.jsx(vi,{entries:w,isActive:s,onExpand:()=>y("full")}):e.jsx(ji,{entries:w,isActive:s,onCollapse:()=>y("compact")})})}function at({title:i,action:a,children:s}){return e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:i}),a]}),s]})}function Mt({label:i,mono:a,children:s}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i}),e.jsx("span",{className:`text-xs text-fg-secondary ${a?"font-mono text-[10px]":""}`,children:s})]})}function dt({label:i,value:a,color:s}){const r=s==="green"?"text-green-500":s==="blue"?"text-blue-400":s==="indigo"?"text-brand-500":s==="red"?"text-red-400":"text-fg-secondary";return e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`text-sm font-semibold ${r}`,children:a}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i})]})}const si=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],ni=5,ri=1440;function Dl({agentId:i,intervalMs:a,onChanged:s}){const{t:r}=Ue(["agent","common"]),[o,l]=n.useState(!1),[u,m]=n.useState(null),[f,y]=n.useState(!1),[w,j]=n.useState(String(Math.round(a/6e4))),A=p=>p%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),b=async p=>{l(!0),m(null);try{await M.agents.updateConfig(i,{heartbeatIntervalMs:p}),s()}catch(S){m(String(S).replace("Error: ",""))}l(!1)},v=p=>{if(p.target.value==="custom"){y(!0);return}y(!1),b(Number(p.target.value))},D=()=>{const p=Math.round(Number(w));if(!Number.isFinite(p)||p<ni||p>ri){m(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}b(p*60*1e3)},T=si.includes(a),C=f||!T?"custom":String(a);return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),e.jsxs("select",{value:C,onChange:v,disabled:o,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!T&&e.jsx("option",{value:String(a),children:A(a)}),si.map(p=>e.jsx("option",{value:String(p),children:A(p)},p)),e.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(f||!T)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("input",{type:"number",min:ni,max:ri,value:w,onChange:p=>j(p.target.value),disabled:o,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),e.jsx("button",{onClick:D,disabled:o,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(o?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),u&&e.jsx("span",{className:"text-[10px] text-red-400",children:u})]})}function lr({text:i}){return e.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:i})}function ai(i){if(i===0)return"0 B";const a=["B","KB","MB","GB"],s=Math.min(Math.floor(Math.log(i)/Math.log(1024)),a.length-1),r=i/Math.pow(1024,s);return`${r<10?r.toFixed(1):Math.round(r)} ${a[s]}`}const ii={0:"0",1:"1",2:"2",3:"3",4:"4"},oi={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},$l={pick:"bg-brand-500/20 text-brand-500",continue:"bg-gray-500/20 text-gray-500",preempt:"bg-amber-500/20 text-amber-500",merge:"bg-blue-500/20 text-blue-500",defer:"bg-purple-500/20 text-purple-500",delegate:"bg-green-500/20 text-green-500",drop:"bg-red-500/20 text-red-500"},Ol={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},sr={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},Fl=["all","interaction","task","notification","system"],Bl={interaction:["human_chat","a2a_message","mention"],task:["task_status_update","task_comment","requirement_comment","review_request","session_reply"],notification:["requirement_update"],system:["system_event","heartbeat","daily_report","memory_consolidation"]},zl={completed:"bg-green-500",processing:"bg-blue-400 animate-pulse",deferred:"bg-purple-400",merged:"bg-brand-400",queued:"bg-amber-400",dropped:"bg-red-500"},Wl={pending:"text-gray-400",assigned:"text-blue-400",in_progress:"text-brand-400",completed:"text-green-400",failed:"text-red-400",cancelled:"text-gray-500",review:"text-amber-400",approved:"text-green-500",rejected:"text-red-500",draft:"text-gray-400"};function Vr(i){const a=i.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(a?.[1]){const s=a[1].trim().replace(/\n/g," ");return s.length>80?s.slice(0,80)+"…":s}}function li(i,a){const s=i.payload,r=s?.summary??"",o=s?.content??"",l=i.metadata?.senderName;switch(i.sourceType){case"task_status_update":{const u=r.match(/^Task "(.+?)" status:/),m=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),f=u?.[1]??r;if(m){const w=m[1],j=m[2],A=Ur(w,a),b=Ur(j,a),v=Wl[j]??"text-fg-secondary";return{title:f,subtitle:a("agent:profilePage.mind.mailbox.statusArrow",{from:A,to:b}),badge:{label:b,color:v}}}const y=r.match(/^Task:\s*(.+)/);return y?{title:y[1]}:{title:f}}case"task_comment":{const u=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=Vr(o);if(u){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:r}}case"requirement_update":{const u=r.match(/^Requirement "(.+?)"\s+(.*)/);return u?{title:u[1],subtitle:u[2]}:{title:r}}case"requirement_comment":{const u=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=Vr(o);if(u){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:r}}case"human_chat":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?a("agent:profilePage.mind.mailbox.chatFrom",{sender:l}):a("agent:profilePage.mind.mailbox.humanChat"),subtitle:u+(o.length>120?"…":"")}}case"a2a_message":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?a("agent:profilePage.mind.mailbox.messageFrom",{sender:l}):a("agent:profilePage.mind.mailbox.agentMessage"),subtitle:u+(o.length>120?"…":"")}}case"mention":{const u=r.match(/from (.+)$/),m=Vr(o);return{title:u?a("agent:profilePage.mind.mailbox.mentionedBy",{name:u[1]}):a("agent:profilePage.mind.mailbox.mention"),subtitle:m||void 0}}case"review_request":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?a("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:l}):a("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:u+(o.length>120?"…":"")}}case"session_reply":{const u=o.slice(0,120).replace(/\n/g," ");return{title:l?a("agent:profilePage.mind.mailbox.replyInSession",{sender:l}):a("agent:profilePage.mind.mailbox.sessionReply"),subtitle:u+(o.length>120?"…":"")}}case"heartbeat":return{title:a("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:a("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:a("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const u=r.match(/^\[Announcement]\s*(.+)/);return u?{title:u[1],subtitle:a("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||a("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||i.sourceType}}}function ci({agentId:i,highlightId:a,agentStatus:s,canManageAgents:r,onAgentStateChange:o}){const{t:l}=Ue(["agent","common","team"]),[u,m]=n.useState(null),[f,y]=n.useState(null),[w,j]=n.useState(!0),[A,b]=n.useState("all"),[v,D]=n.useState("all"),[T,C]=n.useState(a??null),[p,S]=n.useState(a??null),[E,B]=n.useState(!1),[R,k]=n.useState(!0),[_,pe]=n.useState(null),$e=50,ne=3,$=n.useCallback(async(g=!0)=>{g&&j(!0);try{const V=A==="all"?void 0:A,oe=v==="all"?void 0:v,[be,ge]=await Promise.all([M.agents.getMindState(i),M.agents.getMailbox(i,{limit:$e,category:V,status:oe})]);m(be),y(ge),k((ge.history?.length??0)>=$e)}catch{}j(!1)},[i,A,v]),Ce=n.useCallback(async()=>{if(!f)return;const g=A==="all"?void 0:A,V=v==="all"?void 0:v;try{const oe=await M.agents.getMailbox(i,{limit:$e,offset:f.history.length,category:g,status:V});y(be=>be?{...be,history:[...be.history,...oe.history]}:oe),k((oe.history?.length??0)>=$e)}catch{}},[i,f,A,v]);n.useEffect(()=>{C(a??null),S(a??null),$()},[$,a]);const de=n.useRef(!1);if(n.useEffect(()=>{if(!p||w)return;if(f?.history?.some(V=>V.id===p)){de.current=!1;const V=document.getElementById(`mbx-${p}`);if(V){setTimeout(()=>V.scrollIntoView({behavior:"smooth",block:"center"}),100);const oe=setTimeout(()=>S(null),3e3);return()=>clearTimeout(oe)}}else R&&!de.current&&(de.current=!0,(async()=>{let V=f?.history??[],oe=R;for(;oe;)try{const be=await M.agents.getMailbox(i,{limit:$e,offset:V.length}),ge=[...V,...be.history];V=ge,oe=(be.history?.length??0)>=$e;const ye=be.history.some(Ye=>Ye.id===p);if(y(Ye=>Ye?{...Ye,history:ge}:be),k(oe),ye||!oe)break}catch{break}de.current=!1})())},[p,w,f,R,i]),n.useEffect(()=>{let g=null;const V=be=>{be.payload?.agentId===i&&(g&&clearTimeout(g),g=setTimeout(()=>{g=null,$(!1)},500))},oe=[We.on("agent:mailbox",V),We.on("agent:decision",V),We.on("agent:attention",V),We.on("agent:focus",V),We.on("agent:update",V),We.on("agent:triage",V)];return()=>{g&&clearTimeout(g),oe.forEach(be=>be())}},[i,$]),w&&!u)return e.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:l("agent:profilePage.mind.loading")});const I=u?.mailboxDepth??u?.queuedItems?.length??0,Q=(()=>{const g=u?.attentionState??"idle";return g==="deciding"||g==="idle"&&I>0?"deciding":g!=="idle"&&!u?.currentFocus?"idle":g})(),H=Q==="idle"&&f?.history?.some(g=>g.status==="processing"),ee=(u?.attentionState??"idle")==="idle"&&I>0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${Ol[Q]??"bg-gray-500/20 text-gray-500"}`,children:l(`agent:profilePage.mind.attention.${Q}`)}),u?.currentFocus?(()=>{const g=li({id:u.currentFocus.mailboxItemId,sourceType:u.currentFocus.type,payload:{summary:u.currentFocus.label,taskId:u.currentFocus.taskId},metadata:{},queuedAt:u.currentFocus.startedAt},l);return e.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[e.jsxs("span",{children:[sr[u.currentFocus.type]??"●"," ",e.jsx("span",{className:"text-fg-primary font-medium",children:g.title}),g.subtitle&&e.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:g.subtitle}),e.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:l("agent:profilePage.mind.since",{time:new Date(u.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&e.jsxs("button",{onClick:()=>pe(u.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",l("agent:profilePage.mind.cancelCurrentBtn")]})]})})():ee?e.jsx("span",{className:"text-sm text-amber-500",children:l("agent:profilePage.mind.queuedButIdle",{count:I,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):Q==="deciding"?e.jsx("span",{className:"text-sm text-amber-500",children:l("agent:profilePage.mind.decidingWaiting",{count:I})}):e.jsx("span",{className:"text-sm text-fg-tertiary",children:l("agent:profilePage.mind.idleWaiting")}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&s==="offline"&&e.jsxs("button",{onClick:()=>{M.agents.start(i).then(()=>{o?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-green-500/15 text-green-500 hover:bg-green-500/25 transition-colors",children:["▶ ",l("agent:profilePage.mind.continueBtn")]}),r&&(s==="working"||s==="idle")&&e.jsxs("button",{onClick:()=>{M.agents.stop(i).then(()=>{o?.(),$()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors",children:["■ ",l("team:contextMenu.stop")]}),e.jsx("button",{onClick:()=>{$()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:l("agent:profilePage.mind.refresh")})]})]}),H&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[e.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),e.jsx("span",{className:"text-[11px] text-amber-600",children:l("agent:profilePage.mind.staleProcessingWarning")})]}),(u?.queuedItems?.length??0)>0&&(()=>{const g=u.queuedItems,V=g.length>ne,oe=V&&!E?g.slice(0,ne):g,be=g.reduce((ge,ye)=>(ge[ye.sourceType]=(ge[ye.sourceType]??0)+1,ge),{});return e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:l("agent:profilePage.mind.queue",{count:g.length})}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(be).map(([ge,ye])=>e.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[sr[ge]??"●"," ",ye]},ge))})]}),e.jsxs("div",{className:"space-y-1",children:[oe.map((ge,ye)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[e.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:ye+1}),e.jsx("span",{className:"text-sm",children:sr[ge.sourceType]??"●"}),e.jsx("span",{className:`text-[10px] ${oi[ge.priority]??"text-fg-tertiary"}`,children:l(`agent:profilePage.mind.priority.${ii[ge.priority]??ge.priority}`,{defaultValue:`P${ge.priority}`})}),e.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:ge.summary}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(ge.queuedAt).toLocaleTimeString()})]},ge.id)),V&&e.jsx("button",{onClick:()=>B(!E),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:E?l("agent:profilePage.mind.collapseQueue"):l("agent:profilePage.mind.expandQueue",{count:g.length-ne})})]})]})})()]}),(u?.notebook?.length??0)>0&&e.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:e.jsxs("details",{open:!0,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"📓"}),e.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),e.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[u.notebook.length," ",u.notebook.length===1?"entry":"entries"]})]}),e.jsx("div",{className:"mt-2 space-y-2",children:u.notebook.map(g=>{const V=Date.now()-g.updatedAt,oe=V<6e4?`${Math.round(V/1e3)}s ago`:V<36e5?`${Math.round(V/6e4)}min ago`:`${(V/36e5).toFixed(1)}h ago`,be=g.managed==="system"?"text-blue-400":g.managed==="cpp"?"text-purple-400":"text-emerald-400";return e.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary",children:g.key}),e.jsxs("span",{className:`text-[10px] ${be}`,children:["[",g.managed,"]"]}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:oe})]}),e.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:g.text.length>500?g.text.slice(0,500)+"…":g.text})]},g.key)})})]})}),u?.deliberationActivity&&e.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:l("agent:profilePage.mind.deliberationInProgress")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:l("agent:profilePage.mind.since",{time:new Date(u.deliberationActivity.startedAt).toLocaleTimeString()})})]}),e.jsx(En,{agentId:i,activityId:u.deliberationActivity.activityId,isLive:!0})]}),u?.lastTriage&&(()=>{const V=Date.now()-new Date(u.lastTriage.timestamp).getTime()>6e4;return e.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${V?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:e.jsxs("details",{open:!V,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:l("agent:profilePage.mind.triageDecision")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(u.lastTriage.timestamp).toLocaleTimeString()})]}),e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:u.lastTriage.reasoning}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:l("agent:profilePage.mind.processingItem",{id:u.lastTriage.processedItemId.slice(0,12)})}),u.lastTriage.deferredItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:l("agent:profilePage.mind.deferred",{count:u.lastTriage.deferredItemIds.length})}),u.lastTriage.droppedItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:l("agent:profilePage.mind.dropped",{count:u.lastTriage.droppedItemIds.length})}),(u.lastTriage.inlineCompletedIds?.length??0)>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:l("agent:profilePage.mind.inlineCompleted",{count:u.lastTriage.inlineCompletedIds.length})})]})]})})})(),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:l("agent:profilePage.mind.mailboxHistory")}),e.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:Fl.map(g=>{const V=f?.sourceTypeCounts,oe=g==="all"?V?Object.values(V).reduce((be,ge)=>be+ge,0):void 0:V?(Bl[g]??[]).reduce((be,ge)=>be+(V[ge]??0),0):void 0;return e.jsxs("button",{onClick:()=>b(g),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${A===g?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[l(`agent:profilePage.mind.categoryFilters.${g}`),oe!=null&&oe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:oe})]},g)})})]}),e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(g=>{const V=f?.statusCounts,oe=g.key==="all"?V?Object.values(V).reduce((be,ge)=>be+ge,0):void 0:V?.[g.key];return e.jsxs("button",{onClick:()=>D(g.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===g.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[g.dot&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.dot}`}),l(`agent:profilePage.mind.statusFilters.${g.key}`),oe!=null&&oe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:oe})]},g.key)})}),(!f?.history||f.history.length===0)&&!w&&e.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:l("agent:profilePage.mind.noHistory")}),e.jsx("div",{className:"space-y-1",children:f?.history?.map(g=>{const V=T===g.id,oe=sr[g.sourceType]??"●",be=li(g,l),ge=g.metadata?.senderName,ye=g.metadata?.senderRole,Ye=p===g.id;return e.jsxs("div",{id:`mbx-${g.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${Ye?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[e.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>C(V?null:g.id),children:[e.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:V?"▾":"▸"}),e.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${zl[g.status]??"bg-gray-400"}`}),e.jsx("span",{className:"text-sm",children:oe}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-medium text-fg-primary ${V?"":"truncate"}`,children:be.title}),be.badge&&e.jsx("span",{className:`text-[10px] font-medium shrink-0 ${be.badge.color}`,children:be.badge.label}),e.jsx("span",{className:`text-[10px] shrink-0 ${oi[g.priority]??"text-fg-tertiary"}`,children:l(`agent:profilePage.mind.priority.${ii[g.priority]??g.priority}`,{defaultValue:""})})]}),be.subtitle&&e.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${V?"":"truncate"}`,children:be.subtitle}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[e.jsx("span",{children:new Date(g.queuedAt).toLocaleString()}),g.completedAt&&e.jsxs("span",{children:["→ ",new Date(g.completedAt).toLocaleTimeString()]}),g.activity&&e.jsxs(e.Fragment,{children:[g.activity.totalTokens>0&&e.jsx("span",{children:l("agent:profilePage.mind.tokensCount",{count:tn(g.activity.totalTokens)})}),g.activity.totalTools>0&&e.jsx("span",{children:l("agent:profilePage.mind.toolsCount",{count:g.activity.totalTools})})]})]})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:g.sourceType}),r&&g.status==="processing"&&e.jsxs("button",{onClick:Je=>{Je.stopPropagation(),pe(g.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",l("agent:profilePage.mind.cancelCurrentBtn")]})]}),V&&e.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[ge&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[l("agent:profilePage.mind.from")," ",e.jsx("span",{className:"text-fg-secondary",children:ge}),ye&&e.jsxs("span",{className:"text-fg-tertiary",children:[" (",ye,")"]})]}),g.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(g.sourceType)&&e.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:g.payload.content}),g.decisions&&g.decisions.length>0&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:l("agent:profilePage.mind.decisions")}),e.jsx("div",{className:"space-y-1",children:g.decisions.map(Je=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${$l[Je.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:Je.decisionType}),e.jsx("span",{className:"text-fg-secondary flex-1",children:Je.reasoning}),e.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(Je.createdAt).toLocaleTimeString()})]},Je.id))})]}),g.activity?e.jsxs("div",{children:[e.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[l("agent:profilePage.mind.activityHeading",{label:g.activity.label}),e.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${g.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:g.activity.success?l("agent:profilePage.mind.success"):l("agent:profilePage.mind.failed")})]}),g.activity.type==="task"&&g.payload?.taskId?e.jsx(Rl,{taskId:g.payload.taskId,isLive:!g.activity.endedAt}):e.jsx(En,{agentId:i,activityId:g.activity.id,isLive:!g.activity.endedAt})]}):g.status==="processing"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:l("agent:profilePage.mind.processing")}):g.status==="completed"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:l("agent:profilePage.mind.noActivityLog")}):null]})]},g.id)})}),R&&(f?.history?.length??0)>0&&e.jsx("div",{className:"text-center mt-3",children:e.jsx("button",{onClick:Ce,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:l("agent:profilePage.mind.loadEarlier")})})]}),_&&e.jsx(An,{title:l("agent:profilePage.mind.cancelConfirmTitle"),message:l("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:l("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{M.agents.cancelProcessing(i).then(()=>$()),pe(null)},onCancel:()=>pe(null)})]})}function di({agentId:i}){const{t:a}=Ue(["agent","common"]),[s,r]=n.useState([]),[o,l]=n.useState(!0),[u,m]=n.useState(null),f=n.useCallback(async()=>{l(!0);try{const{results:y}=await M.deliverables.search({agentId:i,limit:200});r(y)}catch{r([])}l(!1)},[i]);return n.useEffect(()=>{f()},[f]),n.useEffect(()=>{const y=We.on("deliverable:created",()=>f()),w=We.on("deliverable:updated",()=>f()),j=We.on("deliverable:removed",()=>f());return()=>{y(),w(),j()}},[f]),o?e.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(y=>e.jsxs("div",{className:"animate-pulse space-y-2",children:[e.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),e.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},y))}):s.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("span",{className:"text-3xl mb-3",children:"📦"}),e.jsx("p",{className:"text-sm text-fg-secondary",children:a("agent:deliverables.empty")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:a("agent:deliverables.emptyHint")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:a("agent:deliverables.count",{count:s.length})}),s.map(y=>{const w=Po[y.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},j=_a[y.status]??_a.active;return e.jsxs("button",{onClick:()=>m(y),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[e.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${w.color}`,children:w.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:y.title}),e.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${j.color}`,children:y.status})]}),y.summary&&e.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:y.summary}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[e.jsx("span",{children:new Date(y.createdAt).toLocaleDateString()}),y.tags.length>0&&e.jsx("span",{children:y.tags.slice(0,3).join(", ")})]})]}),e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},y.id)})]}),u&&e.jsx(Eo,{item:u,onClose:()=>m(null),onOpenInPage:y=>{m(null),xs.navigate(ut.DELIVERABLES,{openDeliverable:y})}})]})}const Hl=n.lazy(()=>wi(()=>import("./index-Dgg0L65t.js").then(i=>i.am),__vite__mapDeps([0,1])).then(i=>({default:i.MarkdownMessage}))),Xr=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],ui={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function mi({teamId:i,onBack:a,inline:s,headless:r,activeTab:o,onSelectAgent:l}){const{t:u}=Ue("team"),[m,f]=n.useState(null),[y,w]=n.useState(null),[j,A]=n.useState("overview"),b=r&&o?o:j,[v,D]=n.useState(""),[T,C]=n.useState(""),[p,S]=n.useState(!1),[E,B]=n.useState(!1),[R,k]=n.useState(""),[_,pe]=n.useState(""),$e=n.useRef(null),ne=n.useRef(null),$=n.useRef(null),Ce=n.useRef(null),[de,I]=n.useState(!1),[Q,H]=n.useState(!1),[ee,g]=n.useState(""),[V,oe]=n.useState(""),[be,ge]=n.useState(!1),[ye,Ye]=n.useState([]),Je=n.useRef(null),Gt=n.useCallback(async()=>{try{const He=(await M.teams.list()).teams.find(Be=>Be.id===i);He&&f(He);const qe=await M.teams.status(i);Ye(qe.agents)}catch{}},[i]),fs=n.useCallback(async()=>{try{const ie=await M.teams.getFile(i,"ANNOUNCEMENT.md");D(ie.content)}catch{D("")}try{const ie=await M.teams.getFile(i,"NORMS.md");C(ie.content)}catch{C("")}},[i]);n.useEffect(()=>{A("overview"),Gt(),fs()},[i,Gt,fs]),n.useEffect(()=>{p&&ne.current&&ne.current.focus()},[p]),n.useEffect(()=>{E&&Ce.current&&Ce.current.focus()},[E]);const zt=async(ie,He)=>{I(!0);try{await M.teams.updateFile(i,ie,He),ie==="ANNOUNCEMENT.md"?(D(He),S(!1)):(C(He),B(!1))}catch{}I(!1)},ss=async()=>{ee.trim()&&(await M.teams.update(i,{name:ee.trim()}),H(!1),Gt())},gs=async()=>{await M.teams.update(i,{description:V}),ge(!1),Gt()};if(!m)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const zs=m.members.find(ie=>ie.agentRole==="manager"),Kt=ye.filter(ie=>ie.status!=="offline").length,vt=b==="announcements"&&p||b==="norms"&&E;if(r)return e.jsx("div",{className:`flex-1 bg-surface-primary ${vt?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:e.jsxs("div",{className:`${vt?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:zs?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ie=>{const He=ye.find(jt=>jt.id===ie.id),qe=ui[He?.status??"offline"]??"bg-gray-500",Be=ie.type==="agent";return e.jsxs("div",{onClick:()=>Be&&l?.(ie.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Be&&l?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(yt,{name:ie.name,avatarUrl:ie.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ie.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${qe}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:He?.status??"offline"}),ie.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ie.role," · ",ie.type]})]}),Be&&l&&e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ie.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),b==="announcements"&&e.jsx(nr,{content:v,draft:R,setDraft:k,editing:p,setEditing:S,textareaRef:ne,contentRef:$e,saving:de,onSave:()=>zt("ANNOUNCEMENT.md",R),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),b==="norms"&&e.jsx(nr,{content:T,draft:_,setDraft:pe,editing:E,setEditing:B,textareaRef:Ce,contentRef:$,saving:de,onSave:()=>zt("NORMS.md",_),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),b==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Q?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:Je,value:ee,onChange:ie=>g(ie.target.value),onKeyDown:ie=>ie.key==="Enter"&&ss(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),e.jsx("button",{onClick:ss,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{g(m.name),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),be?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:V,onChange:ie=>oe(ie.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:gs,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>ge(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{oe(m.description??""),ge(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(xi,{teamId:i,teamName:m.name,onDeleted:a})]})]})});const mt=j==="announcements"&&p||j==="norms"&&E;return e.jsxs("div",{className:`flex-1 bg-surface-primary ${mt?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:m.name}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[m.members.length," members"]}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Kt," online"]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:m.description||"No description"})]}),e.jsxs("button",{onClick:async()=>{if(m)try{const{files:ie}=await M.teams.getFilesMap(m.id),He=m.members.filter(Be=>Be.type==="agent"),qe={type:"team",name:bi(m.name,m.name),displayName:m.name,version:"1.0.0",description:m.description??"",author:"",category:"general",tags:[],team:{members:He.map(Be=>({name:Be.name,roleName:Be.role,role:Be.agentRole??"worker",count:1,skills:[]}))}};await yi.publishViaProxy({itemType:"team",name:m.name,description:m.description??"",category:"general",config:qe,files:ie}),w({title:"Hub",message:`Published "${m.name}" to Markus Hub`,variant:"primary"})}catch(ie){w({title:"Hub",message:`Failed to publish: ${ie}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[e.jsx("span",{children:"↑"})," Hub"]}),s&&e.jsx("button",{onClick:a,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),e.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:Xr.map(ie=>e.jsxs("button",{onClick:()=>A(ie.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${j===ie.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[ie.icon," ",u(ie.labelKey)]},ie.key))})]}),e.jsxs("div",{className:`${mt?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[j==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:zs?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ie=>{const He=ye.find(jt=>jt.id===ie.id),qe=ui[He?.status??"offline"]??"bg-gray-500",Be=ie.type==="agent";return e.jsxs("div",{onClick:()=>Be&&l?.(ie.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Be&&l?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(yt,{name:ie.name,avatarUrl:ie.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ie.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${qe}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:He?.status??"offline"}),ie.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ie.role," · ",ie.type]})]}),Be&&l&&e.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ie.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),j==="announcements"&&e.jsx(nr,{content:v,draft:R,setDraft:k,editing:p,setEditing:S,textareaRef:ne,contentRef:$e,saving:de,onSave:()=>zt("ANNOUNCEMENT.md",R),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),j==="norms"&&e.jsx(nr,{content:T,draft:_,setDraft:pe,editing:E,setEditing:B,textareaRef:Ce,contentRef:$,saving:de,onSave:()=>zt("NORMS.md",_),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),j==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),Q?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:Je,value:ee,onChange:ie=>g(ie.target.value),onKeyDown:ie=>ie.key==="Enter"&&ss(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),e.jsx("button",{onClick:ss,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>H(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{g(m.name),H(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),be?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:V,onChange:ie=>oe(ie.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:gs,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>ge(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{oe(m.description??""),ge(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(xi,{teamId:i,teamName:m.name,onDeleted:a})]})]}),y&&e.jsx(An,{alertOnly:!0,variant:y.variant??"primary",title:y.title,message:y.message,onConfirm:()=>w(null),onCancel:()=>w(null)})]})}function nr({content:i,draft:a,setDraft:s,editing:r,setEditing:o,textareaRef:l,contentRef:u,saving:m,onSave:f,placeholder:y,emptyText:w}){return r?e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("textarea",{ref:l,value:a,onChange:j=>s(j.target.value),onBlur:()=>{a!==i?f():o(!1)},onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),s(i),o(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:y}),m&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):e.jsx("div",{ref:u,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{s(i),o(!0)},role:"button",tabIndex:0,onKeyDown:j=>{j.key==="Enter"&&(s(i),o(!0))},children:i.trim()?e.jsx(n.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(Hl,{content:i,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic",children:w})})}function xi({teamId:i,teamName:a,onDeleted:s}){const[r,o]=n.useState(!1),[l,u]=n.useState(!1),[m,f]=n.useState(!1),[y,w]=n.useState(!1);return e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',a,'"? This removes the team record from the database.']}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:j=>f(j.target.checked),className:"rounded"}),"Also delete all members in this team"]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:j=>u(j.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y,onClick:async()=>{w(!0);try{await M.teams.delete(i,m,{purgeFiles:l}),window.dispatchEvent(new CustomEvent("markus:data-changed")),s()}catch{w(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:y?"Deleting...":"Confirm Delete"}),e.jsx("button",{onClick:()=>o(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}function qr(i,a,s,r){return i==="channel"?`ch:${s}`:i==="dm"?`dm:${r??""}`:a||"_direct"}class ms{currentConvKey="";loadingSession=null;msgBuffers=new Map;sessionMsgCache=new Map;activeSession=new Map;actBuffers=new Map;sessionTabs=new Map;phase=new Map;sendCount=new Map;streamingSessions=new Map;sessionCacheOrder=[];static MAX_MESSAGES=500;static MAX_CONVERSATIONS=20;static MAX_SESSION_CACHE=30;static NEW_CHAT_ID="__new_chat__";getPhase(a){return this.phase.get(a)??"idle"}beginLoad(a){this.getPhase(a)!=="streaming"&&this.phase.set(a,"loading")}completeLoad(a){this.getPhase(a)==="loading"&&this.phase.set(a,"ready")}beginStream(a){this.phase.set(a,"streaming")}endStream(a){this.getPhase(a)==="streaming"&&this.phase.set(a,"ready")}resetConv(a){this.phase.set(a,"idle"),this.activeSession.delete(a)}updateMessages(a,s,r){const o=this.activeSession.get(a),l=!r||o===r||o===void 0,u=l?this.msgBuffers.get(a)??[]:this.sessionMsgCache.get(r)??[];let m=s(u);m.length>ms.MAX_MESSAGES&&(m=m.slice(-500));let f=!1;return l&&(this.msgBuffers.set(a,m),this.evictIfNeeded(a),f=this.currentConvKey===a),r&&r!==ms.NEW_CHAT_ID&&(this.sessionMsgCache.set(r,m),this.touchSessionCache(r)),{displayChanged:f,newMessages:f?m:void 0}}applyLoadResult(a,s,r){const o=this.isCacheFresher(s,r);o||(this.sessionMsgCache.set(s,r),this.touchSessionCache(s));const l=this.getPhase(a),u=this.activeSession.get(a);if(this.currentConvKey===a&&(this.loadingSession===s||u===s)&&l!=="streaming"){const f=o?this.sessionMsgCache.get(s):r;return this.msgBuffers.set(a,f),this.loadingSession=s,this.completeLoad(a),{displayChanged:!0,newMessages:f}}return{displayChanged:!1}}appendActivity(a,s,r){const o=r??a,l=[...this.actBuffers.get(o)??[],s];if(this.actBuffers.set(o,l),this.currentConvKey!==a)return{displayChanged:!1};const u=this.activeSession.get(a);return!r||!u||u===r?{displayChanged:!0,newActivities:l}:{displayChanged:!1}}getActiveSession(a){return this.activeSession.get(a)}setActiveSession(a,s){this.activeSession.set(a,s)}saveToCache(a,s){if(!s||s===ms.NEW_CHAT_ID)return;const r=this.msgBuffers.get(a);r&&r.length>0&&(this.sessionMsgCache.set(s,r),this.touchSessionCache(s))}restoreFromCache(a,s){const r=this.sessionMsgCache.get(s);if(r&&r.length>0)return this.msgBuffers.set(a,r),r;this.msgBuffers.delete(a)}isCacheFresher(a,s){const r=this.sessionMsgCache.get(a);if(!r||r.length===0)return!1;if(r.length>s.length)return!0;const o=r.reduce((f,y)=>f+y.text.length,0),l=s.reduce((f,y)=>f+y.text.length,0);if(o>l)return!0;const u=r.reduce((f,y)=>f+(y.segments?.length??0),0),m=s.reduce((f,y)=>f+(y.segments?.length??0),0);return u>m}incrementSend(a){this.sendCount.set(a,(this.sendCount.get(a)??0)+1)}decrementSend(a){const s=Math.max(0,(this.sendCount.get(a)??1)-1);return this.sendCount.set(a,s),s}resetSend(a){this.sendCount.set(a,0)}isSending(a){return(this.sendCount.get(a)??0)>0}addStreamSession(a,s){const r=this.streamingSessions.get(a)??new Set;r.add(s),this.streamingSessions.set(a,r)}removeStreamSession(a,s){if(s){const r=this.streamingSessions.get(a);r&&(r.delete(s),r.size===0&&this.streamingSessions.delete(a))}else this.streamingSessions.delete(a)}getStreamSessions(a){return this.streamingSessions.get(a)}getMessages(a){return this.msgBuffers.get(a)}getActivities(a){return this.actBuffers.get(a)??[]}deleteBuffer(a){this.msgBuffers.delete(a)}evictIfNeeded(a){if(this.msgBuffers.size<=ms.MAX_CONVERSATIONS)return;const s=[...this.msgBuffers.keys()],r=s.filter(o=>o!==a&&o!==this.currentConvKey).slice(0,s.length-ms.MAX_CONVERSATIONS);for(const o of r)this.msgBuffers.delete(o),this.actBuffers.delete(o),this.sessionTabs.delete(o),this.activeSession.delete(o)}touchSessionCache(a){const s=this.sessionCacheOrder.indexOf(a);for(s!==-1&&this.sessionCacheOrder.splice(s,1),this.sessionCacheOrder.push(a);this.sessionCacheOrder.length>ms.MAX_SESSION_CACHE;){const r=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(r)){this.sessionCacheOrder.push(r);break}this.sessionMsgCache.delete(r)}}}const Ve=ms.NEW_CHAT_ID;function Vl(i){const a=n.useRef(new ms),[s,r]=n.useState(i??[]),[o,l]=n.useState(!1),[u,m]=n.useState([]),f=n.useRef(null);n.useEffect(()=>()=>{f.current!==null&&cancelAnimationFrame(f.current)},[]);const y=n.useCallback((p,S,E)=>{const B=a.current.updateMessages(p,S,E);B.displayChanged&&B.newMessages&&r(B.newMessages)},[]),w=n.useCallback((p,S,E)=>{a.current.updateMessages(p,S,E).displayChanged&&f.current===null&&(f.current=requestAnimationFrame(()=>{f.current=null;const R=a.current.getMessages(p);R&&a.current.currentConvKey===p&&r([...R])}))},[]),j=n.useCallback((p,S,E)=>{const B=a.current.appendActivity(p,S,E);B.displayChanged&&B.newActivities&&m(B.newActivities)},[]),A=n.useCallback(p=>a.current.getPhase(p),[]),b=n.useCallback(p=>a.current.beginLoad(p),[]),v=n.useCallback(p=>a.current.beginStream(p),[]),D=n.useCallback(p=>a.current.endStream(p),[]),T=n.useCallback(p=>{a.current.resetConv(p),a.current.deleteBuffer(p)},[]),C=n.useCallback(async(p,S,E)=>{a.current.loadingSession=p,a.current.beginLoad(S);try{const B=await E(),R=a.current.applyLoadResult(S,p,B.messages);return R.displayChanged&&R.newMessages&&r(R.newMessages),{count:B.messages.length,hasMore:B.hasMore,oldestCursor:B.oldestCursor}}catch{return a.current.currentConvKey===S&&a.current.getPhase(S)!=="streaming"&&(r([]),a.current.completeLoad(S)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:a.current,messages:s,setMessages:r,sending:o,setSending:l,activities:u,setActivities:m,get msgBuffers(){return a.current.msgBuffers},get sessionMsgCache(){return a.current.sessionMsgCache},get activeSessionBuffer(){return a.current.activeSession},get actBuffers(){return a.current.actBuffers},get sessionTabsBuffer(){return a.current.sessionTabs},get currentConvKeyRef(){return{get current(){return a.current.currentConvKey},set current(p){a.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return a.current.loadingSession},set current(p){a.current.loadingSession=p}}},updateConvMsgs:y,updateConvMsgsRaf:w,appendConvActivity:j,getPhase:A,beginLoad:b,beginStream:v,endStream:D,resetConv:T,loadAndDisplay:C,incrementSending:p=>a.current.incrementSend(p),decrementSending:p=>a.current.decrementSend(p),resetSending:p=>a.current.resetSend(p),isSendingFor:p=>a.current.isSending(p),setStreamSession:(p,S)=>a.current.addStreamSession(p,S),clearStreamSession:(p,S)=>a.current.removeStreamSession(p,S),getStreamSession:p=>a.current.getStreamSessions(p),saveSessionToCache:(p,S)=>a.current.saveToCache(p,S),restoreSessionFromCache:(p,S)=>{const E=a.current.restoreFromCache(p,S);return r(E??[]),E},isSessionCacheFresherThanDb:(p,S)=>a.current.isCacheFresher(p,S)}}function ql({value:i,onSelect:a,disabled:s}){const{t:r}=Ue("team"),[o,l]=n.useState(!1),[u,m]=n.useState(!0),[f,y]=n.useState(""),[w,j]=n.useState(!1),[A,b]=n.useState([]),[v,D]=n.useState(null),T=n.useRef(null),C=n.useCallback(async()=>{j(!0);try{const R=await fetch("/api/settings/llm",{credentials:"include"});if(!R.ok)throw new Error(`HTTP ${R.status}`);const k=await R.json(),_=k.providers?.markus;if(_?.configured&&_.enabled!==!1&&(!_.models||_.models.length===0))try{const ne=await fetch("/api/models/live/markus",{credentials:"include"});if(ne.ok){const $=await ne.json();$.models?.length&&(_.models=$.models)}}catch{}const pe=[];for(const[ne,$]of Object.entries(k.providers??{})){if(!$.configured||$.enabled===!1)continue;const Ce=($.models??[]).map(de=>({id:de.id,name:de.name}));Ce.length!==0&&pe.push({provider:ne,displayName:$.displayName??ne,models:Ce})}pe.sort((ne,$)=>ne.displayName.localeCompare($.displayName)),b(pe);let $e=null;if(k.routingDefaultModel?.provider&&k.routingDefaultModel?.model)$e={provider:k.routingDefaultModel.provider,model:k.routingDefaultModel.model};else if(k.defaultProvider){const ne=k.providers?.[k.defaultProvider];ne?.model&&($e={provider:k.defaultProvider,model:ne.model})}D($e)}catch{b([])}finally{j(!1)}},[]);n.useEffect(()=>{C()},[C]),n.useEffect(()=>{o&&(m(!0),y(""),C())},[o,C]),n.useEffect(()=>{if(!o)return;const R=k=>{T.current?.contains(k.target)||l(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[o]);const p=n.useMemo(()=>{const R=f.trim().toLowerCase();return A.map(k=>({...k,models:R?k.models.filter(_=>_.id.toLowerCase().includes(R)||(_.name?.toLowerCase().includes(R)??!1)||k.displayName.toLowerCase().includes(R)||k.provider.toLowerCase().includes(R)):k.models})).filter(k=>k.models.length>0)},[A,f]),S=i??v,B=(S?.model?S.model.includes("/")?S.model.split("/").pop():S.model:"")||r("chatModel.title",{defaultValue:"Model"});return e.jsxs("div",{ref:T,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",disabled:s,onClick:()=>l(R=>!R),className:"max-w-[180px] px-1.5 py-1 text-[12px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-md hover:bg-surface-elevated transition-colors flex items-center gap-1",title:S?`${S.provider}: ${S.model}`:r("chatModel.title",{defaultValue:"Model"}),children:[e.jsx("span",{className:"truncate",children:B}),e.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),o&&e.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[e.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[e.jsx("input",{autoFocus:!0,value:f,onChange:R=>y(R.target.value),placeholder:r("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-base border border-border-default/50 outline-none focus:border-brand-500/50"}),e.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[e.jsx("span",{children:r("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),e.jsx("button",{type:"button",role:"switch","aria-checked":u,onClick:()=>m(R=>!R),className:`relative w-9 h-5 rounded-full transition-colors ${u?"bg-brand-600":"bg-fg-tertiary/30"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${u?"translate-x-4":""}`})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}),!w&&p.length===0&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!w&&p.map(R=>e.jsxs("div",{className:"mb-1",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:R.displayName}),R.models.slice(0,80).map(k=>{const _=S?.provider===R.provider&&S?.model===k.id;return e.jsxs("button",{type:"button",onClick:()=>{a({provider:R.provider,model:k.id},u),u&&D({provider:R.provider,model:k.id}),l(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${_?"text-fg-primary":"text-fg-secondary"}`,children:[e.jsx("span",{className:"truncate flex-1",children:k.id}),_&&e.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${R.provider}:${k.id}`)})]},R.provider))]})]})]})}async function Ul(i,a,s){i&&!i.startsWith("new_")&&await M.sessions.setModelOverride(i,a),s&&await M.settings.updateRouting({defaultProvider:a.provider,routingDefaultModel:{provider:a.provider,model:a.model}})}const fi="markus_team_sidebars_c",Gl=["chat","overview","files","tools","memory","deliverables"],Kl=["chat","overview","announcements","norms","settings"];function Yl(i,a){if(i==="chat")return a("page.chatTitle");if(Yr.find(o=>o.key===i))return a(`agent:tabs.${i}`);const r=Xr.find(o=>o.key===i);return r?a(r.labelKey):i}function Xl(i){if(i==="chat")return"💬";const a=Yr.find(r=>r.key===i);if(a)return a.icon;const s=Xr.find(r=>r.key===i);return s?s.icon:""}function us(i){return i!=="chat"}const Gr=new Set;function Ql(){return window.location.hash}function Zl(i){return Gr.add(i),()=>{Gr.delete(i)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Gr.forEach(i=>i()));function oc({initialAgentId:i,authUser:a,previewMode:s,previewData:r}={}){const{t:o,i18n:l}=Ue(["team","common"]),u=n.useMemo(()=>({today:o("page.dateToday"),yesterday:o("page.dateYesterday")}),[o]),m=hi(ut.TEAM),[f,y]=n.useState(r?.agents??[]),[w,j]=n.useState(r?.humans??[]),[A,b]=n.useState(!r),v=Kr(),D=n.useSyncExternalStore(Zl,Ql),T=v&&(D.startsWith(`#${ut.TEAM}/`)||D.startsWith("#chat/")),C=v&&D.match(/^#team\/t\/(.+)$/),p=v?C?"team":T?"chat":"roster":"roster",S=C?C[1]:null,E=n.useRef(ut.TEAM),B=n.useCallback(()=>{E.current=window.location.hash.slice(1)||ut.TEAM,window.location.hash=`${ut.TEAM}/d`},[]),R=n.useCallback(t=>{window.location.hash=`${ut.TEAM}/t/${t}`},[]);n.useEffect(()=>{if(!v)return;const t=()=>{us(pe.current)&&_("chat")};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[v]);const[k,_]=n.useState("chat"),pe=n.useRef("chat");pe.current=k;const $e=Ia({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[ne,$]=n.useState(()=>{try{return localStorage.getItem(fi)==="1"}catch{return!1}}),Ce=n.useCallback(t=>{$(t);try{localStorage.setItem(fi,t?"1":"0")}catch{}},[]),de=Ro(),I=de?.leftCollapsed??!1,Q=de?.rightPanel??null,H=de?.rightPanelTabs??[],ee=de?.activeRightPanelTabId??null,g=de?.rightPanelFullscreen??!1,V=Q?"2xl:pr-8":"2xl:pr-[280px]",oe=de?.setHostAvailable,be=de?.collapseRightPanelOnly??de?.toggleRightPanel,ge=de?.openRightPanel,ye=400,Ye=320,Je=6,[Gt,fs]=n.useState(typeof window<"u"?window.innerWidth:1440),[zt,ss]=n.useState("auto"),gs=n.useRef(I);n.useEffect(()=>{gs.current!==I&&(gs.current=I,$(I))},[I]),n.useEffect(()=>{if(oe)return oe(m&&!v),()=>oe(!1)},[m,v,oe]),n.useEffect(()=>s||v||!m?void 0:We.on("ui:right_panel",c=>{const d=c.payload;if(d.action==="collapse"){be?.();return}if(d.action!=="open"||!d.panel||!ge)return;const x=d.panel;if(x.kind==="url"&&x.url){const P=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ge({kind:"url",url:x.url,title:x.title||x.url,browserId:P});return}if(x.kind==="file"&&x.path){ge({kind:"file",path:x.path,title:x.title});return}x.kind==="deliverable"&&x.deliverableId&&M.deliverables.get(x.deliverableId).then(P=>{P.deliverable&&ge({kind:"deliverable",deliverable:P.deliverable})}).catch(()=>{})}),[s,v,m,be,ge]);const zs=n.useCallback(t=>{const c=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;mr(d=>[...d,{id:c,...t}]),requestAnimationFrame(()=>os.current?.focus())},[]),[Kt,vt]=n.useState(()=>{if(s)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),mt=Ia({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),ie=n.useRef(null),[He,qe]=n.useState(!1),[Be,jt]=n.useState(!1),nn=n.useCallback(()=>{He?jt(t=>!t):vt(t=>{const c=!t;try{localStorage.setItem("markus_team_panel_visible",String(c))}catch{}return c})},[He]);n.useEffect(()=>{if(v)return;const t=ie.current;if(!t)return;const c=new ResizeObserver(([d])=>{if(!d)return;const x=d.contentRect.width;if(fs(x),!s){const P=x-$e.width-mt.width;qe(P<400)}});return c.observe(t),()=>c.disconnect()},[v,s,$e.width,mt.width]);const _n=Kt&&!He&&!Be,rn=ne?0:$e.width+Je+(_n?mt.width+Je:0),Yt=Math.max(0,Gt-rn-Je-8),an=Math.min(ye,Math.floor(Yt*.4)),on=Math.max(0,Yt-an),Qr=Math.min(Math.round(Yt/2),on),hs=Math.max(0,Math.min(zt==="auto"?Qr:zt,on)),ps=n.useRef(!1);n.useEffect(()=>{const t=(de?.rightPanel??null)!==null;t&&!ps.current&&($(!0),ss("auto")),ps.current=t},[de?.rightPanel]);const Xt=n.useRef(hs);Xt.current=hs;const In=n.useRef(on);In.current=on;const cr=n.useCallback(t=>{t.preventDefault();const c=t.clientX,d=Xt.current,x=z=>{const q=d+(c-z.clientX),Y=In.current,N=Math.min(Ye,Y);ss(Math.max(N,Math.min(Y,q)))},P=()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",x),document.addEventListener("mouseup",P),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);n.useEffect(()=>{if(!Be)return;const t=c=>{c.target.closest("[data-l2-floating]")||jt(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Be]);const[Ns,ns]=n.useState(null),[Ln,ln]=n.useState(),[cn,Ss]=n.useState(),[It,Wt]=n.useState(!1),[Rn,dn]=n.useState(""),[Ws,un]=n.useState(!1),[Qt,Cs]=n.useState(""),Hs=n.useRef(null),Lt=n.useRef(null),bs=n.useCallback((t,c)=>{ln(t),Ss(c),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(t??"overview")},[v]),Ts=[{id:"chat"},{id:"profile"}],mn=n.useCallback(t=>{t==="profile"?bs():us(pe.current)?history.back():_("chat")},[bs]),Rt=pi(Ts,k,mn),wt=n.useCallback((t,c)=>{Oe("direct"),ot(t),v&&B(),bs(c?.tab,c?.highlightMailboxId),ns(null)},[v,B,bs]),Ht=n.useCallback((t,c)=>{const d=f.find(x=>x.name.toLowerCase()===t.toLowerCase());if(d){const x=c.target.getBoundingClientRect();ns({agentId:d.id,top:x.bottom,left:x.left})}},[f]),xn=n.useMemo(()=>f.map(t=>t.name),[f]),[L,Oe]=n.useState(()=>r?.chatMode??(i?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[J,ot]=n.useState(()=>i??localStorage.getItem("markus_chat_agent")??""),[Ae,kt]=n.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[rt,Ms]=n.useState(""),Nt=500,Ps=n.useRef(new Set),Vs=t=>{if(Ps.current.add(t),Ps.current.size>Nt){const c=Math.floor(Nt*.2),d=Ps.current.values();for(let x=0;x<c;x++){const P=d.next().value;P&&Ps.current.delete(P)}}},dr=n.useMemo(()=>{if(r?.channelMessages){const t=r.activeChannel??"custom:general";return r.channelMessages.filter(c=>c.channel===t).map(c=>Bs(c))}},[]),{manager:Dn,messages:Ge,setMessages:St,sending:Ct,setSending:lt,activities:ur,setActivities:Vt,msgBuffers:xt,sessionMsgCache:Es,activeSessionBuffer:Pt,actBuffers:Dt,sessionTabsBuffer:$n,currentConvKeyRef:ve,updateConvMsgs:_e,updateConvMsgsRaf:rs,appendConvActivity:As,beginLoad:h,beginStream:W,endStream:U,resetConv:me,loadAndDisplay:ke,incrementSending:Fe,decrementSending:Ke,resetSending:ze,isSendingFor:Ie,setStreamSession:tt,clearStreamSession:ft,getStreamSession:ct,saveSessionToCache:qt,restoreSessionFromCache:it}=Vl(dr),[st,Et]=n.useState(""),[ys,Xe]=n.useState(null),[Zt,mr]=n.useState([]),[Zr,fn]=n.useState([]),$t=n.useRef(null),[xr,On]=n.useState(!!r?.streamLastMessage),_s=n.useRef(null),Ti=400;n.useEffect(()=>(Ct?(_s.current&&(clearTimeout(_s.current),_s.current=null),On(!0)):xr&&(_s.current=setTimeout(()=>{On(!1),_s.current=null},Ti)),()=>{_s.current&&clearTimeout(_s.current)}),[Ct]);const Jr=Ct||xr||(()=>{for(let t=Ge.length-1;t>=Math.max(0,Ge.length-8);t--){const c=Ge[t];if(c.isStreaming&&!c.isStopped)return!0}return!1})(),fr=n.useRef({fullText:"",timers:[]});n.useEffect(()=>{if(!s||!r?.streamLastMessage||Ge.length===0)return;const t=Ge[Ge.length-1];if(!t||t.sender!=="agent")return;const c=t.text;fr.current.fullText=c;const d=fr.current.timers;function x(){let z=0;St(Y=>Y.map((N,O)=>O===Y.length-1?{...N,text:""}:N)),On(!0);const q=setInterval(()=>{if(z+=1+Math.floor(Math.random()*2),z>=c.length){clearInterval(q),St(O=>O.map((Me,je)=>je===O.length-1?{...Me,text:c}:Me));const Y=setTimeout(()=>On(!1),800);d.push(Y);const N=setTimeout(x,6e3);d.push(N)}else St(Y=>Y.map((N,O)=>O===Y.length-1?{...N,text:c.slice(0,z)}:N))},30);d.push(q)}const P=setTimeout(x,1500);return d.push(P),()=>{d.forEach(z=>clearTimeout(z)),fr.current.timers=[]}},[]);const vs=n.useRef(0),[ea,as]=n.useState(!1),[gr,ta]=n.useState(!1),[sa,is]=n.useState(!1),[Ut,hr]=n.useState([]),pr=n.useRef(null),os=n.useRef(null),[Fn,Bn]=n.useState(null),js=n.useRef(null),br=n.useRef(!1),gn=n.useCallback(()=>{const t=os.current;if(!t)return;const c=br.current,d=c?36:52,x=c?160:120;t.style.height="auto";const P=Math.max(d,Math.min(t.scrollHeight,x));t.style.height=`${P}px`,t.style.overflowY=P>=x?"auto":"hidden"},[]);n.useEffect(()=>{gn()},[st,gn]);const yr=t=>{try{const c=localStorage.getItem(`markus_closed_tabs_${t}`);return c?new Set(JSON.parse(c)):new Set}catch{return new Set}},Mi=(t,c)=>{const d=yr(t);d.add(c);try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...d]))}catch{}},Pi=(t,c)=>{const d=yr(t);if(d.delete(c))try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...d]))}catch{}},Ei=t=>{try{return localStorage.getItem(`markus_active_session_${t}`)}catch{return null}},vr=(t,c)=>{if(t)try{c&&c!==Ve?localStorage.setItem(`markus_active_session_${t}`,c):localStorage.removeItem(`markus_active_session_${t}`)}catch{}},[na,qs]=n.useState([]),[Le,ls]=n.useState(null),[Is,Ls]=n.useState(!1),[ra,jr]=n.useState([]),[hn,wr]=n.useState(null),[Ai,aa]=n.useState(null),[zn,_i]=n.useState([]),At=t=>{_i(c=>{const d=typeof t=="function"?t(c):t,x=new Set;return d.filter(P=>x.has(P.id)?!1:(x.add(P.id),!0))})},Wn=n.useRef(null),kr=n.useRef(null),Jt=n.useRef(null),[pt,pn]=n.useState(r?.groupChats??[]),Nr=n.useRef(pt);Nr.current=pt;const ia=n.useRef(null),[bn,gt]=n.useState(!1),[Rs,yn]=n.useState(!1),[oa,Us]=n.useState(""),[Sr,ws]=n.useState([]),[la,ca]=n.useState(!1),Cr=n.useRef(void 0),[es,da]=n.useState(r?.teams??[]),[Ii,Li]=n.useState([]),[Hn,ua]=n.useState([]),[Ri,Di]=n.useState(null),[Jl,ec]=n.useState(!1),[tc,sc]=n.useState(""),[ma,vn]=n.useState(!1),[xa,$i]=n.useState(""),[jn,Gs]=n.useState(0),[Oi,Fi]=n.useState([]),fa=n.useRef(!1),Bi=n.useCallback(()=>{fa.current||(fa.current=!0,(async()=>{const t=[];try{const[c,d,x,P,z]=await Promise.all([M.projects.list().catch(()=>({projects:[]})),M.requirements.list().catch(()=>({requirements:[]})),M.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),M.deliverables.search({limit:100}).catch(()=>({results:[]})),M.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const q of c.projects)t.push({id:q.id,name:q.name,entityType:"project",role:q.status});for(const q of d.requirements)t.push({id:q.id,name:q.title,entityType:"requirement",role:q.priority});for(const q of x.tasks)t.push({id:q.id,name:q.title,entityType:"task",role:q.status});for(const q of P.results)t.push({id:q.id,name:q.title,entityType:"deliverable",role:q.type});for(const q of z.teams)try{const Y=await M.workflows.list(q.id);for(const N of Y.workflows)t.push({id:N.name,name:N.displayName||N.name,entityType:"workflow",role:`v${N.version}`})}catch{}}catch{}Fi(t)})())},[]),nt=L==="channel"?pt.find(t=>t.channelKey===Ae)?.teamId:void 0,zi=n.useRef(null),wn=n.useRef(null),bt=n.useRef(null),ga=n.useRef(void 0),Vn=n.useRef(!1),ts=n.useRef(!0),ha=n.useRef(void 0);n.useEffect(()=>{if(!Is)return;const t=c=>{kr.current&&!kr.current.contains(c.target)&&Wn.current&&!Wn.current.contains(c.target)&&Ls(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Is]);const qn=(t,c)=>{if(!c||t===c)return`notes:${t}`;const[d,x]=[t,c].sort();return`dm:${d}:${x}`};n.useEffect(()=>{localStorage.setItem("markus_chat_mode",L)},[L]),n.useEffect(()=>{localStorage.setItem("markus_chat_agent",J)},[J]),n.useEffect(()=>{localStorage.setItem("markus_chat_channel",Ae)},[Ae]);const{counts:Tr,sessionAgentMap:kn,markRead:Nn,setActiveKey:Wi,clearActiveKey:Hi}=Do({enabled:!s}),Un=n.useMemo(()=>{const t={};for(const[c,d]of Object.entries(Tr))c.startsWith("channel:")&&(t[c.slice(8)]=d);return t},[Tr]),Mr=$o(kn,Tr);n.useEffect(()=>{let t=0;for(const c of Mr.values())t+=c;for(const c of Object.values(Un))t+=c;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:t}}))},[Mr,Un]);const Gn=Mr,Vi=n.useCallback(async t=>{for(const[c,d]of Object.entries(kn))d===t&&Nn(`session:${c}`)},[kn,Nn]);n.useEffect(()=>{if(s||!((!v||p==="chat")&&k==="chat"))return;if(L==="direct"&&J&&Vi(J),L==="channel"&&Ae)Nn(`channel:${Ae}`);else if(L==="direct"&&Le)Nn(`session:${Le}`);else if(L==="dm"&&rt){const d=`dm:${[a?.id,rt].sort().join(":")}`;Nn(`channel:${d}`)}const c=[];if(L==="direct"&&Le){c.push(`session:${Le}`);for(const[d,x]of Object.entries(kn))x===J&&c.push(`session:${d}`)}else L==="channel"&&Ae?c.push(`channel:${Ae}`):L==="dm"&&rt&&a?.id&&c.push(`channel:dm:${[a.id,rt].sort().join(":")}`);for(const d of c)Wi(d);return()=>{for(const d of c)Hi(d)}},[s,L,Ae,Le,rt,J,p,k,kn]);const Ot=n.useCallback(()=>M.agents.list().then(t=>y(t.agents)).catch(()=>{}),[]),_t=n.useCallback(()=>M.teams.list().then(t=>da(t.teams)).catch(()=>{}),[]),Ks=n.useCallback(()=>M.groupChats.list().then(t=>pn(t.chats)).catch(()=>{}),[]),qi=n.useMemo(()=>Br(Ot,3e3),[Ot]),Kn=n.useMemo(()=>Br(_t,5e3),[_t]),Pr=n.useMemo(()=>Br(Ks,3e3),[Ks]),Sn=n.useCallback(()=>{M.users.list(a?.orgId).then(t=>j(t.users)).catch(()=>{})},[a?.orgId]);n.useEffect(()=>{s||(Promise.all([Ot(),_t()]).finally(()=>b(!1)),Sn(),M.tasks.list().then(t=>ua(t.tasks)).catch(()=>{}),M.externalAgents.list().then(t=>Li(t.agents)).catch(()=>{}),Ks())},[s,Sn]),n.useEffect(()=>{if(!(!s||!r)&&(y(r.agents??[]),j(r.humans??[]),da(r.teams??[]),pn(r.groupChats??[]),r.channelMessages)){const t=r.activeChannel??"custom:general";St(r.channelMessages.filter(c=>c.channel===t).map(c=>Bs(c)))}},[s,r]),n.useEffect(()=>{if(s||!m)return;Ot(),_t();const t=setInterval(Ot,3e4),c=setInterval(_t,6e4),d=We.on("agent:update",()=>{qi(),Kn()}),x=We.on("team:update",()=>{Kn(),Pr()}),P=We.on("agent:removed",Kn),z=We.on("chat:group_created",()=>{Ks(),_t(),Ot()}),q=We.on("chat:group_updated",Pr),Y=We.on("chat:group_deleted",()=>{Pr(),Kn()}),N=We.on("task:update",Me=>{const je=Me?.payload;je?.taskId&&ua(xe=>xe.map(re=>re.id===je.taskId?{...re,status:je.status??re.status}:re))}),O=()=>{Ot(),_t(),Sn()};return window.addEventListener("markus:data-changed",O),()=>{clearInterval(t),clearInterval(c),d(),x(),P(),z(),q(),Y(),N(),window.removeEventListener("markus:data-changed",O)}},[s,m,Sn]),n.useEffect(()=>{if(s)return;const t=Y=>{const N=Y.detail;if(qo(N.page)===ut.TEAM){if(N.params?.agentId){if(N.params.profileTab)wt(N.params.agentId,{tab:N.params.profileTab});else if(Oe("direct"),ot(N.params.agentId),_("chat"),v&&B(),N.params.sessionId){const O=N.params.sessionId;setTimeout(async()=>{try{const{sessions:Me}=await M.sessions.listByAgent(N.params.agentId,20),je=Me.find(xe=>xe.id===O);je&&Jn(je)}catch{}},300)}}if(N.params?.selectAgent&&(Oe("direct"),ot(N.params.selectAgent),_("chat"),v&&B()),N.params?.prefillMessage){const O=N.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),N.params?.autoSend==="true"?setTimeout(()=>ga.current?.(O),300):(Et(O),setTimeout(()=>{const Me=os.current;Me&&(Me.focus(),Me.setSelectionRange(Me.value.length,Me.value.length))},100))}if(N.params?.dm&&(Oe("dm"),Ms(N.params.dm),_("chat"),v&&B()),N.params?.channel&&(Oe("channel"),kt(N.params.channel),_("chat"),v&&B()),N.params?.selectTeam){const O=N.params.selectTeam;if(v)R(O);else{const Me=Nr.current.find(je=>je.type==="team"&&je.teamId===O);Oe("channel"),kt(Me?.channelKey??`group:${O}`),_("chat"),gt(!1),vt(!0)}}N.params?.openHire}},c=localStorage.getItem("markus_nav_agentId");if(c){localStorage.removeItem("markus_nav_agentId");const Y=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),Oe("direct"),ot(c),Y?wt(c,{tab:Y}):(_("chat"),v&&B())}const d=localStorage.getItem("markus_nav_dm");d&&(localStorage.removeItem("markus_nav_dm"),Oe("dm"),Ms(d),_("chat"),v&&B());const x=localStorage.getItem("markus_nav_channel");x&&(localStorage.removeItem("markus_nav_channel"),Oe("channel"),kt(x),_("chat"),v&&B());const P=localStorage.getItem("markus_nav_prefillMessage");P&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),Et(P),setTimeout(()=>{const Y=os.current;Y&&(Y.focus(),Y.setSelectionRange(Y.value.length,Y.value.length))},150));const z=localStorage.getItem("markus_nav_selectAgent");z&&(localStorage.removeItem("markus_nav_selectAgent"),Oe("direct"),ot(z),_("chat"),v&&B());const q=localStorage.getItem("markus_nav_selectTeam");if(q)if(localStorage.removeItem("markus_nav_selectTeam"),v)R(q);else{const Y=Nr.current.find(N=>N.type==="team"&&N.teamId===q);Oe("channel"),kt(Y?.channelKey??`group:${q}`),_("chat"),gt(!1),vt(!0)}return window.addEventListener("markus:navigate",t),()=>window.removeEventListener("markus:navigate",t)},[s]),n.useEffect(()=>{const t=ia.current;if(!t)return;const c=pt.find(d=>d.type==="team"&&d.teamId===t);ia.current=null,Oe("channel"),kt(c?.channelKey??`group:${t}`),_("chat"),gt(!1),vt(!0)},[pt,es]),n.useEffect(()=>{if(s&&r?.chatMode==="channel"||f.length===0||J&&f.some(c=>c.id===J))return;const t=f.find(c=>!c.teamId&&c.role?.toLowerCase()==="secretary")??f.find(c=>c.role?.toLowerCase()==="secretary")??f.find(c=>c.name?.toLowerCase().includes("secretary"));t?(Oe("direct"),ot(t.id),_("chat")):f.length>0&&(Oe("direct"),ot(f[0].id),_("chat"))},[f,J]);const Yn=n.useRef(!1),[Ui,Ds]=n.useState(!1),$s=n.useRef(0),[pa,Ys]=n.useState(0),Xs=n.useCallback(t=>{const c=wn.current;if(!c)return;if(c.scrollHeight-c.scrollTop-c.clientHeight<160){ts.current=!0,Ds(!1),$s.current=0,Ys(0);return}t?.fromProgrammatic||Yn.current||(ts.current=!1,Ds(!0))},[]);n.useEffect(()=>{const t=wn.current;if(!t)return;const c=()=>{Xs({fromProgrammatic:Yn.current})};t.addEventListener("scroll",c,{passive:!0});const d=typeof ResizeObserver<"u"?new ResizeObserver(()=>Xs()):null;return d?.observe(t),Xs(),()=>{t.removeEventListener("scroll",c),d?.disconnect()}},[p,Xs]);const ht=n.useMemo(()=>L==="channel"?Ge:Ge.filter(t=>!t.isActivityLog),[Ge,L]);n.useEffect(()=>{br.current=k==="chat"&&ht.length>0,gn()},[k,ht.length,gn]);const cs=dl({count:ht.length,getScrollElement:()=>wn.current,estimateSize:t=>{const c=ht[t];return c?c.segments&&c.segments.length>0?300:c.text.length>500?200:120:120},overscan:8});cs.shouldAdjustScrollPositionOnItemSizeChange=(t,c,d)=>La()?!1:t.start<(d.scrollOffset??0);const Qs=n.useCallback((t="instant")=>{Yn.current=!0;const c=()=>{Yn.current=!1,ts.current=!0,Ds(!1),$s.current=0,Ys(0),requestAnimationFrame(()=>Xs({fromProgrammatic:!0}))};if(ht.length>0)cs.scrollToIndex(ht.length-1,{align:"end",behavior:t}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{cs.scrollToIndex(ht.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(c)})});else{const d=wn.current;d&&d.scrollTo({top:d.scrollHeight,behavior:t}),requestAnimationFrame(c)}},[ht.length,cs,Xs]),ba=n.useRef(m);n.useEffect(()=>{ba.current=m},[m]),n.useLayoutEffect(()=>{if(Vn.current){Vn.current=!1;const t=Qn.current;t>0&&(Qn.current=0,cs.scrollToIndex(t,{align:"start",behavior:"instant"}));return}ba.current&&ts.current&&(La()||Qs())},[Ge,Qs,cs]);const ya=n.useRef(k);n.useEffect(()=>{const t=ya.current!=="chat";if(ya.current=k,k==="chat"&&t&&(ts.current||Ct)){const c=[],d=requestAnimationFrame(()=>Qs("instant"));for(const x of[60,160,320])c.push(setTimeout(()=>Qs("instant"),x));return()=>{cancelAnimationFrame(d);for(const x of c)clearTimeout(x)}}},[k,Ct,Qs]);const va=n.useCallback(async(t,c)=>{const d=c??`ch:${t}`;ve.current===d&&is(!0);try{const x=await M.channels.getMessages(t,50),P=x.messages.map(z=>Bs(z,a?.id));xt.set(d,P),ve.current===d&&(St(P),as(x.hasMore),Jt.current=x.messages[0]?new Date(x.messages[0].createdAt).toISOString():null)}catch{ve.current===d&&(St([]),as(!1))}finally{ve.current===d&&is(!1)}},[]),Er=n.useCallback(async(t,c)=>{const d=ve.current===c&&(xt.get(c)?.length??0)===0;d&&is(!0);try{const{count:x,hasMore:P,oldestCursor:z}=await ke(t,c,async()=>{const q=await M.sessions.getMessages(t,50);return{messages:Ko(q.messages.map(zr).filter(N=>N.sender!=="agent"||N.text||N.segments&&N.segments.length>0||N.isStreaming)),hasMore:q.hasMore,oldestCursor:q.messages[0]?new Date(q.messages[0].createdAt).toISOString():null}});return as(P),Jt.current=z,x}finally{d&&ve.current===c&&is(!1)}},[ke,xt]),ja=n.useRef(new Map),Os=n.useCallback(async(t,c,d)=>{if(!t||!c||c===Ve)return;let x=null;try{if(bt.current&&!bt.current.signal.aborted&&ct(d)?.has(c)){W(d),ve.current===d&<(!0);return}const P=`${t}:${c}`,z=ja.current.get(P)??0;if(Date.now()-z<1500)return;const q=await M.sessions.streamStatus(t,c),N=[...xt.get(d)??[]].reverse().find(X=>X.sender==="agent"),O=q.status==="streaming",Me=!!q.active&&(q.status==="done"||q.status==="error")&&!!N?.isStreaming;if(!O&&!Me)return;ja.current.set(P,Date.now()),js.current?.abort(),x=new AbortController,js.current=x,W(d),lt(!0),tt(d,c);let je=N?.id;if(!N||N.isError)je=`reattach_${Date.now()}`,_e(d,X=>[...X,{id:je,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],c);else{const X=(N.segments??[]).filter(he=>he.type==="tool").map(he=>he.status==="stopped"||he.status==="running"?{...he,status:"running"}:he);_e(d,he=>he.map(te=>te.id===N.id?{...te,text:"",isStreaming:!0,isStopped:!1,segments:X,committedSegments:void 0}:te),c)}let xe=!1;const re=X=>{ve.current===d&&(vs.current=Date.now(),rs(d,he=>{const te=[...he],ae=je?te.findIndex(F=>F.id===je):-1,ue=ae>=0?ae:te.map((F,se)=>({m:F,j:se})).reverse().find(F=>F.m.sender==="agent")?.j??-1;if(ue<0)return he;const fe=te[ue].segments??[],Te=fe[fe.length-1],Qe=Te?.type==="text"?Te.thinking??"":"";let Tt="",G="",Z=X;for(;Z.length>0;)if(xe){const F=Z.indexOf("</think>");F>=0?(Tt+=Z.slice(0,F),Z=Z.slice(F+8),xe=!1):(Tt+=Z,Z="")}else{const F=Z.indexOf("<think>");F>=0?(G+=Z.slice(0,F),Z=Z.slice(F+7),xe=!0):(G+=Z,Z="")}const ce=Qe+Tt||void 0,K=Te?.type==="text"?[...fe.slice(0,-1),{type:"text",content:Te.content+G,thinking:ce,createdAt:Te.createdAt}]:[...fe,{type:"text",content:G,thinking:ce,createdAt:new Date().toISOString()}];return te[ue]={...te[ue],text:(te[ue].text??"")+G,segments:K,isStreaming:!0},te},c))},Re=X=>{if(ve.current===d&&(vs.current=Date.now(),X.phase!=="heartbeat")){if((X.phase==="start"||X.phase==="end")&&As(d,{...X,phase:X.phase,ts:Date.now()},c),X.phase==="start"){const he=`${X.tool}_${Date.now()}`,te=new Date().toISOString(),ae=ue=>{const fe=[...ue];for(let Te=fe.length-1;Te>=0;Te--){const Qe=fe[Te];if(Qe.type==="tool"&&Qe.tool===X.tool&&(Qe.status==="running"||Qe.status==="stopped"))return fe[Te]={...Qe,status:"running",args:X.arguments??Qe.args},fe}return fe.push({type:"tool",key:he,tool:X.tool,status:"running",args:X.arguments,createdAt:te}),fe};_e(d,ue=>{const fe=[...ue],Te=je?fe.findIndex(Z=>Z.id===je):-1;if(Te<0)return ue;const Qe=ae(fe[Te].segments??[]),Tt=fe[Te].committedSegments,G=Tt&&ae(Tt);return fe[Te]={...fe[Te],segments:Qe,committedSegments:G,isStreaming:!0},fe},c)}else if(X.phase==="end"){const he=new Date().toISOString(),te=ae=>{const ue=[...ae];for(let fe=ue.length-1;fe>=0;fe--){const Te=ue[fe];if(Te.type==="tool"&&Te.tool===X.tool&&(Te.status==="running"||Te.status==="stopped")){ue[fe]={...Te,status:X.success===!1?"error":"done",args:X.arguments??Te.args,result:X.result,error:X.error,durationMs:X.durationMs,liveOutput:void 0,createdAt:he};break}}return ue};_e(d,ae=>{const ue=[...ae],fe=je?ue.findIndex(G=>G.id===je):-1;if(fe<0)return ae;const Te=te(ue[fe].segments??[]),Qe=ue[fe].committedSegments,Tt=Qe&&te(Qe);return ue[fe]={...ue[fe],segments:Te,committedSegments:Tt,isStreaming:!0},ue},c)}else if(X.phase==="subagent_progress"&&X.subagentEvent){const he=te=>{const ae=[...te];for(let ue=ae.length-1;ue>=0;ue--){const fe=ae[ue];if(fe.type==="tool"&&(fe.tool==="spawn_subagent"||fe.tool==="spawn_subagents")&&(fe.status==="running"||fe.status==="stopped")){ae[ue]={...fe,status:"running",subagentLogs:Oa(fe.subagentLogs,X.subagentEvent)};break}}return ae};rs(d,te=>{const ae=[...te],ue=je?ae.findIndex(Tt=>Tt.id===je):-1;if(ue<0)return te;const fe=he(ae[ue].segments??[]),Te=ae[ue].committedSegments,Qe=Te&&he(Te);return ae[ue]={...ae[ue],segments:fe,committedSegments:Qe,isStreaming:!0},ae},c)}}},le=X=>{ve.current===d&&(vs.current=Date.now(),_e(d,he=>{const te=[...he],ae=je?te.findIndex(fe=>fe.id===je):-1;if(ae<0)return he;const ue=[...te[ae].committedSegments??[]];if(X.type==="thinking_commit")ue.push({type:"text",content:"",thinking:X.content,createdAt:X.createdAt});else if(X.type==="text_commit")ue.push({type:"text",content:X.content,createdAt:X.createdAt});else return he;return te[ae]={...te[ae],committedSegments:ue,isStreaming:!0},te},c))},we=X=>{if(ve.current!==d)return;vs.current=Date.now();const he=(X.segments??[]).map((te,ae)=>te.type==="tool"?{type:"tool",key:`${te.tool}_${ae}`,tool:te.tool??"tool",status:te.status==="error"?"error":te.status==="running"||te.status==="stopped"?"running":"done",args:te.arguments,result:te.result,error:te.error,durationMs:te.durationMs,createdAt:te.createdAt,...te.subagentLogs?.length?{subagentLogs:te.subagentLogs}:{}}:{type:"text",content:te.content??"",thinking:te.thinking,createdAt:te.createdAt});_e(d,te=>{const ae=[...te],ue=je?ae.findIndex(fe=>fe.id===je):-1;return ue<0?te:(ae[ue]={...ae[ue],text:X.content||ae[ue].text,segments:he,committedSegments:he,isStreaming:!0,isStopped:!1},ae)},c);for(const te of he)te.type==="tool"&&As(d,{tool:te.tool,phase:te.status==="running"||te.status==="stopped"?"start":"end",success:te.status!=="error",arguments:te.args,result:te.result,error:te.error,durationMs:te.durationMs,ts:Date.now()},c)},Se=await M.sessions.reattachStream(t,c,{onChunk:re,onActivity:Re,onCommit:le,onSnapshot:we},x.signal,0);if(!Se.attached){U(d),ve.current===d&<(!1);return}ve.current===d&&(_e(d,X=>{const he=[...X],te=je?he.findIndex(Te=>Te.id===je):-1,ae=te>=0?te:he.map((Te,Qe)=>({m:Te,j:Qe})).reverse().find(Te=>Te.m.sender==="agent")?.j??-1;if(ae<0)return X;const ue=he[ae],fe=Se.segments?.length?Fa(Se.segments,ue.segments):void 0;return he[ae]={...ue,text:Se.content||ue.text,isStreaming:!1,isStopped:!1,...fe?{segments:fe,committedSegments:fe}:{}},he},c),lt(!1)),U(d),js.current===x&&(js.current=null)}catch(P){if(js.current===x&&(js.current=null),U(d),ve.current===d&<(!1),P instanceof Error&&P.name==="AbortError")return}},[As,W,U,ct,xt,tt,_e,rs]);n.useEffect(()=>{if(!m||s||L!=="direct"||!J)return;const t=Le;!t||t===Ve||Os(J,t,ve.current)},[m,s,L,J,Le,Os]);const Xn=n.useCallback(async t=>{if(!t)return qs([]),[];try{const{sessions:c}=await M.sessions.listByAgent(t,10);return qs(c),c}catch{return qs([]),[]}},[]),Qn=n.useRef(0),Gi=n.useCallback(async()=>{if(!(gr||!ea||!Jt.current)){ta(!0);try{const t=ve.current;if(L==="channel"||L==="dm"){const c=L==="dm"?qn(a?.id??"",rt):Ae,d=await M.channels.getMessages(c,50,Jt.current),x=d.messages.map(P=>Bs(P,a?.id));Qn.current=x.length,Vn.current=!0,St(P=>{let z=[...x,...P];return z.length>500&&(z=z.slice(-500)),xt.set(t,z),z}),as(d.hasMore),d.messages[0]&&(Jt.current=new Date(d.messages[0].createdAt).toISOString())}else if(Le){const c=await M.sessions.getMessages(Le,50,Jt.current),d=c.messages.map(zr);Qn.current=d.length,Vn.current=!0,St(x=>{let P=[...d,...x];return P.length>500&&(P=P.slice(-500)),xt.set(t,P),P}),as(c.hasMore),c.messages[0]&&(Jt.current=new Date(c.messages[0].createdAt).toISOString())}}catch{}finally{ta(!1)}}},[gr,ea,L,Ae,Le,a?.id,rt]);ha.current=Gi;const Ar=n.useRef(!1),Ki=n.useCallback(t=>{Ar.current||(Ar.current=!0,requestAnimationFrame(()=>{Ar.current=!1,t.target.scrollTop<100&&ha.current?.()}))},[]);n.useEffect(()=>{if(s)return;const t=qr(L,J,Ae,rt),c=ve.current;ve.current=t,c&&c!==t&&($n.set(c,zn),Le&&Pt.set(c,Le)),c!==t&&(ts.current=!0,Ds(!1),$s.current=0,Ys(0));const d=xt.get(t),x=$n.get(t),P=Pt.get(t),z=ct(t),q=P??Le,Y=Ie(t)&&(L!=="direct"||!z||!q||z.has(q)),N=q??t,O=Dt.get(N)??[];if(Vt(Y?O:[]),lt(Y),L==="direct"&&J&&Xn(J),x&&x.length>0&&At(x),Ls(!1),d!==void 0&&d.length>0)if(Y||Dn.completeLoad(t),is(!1),St(d),as(!1),P!==void 0&&ls(P),(!x||x.length===0)&&At([]),L==="channel"||L==="dm"){const je=L==="dm"?qn(a?.id??"",rt):Ae;va(je,t)}else L==="direct"&&J&&P&&P!==Ve&&(Y?Os(J,P,t):Er(P,t).then(()=>{ve.current===t&&J&&Os(J,P,t)}));else if(h(t),is(!0),St([]),as(!1),Jt.current=null,xt.delete(t),L==="channel"||L==="dm"){const je=L==="dm"?qn(a?.id??"",rt):Ae;va(je,t),(!x||x.length===0)&&At([])}else L==="direct"&&J?Xn(J).then(je=>{if(ve.current===t)if(je.length>0){const xe=je.find(ae=>ae.isMain),re=yr(J),Re=xe?[xe,...je.filter(ae=>!ae.isMain&&!re.has(ae.id)).slice(0,4)]:je.filter(ae=>!re.has(ae.id)).slice(0,5);let le=x&&x.length>0?x:Re;const we=Ei(J),Se=P!==void 0?P:we??xe?.id??le[0].id;if(Se&&Se!==Ve&&!le.some(ae=>ae.id===Se)){const ae=je.find(ue=>ue.id===Se);ae&&(le=[...le,ae])}const X=Se&&le.some(ae=>ae.id===Se)?Se:le[0].id;ls(X),Pt.set(t,X),vr(J,X),At(le);const te=je.find(ae=>ae.id===X)?.metadata?.modelOverride;Bn(te?.provider&&te?.model?{provider:te.provider,model:te.model}:null),Er(X,t).then(()=>{ve.current===t&&J&&Os(J,X,t)})}else ls(null),Bn(null),is(!1),(!x||x.length===0)&&At([])}).catch(()=>{ve.current===t&&is(!1)}):is(!1)},[s,L,J,Ae,rt,l.language,o]),n.useEffect(()=>s?void 0:We.on("chat:message",c=>{const d=c.payload,x=d.channel??"";if(!x)return;const P=d.senderType??"agent",z=d.text??d.message??"",q=d.senderId??d.agentId??"",Y=d.senderName??d.agentId??o("page.fallbackAgent"),N=d.metadata,O=d.messageId??d.id??"";if(O&&Ps.current.has(O))return;const Me=P==="human"&&q===(a?.id??""),je={id:O||`ws_${Date.now()}_${q}`,sender:Me?"user":"agent",text:z,time:new Date().toLocaleTimeString(),agentName:Me?void 0:Y,agentId:Me?void 0:q,replyToId:d.replyToId??void 0,replyToSender:d.replyToSender??void 0,replyToText:d.replyToText??void 0};if(N&&P==="agent"){const re=[];if(N.thinking?.length&&re.push({type:"text",content:"",thinking:N.thinking.join(`
|
|
33
|
-
|
|
34
|
-
`)}),N.toolCalls?.length)for(let Re=0;Re<N.toolCalls.length;Re++){const le=N.toolCalls[Re];re.push({type:"tool",key:`${le.tool}_${Re}`,tool:le.tool,status:le.status==="error"?"error":"done",args:le.arguments,result:le.result,durationMs:le.durationMs})}re.length>0&&(re.push({type:"text",content:z}),je.segments=re)}let xe;if(x.startsWith("notes:"))xe=`dm:${x.slice(6)}`;else if(x.startsWith("dm:")){const re=x.slice(3).split(":");xe=`dm:${re.find(le=>le!==(a?.id??""))??re[0]??""}`}else xe=`ch:${x}`;_e(xe,re=>[...re,je]),xe===ve.current&&!ts.current&&($s.current+=1,Ys($s.current),Ds(!0)),P==="agent"&&xe===`ch:${Ae}`&&fn(re=>{const Re=re.filter(le=>le.id!==q);return Re.length===0&&$t.current&&(clearTimeout($t.current),$t.current=null),Re})}),[s,_e,a?.id,Ae]),n.useEffect(()=>s?void 0:We.on("chat:agent_no_response",c=>{const d=c.payload,x=d.channel??"",P=d.agentId??"";x&&P&&`ch:${Ae}`==`ch:${x}`&&fn(z=>{const q=z.filter(Y=>Y.id!==P);return q.length===0&&$t.current&&(clearTimeout($t.current),$t.current=null),q})}),[s,Ae]),n.useEffect(()=>s?void 0:We.on("chat:proactive_message",c=>{const d=c.payload,x=d.targetUserId;if(x&&x!==a?.id)return;const P=d.agentId??"",z=d.agentName??o("page.fallbackAgent"),q=d.message??"",Y=d.sessionId??"",N=d.messageId??"",O=d.metadata??{};if(!P||!q||q==="[cancelled]"||q==="[Stream cancelled]")return;const Me=O.role==="user",je=!Me&&(!!O.activityLog||q.startsWith("[ACTIVITY:")),{cleaned:xe,priority:re}=Yo(q),Re=!Me&&(!!O.notifyUser||xe!==q),le=qr("direct",P,"","");if(Y&&ve.current===le){const ae=Le;if(ae&&ae!==Ve&&ae!==Y)return}const we=!!O.isMainSession&&!Me,Se=Y||Le,X=typeof O.userText=="string"?O.userText:"",he=typeof O.userMessageId=="string"?O.userMessageId:"",te={id:N||`proactive_${Date.now()}`,sender:Me?"user":"agent",text:xe,time:new Date().toLocaleTimeString(),...Me?{}:{agentName:z,agentId:P,...Re?{isNotification:!0,notifyPriority:O.priority??re}:{},...je?{isActivityLog:!0,activityType:O.activityType,outcome:O.outcome,mailboxItemId:O.mailboxItemId,taskId:O.taskId,requirementId:O.requirementId}:{},...!je&&O.taskId?{taskId:O.taskId}:{},...!je&&O.requirementId?{requirementId:O.requirementId}:{}}};_e(le,ae=>{if(ae.some(fe=>fe.id===te.id))return ae;let ue=ae;if(!Me&&X&&(ue.some(Te=>he&&Te.id===he||Te.sender==="user"&&Te.text===X)||(ue=[...ue,{id:he||`feishu_user_${te.id}`,sender:"user",text:X,time:new Date().toLocaleTimeString()}])),we)for(let fe=ue.length-1;fe>=0;fe--){const Te=ue[fe];if(Te.sender==="agent"&&Te.agentId===P&&Te.isStopped){const Qe=[...ue];return Qe[fe]={...te,id:Te.id},Qe}}return[...ue,te]},Se||void 0)}),[s,_e,o,Le]),Hn.find(t=>t.id===Ri),n.useEffect(()=>{Di(null)},[J]);const Yi=t=>Uo(t),Xi=()=>{const t=L==="direct"?J:null;t&&M.agents.cancelProcessing(t).catch(()=>{}),bt.current?.abort(),bt.current=null,js.current?.abort(),js.current=null;const c=ve.current;ze(c),Dt.delete(Le??c),Le&&ft(c,Le),U(c),lt(!1),Vt([])},wa=n.useRef(null),Zs=async(t,c)=>{const d=!t&&Zt.length>0?Zt.map(xe=>xe.content).join(`
|
|
35
|
-
|
|
36
|
-
`)+`
|
|
37
|
-
|
|
38
|
-
`:"",x=(t??d+st).trim();if(!x&&Ut.length===0||L==="direct"&&!J)return;ts.current=!0;const P=Date.now(),z=wa.current;if(!c?.isRetry&&!c?.isResume&&x&&z&&z.text===x&&P-z.at<1500)return;if(wa.current={text:x,at:P},Ct&&L==="direct"){if(Le&&Le!==Ve){const re=ve.current;if([...xt.get(re)??[]].reverse().find(we=>we.sender==="user")?.text===x&&!c?.isRetry&&!c?.isResume)return bt.current?.abort(),bt.current=null,M.agents.cancelProcessing(J).catch(()=>{}),ze(re),Dt.delete(Le??re),U(re),_e(re,we=>{const Se=[...we];return Se.length>0&&Se[Se.length-1].sender==="agent"&&Se.pop(),Se.length>0&&Se[Se.length-1].sender==="user"&&Se[Se.length-1].text===x&&Se.pop(),Se}),lt(!1),Vt([]),await new Promise(we=>setTimeout(we,50)),Zs(x,{isRetry:!0});bt.current?.abort(),bt.current=null,M.agents.cancelProcessing(J).catch(()=>{}),ze(re),Dt.delete(Le??re),U(re),_e(re,we=>{const Se=[...we];for(let X=Se.length-1;X>=0;X--)if(Se[X].sender==="agent"&&!Se[X].isStopped&&!Se[X].isError){const he=Se[X];if(!(he.text?.trim()||(he.segments??[]).some(ae=>ae.type==="text"&&(ae.content||ae.thinking)||ae.type==="tool")))Se.splice(X,1);else{const ae=(he.segments??[]).map(ue=>ue.type==="tool"&&ue.status==="running"?{...ue,status:"stopped"}:ue);Se[X]={...he,isStopped:!0,segments:ae}}break}return Se}),lt(!1),Vt([]),await new Promise(we=>setTimeout(we,50))}}else if(Ct&&L!=="direct"){bt.current?.abort(),bt.current=null;const xe=ve.current;ze(xe),Dt.delete(xe),U(xe),_e(xe,re=>{const Re=[...re];for(let le=Re.length-1;le>=0;le--)if(Re[le].sender==="agent"&&!Re[le].isStopped&&!Re[le].isError){const we=Re[le];if(!(we.text?.trim()||(we.segments??[]).some(X=>X.type==="text"&&(X.content||X.thinking)||X.type==="tool")))Re.splice(le,1);else{const X=(we.segments??[]).map(he=>he.type==="tool"&&he.status==="running"?{...he,status:"stopped"}:he);Re[le]={...we,isStopped:!0,segments:X}}break}return Re}),lt(!1),Vt([]),await new Promise(re=>setTimeout(re,50))}const q=Ut.length>0?Ut.map(xe=>xe.dataUrl):void 0,Y=Ut.length>0?Ut.map(xe=>xe.name):void 0,N=qr(L,J,Ae,rt),O=ys;t||(Et(""),mr([])),hr([]),vn(!1),Xe(null);const Me=L==="dm";Fe(N);const je=Le??N;if(Dt.set(je,[]),ve.current===N&&!Me&&(lt(!0),Vt([])),L==="dm"){const xe=qn(a?.id??"",rt),re=`opt_${Date.now()}`,Re={id:re,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};O&&(Re.replyToId=O.id,Re.replyToSender=O.sender,Re.replyToText=O.text),_e(N,le=>[...le,Re]);try{const le=await M.channels.sendMessage(xe,{text:x,senderName:a?.name??o("page.fallbackYou"),senderId:a?.id,mentions:[],orgId:"default",humanOnly:!0});le.userMessage&&Vs(le.userMessage.id),_e(N,we=>{const Se=we.filter(he=>he.id!==re),X=[];return le.userMessage&&X.push(Bs(le.userMessage,a?.id)),X.length>0?[...Se,...X]:we})}catch(le){rr(le)&&ar(),_e(N,we=>[...we,{id:`err_${Date.now()}`,sender:"agent",text:o("page.errorWithMessage",{message:String(le)}),time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}])}Ke(N),ve.current===N&<(!1)}else if(L==="channel"){const xe=`opt_${Date.now()}`,re={id:xe,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};O&&(re.replyToId=O.id,re.replyToSender=O.sender,re.replyToText=O.text),_e(N,we=>[...we,re]);const Re=Yi(x),le=pt.find(we=>we.channelKey===Ae);if(Ae.startsWith("group:")){const we=[];if(le?.members){for(const Se of le.members)if(Se.type==="agent"){const X=f.find(he=>he.id===Se.id);X&&we.push({id:X.id,name:X.name,avatarUrl:X.avatarUrl})}}we.length>0&&($t.current&&clearTimeout($t.current),fn(we),$t.current=setTimeout(()=>fn([]),12e4))}try{const we=await M.channels.sendMessage(Ae,{text:x,senderName:a?.name??o("page.fallbackYou"),mentions:Re,senderId:a?.id,orgId:"default",replyToId:O?.id});we.userMessage&&Vs(we.userMessage.id),we.agentMessage&&Vs(we.agentMessage.id),_e(N,Se=>{const X=Se.filter(te=>te.id!==xe),he=[];return we.userMessage&&he.push(Bs(we.userMessage,a?.id)),we.agentMessage&&he.push(Bs(we.agentMessage,a?.id)),he.length>0?[...X,...he]:Se})}catch(we){rr(we)&&ar();const Se=ir(we,o)||o("page.errorWithMessage",{message:String(we)});_e(N,X=>[...X,{id:`err_${Date.now()}`,sender:"agent",text:Se,time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}]),$t.current&&(clearTimeout($t.current),$t.current=null),fn([])}Ke(N),ve.current===N&<(!1)}else{W(N);const xe=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,re=`a_${xe}`,Re=`u_${xe}`;let le=Le===Ve?null:Le;if(c?.isResume){const G=new Date().toISOString();_e(N,Z=>[...Z,{id:re,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:G,segments:[]}],le)}else{const G=new Date().toISOString(),Z={id:Re,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:G};q?.length&&(Z.images=q),O&&(Z.replyToId=O.id,Z.replyToSender=O.sender,Z.replyToText=O.text),_e(N,ce=>[...ce,Z,{id:re,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:G,segments:[]}],le)}let we=!1;const Se=G=>{vs.current=Date.now(),rs(N,Z=>{const ce=[...Z],K=ce.findIndex(ds=>ds.id===re);if(K<0)return Z;const F=ce[K].segments??[],se=F[F.length-1],Ne=se?.type==="text"?se.thinking??"":"";let De="",Pe="",Ee=G;for(;Ee.length>0;)if(we){const ds=Ee.indexOf("</think>");ds>=0?(De+=Ee.slice(0,ds),Ee=Ee.slice(ds+8),we=!1):(De+=Ee,Ee="")}else{const ds=Ee.indexOf("<think>");ds>=0?(Pe+=Ee.slice(0,ds),Ee=Ee.slice(ds+7),we=!0):(Pe+=Ee,Ee="")}const Ze=Ne+De||void 0,wo=se?.type==="text"?[...F.slice(0,-1),{type:"text",content:se.content+Pe,thinking:Ze,createdAt:se.createdAt}]:[...F,{type:"text",content:Pe,thinking:Ze,createdAt:new Date().toISOString()}];return ce[K]={...ce[K],text:ce[K].text+Pe,segments:wo},ce},le)},X=G=>{if(vs.current=Date.now(),G.type==="session_start"&&G.sessionId){const Z=le;le=G.sessionId,Z&&Z!==G.sessionId&&ft(N,Z),tt(N,G.sessionId),Fn&&M.sessions.setModelOverride(G.sessionId,Fn).catch(()=>{}),G.userMessageId&&!c?.isResume&&_e(N,K=>K.map(F=>F.id===Re?{...F,id:G.userMessageId}:F),G.sessionId);const ce=xt.get(N);if(ce&&ce.length>0&&Es.set(G.sessionId,ce),ve.current===N){const K=Le;(!K||K===Ve||K===G.sessionId)&&(ls(G.sessionId),Pt.set(N,G.sessionId),J&&vr(J,G.sessionId),At(F=>F.some(se=>se.id===Ve)?F.map(se=>se.id===Ve?{...se,id:G.sessionId}:se):F.some(se=>se.id===G.sessionId)?F:[...F,{id:G.sessionId,agentId:J??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}_e(N,Z=>{const ce=[...Z],K=ce.findIndex(se=>se.id===re);if(K<0)return Z;const F=[...ce[K].committedSegments??[]];return G.type==="thinking_commit"?F.push({type:"text",content:"",thinking:G.content,createdAt:G.createdAt}):F.push({type:"text",content:G.content,createdAt:G.createdAt}),ce[K]={...ce[K],committedSegments:F},ce},le)},he=G=>{vs.current=Date.now(),G.phase!=="heartbeat"&&((G.phase==="start"||G.phase==="end")&&As(N,{...G,phase:G.phase,ts:Date.now()},le),G.phase==="start"?_e(N,Z=>{const ce=[...Z],K=ce.findIndex(Ee=>Ee.id===re);if(K<0)return Z;const F=[...ce[K].segments??[]];let se=!1;if(G.arguments)for(let Ee=F.length-1;Ee>=0;Ee--){const Ze=F[Ee];if(Ze.type==="tool"&&Ze.tool===G.tool&&Ze.status==="running"){F[Ee]={...Ze,args:G.arguments},se=!0;break}}const Ne=`${G.tool}_${Date.now()}`,De=new Date().toISOString();se||F.push({type:"tool",key:Ne,tool:G.tool,status:"running",args:G.arguments,createdAt:De});const Pe=[...ce[K].committedSegments??[]];return G.arguments!==void 0&&Pe.push({type:"tool",key:Ne,tool:G.tool,status:"running",args:G.arguments,createdAt:De}),ce[K]={...ce[K],segments:F,committedSegments:Pe},ce},le):G.phase==="output"?rs(N,Z=>{const ce=[...Z],K=ce.findIndex(se=>se.id===re);if(K<0)return Z;const F=[...ce[K].segments??[]];for(let se=F.length-1;se>=0;se--){const Ne=F[se];if(Ne.type==="tool"&&Ne.tool===G.tool&&Ne.status==="running"){F[se]={...Ne,liveOutput:Zo(Ne.liveOutput,G.output??"")};break}}return ce[K]={...ce[K],segments:F},ce},le):G.phase==="subagent_progress"&&G.subagentEvent?rs(N,Z=>{const ce=[...Z],K=ce.findIndex(De=>De.id===re);if(K<0)return Z;const F=De=>{const Pe=[...De];for(let Ee=Pe.length-1;Ee>=0;Ee--){const Ze=Pe[Ee];if(Ze.type==="tool"&&(Ze.tool==="spawn_subagent"||Ze.tool==="spawn_subagents")&&Ze.status==="running"){Pe[Ee]={...Ze,subagentLogs:Oa(Ze.subagentLogs,G.subagentEvent)};break}}return Pe},se=F(ce[K].segments??[]),Ne=F(ce[K].committedSegments??[]);return ce[K]={...ce[K],segments:se,committedSegments:Ne},ce},le):_e(N,Z=>{const ce=[...Z],K=ce.findIndex(Pe=>Pe.id===re);if(K<0)return Z;const F=new Date().toISOString(),se=[...ce[K].segments??[]];let Ne;for(let Pe=se.length-1;Pe>=0;Pe--){const Ee=se[Pe];if(Ee.type==="tool"&&Ee.tool===G.tool&&Ee.status==="running"){Ne=Ee.subagentLogs,se[Pe]={...Ee,status:G.success===!1?"error":"done",args:G.arguments,result:G.result,error:G.error,durationMs:G.durationMs,liveOutput:void 0,createdAt:F};break}}const De=[...ce[K].committedSegments??[]];for(let Pe=De.length-1;Pe>=0;Pe--){const Ee=De[Pe];if(Ee.type==="tool"&&Ee.tool===G.tool&&Ee.status==="running"){De[Pe]={...Ee,status:G.success===!1?"error":"done",args:G.arguments,result:G.result,error:G.error,durationMs:G.durationMs,liveOutput:void 0,createdAt:F,subagentLogs:Ne??Ee.subagentLogs};break}}return ce[K]={...ce[K],segments:se,committedSegments:De},ce},le))},te=new AbortController;bt.current=te;const ae=Le;ae&&tt(N,ae);try{vs.current=Date.now();const G=Le===Ve?null:Le,Z=await M.agents.messageStream(J,x,Se,he,te.signal,q,G,c?.isRetry,c?.isResume,X,Y,O,Fn);if(ve.current===N){Z.merged&&_e(N,K=>K.filter(F=>F.id!==re&&F.id!==Re),le),!Z.merged&&Z.segments?.length&&_e(N,K=>{const F=[...K],se=F.findIndex(Pe=>Pe.id===re);if(se<0)return K;const Ne=Fa(Z.segments,F[se].segments);let De=Z.content||F[se].text;return De||(De=Ne.filter(Pe=>Pe.type==="text").map(Pe=>Pe.content).join("")),F[se]={...F[se],text:De,segments:Ne,committedSegments:Ne},F},le),!Z.merged&&!Z.segments?.length&&_e(N,K=>{const F=[...K],se=F.findIndex(Ze=>Ze.id===re);if(se<0)return K;const Ne=F[se],De=Ne.committedSegments??[],Ee=De.filter(Ze=>Ze.type==="text"&&!!Ze.content).map(Ze=>Ze.content).join("")||Z.content||Ne.text;return(De.length>0||Ee)&&(F[se]={...Ne,text:Ee,segments:De.length>0?De:Ne.segments}),F},le),Z.sessionId&&(ls(K=>!K||K===Ve||K===Z.sessionId?Z.sessionId:K),At(K=>K.some(F=>F.id===Ve)?K.map(F=>F.id===Ve?{...F,id:Z.sessionId}:F):K.some(F=>F.id===Z.sessionId)?K:[...K,{id:Z.sessionId,agentId:J??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])),Xn(J).then(K=>{if(ve.current===N&&(qs(K),Z.sessionId)){const F=K.find(se=>se.id===Z.sessionId);F&&At(se=>se.some(De=>De.id===F.id)?se.map(De=>De.id===F.id?F:De):[F,...se.filter(De=>De.id!==Ve)])}});const ce=Z.sessionId??(ae&&ae!==Ve?ae:null);if(!te.signal.aborted&&!Z.merged&&Z.segments===void 0&&L==="direct"&&J&&ce)try{if((await M.sessions.streamStatus(J,ce)).status==="streaming"){_e(N,F=>F.map(se=>se.id===re?{...se,isStreaming:!0,isStopped:!1,segments:(se.segments??[]).map(Ne=>Ne.type==="tool"&&(Ne.status==="stopped"||Ne.status==="running")?{...Ne,status:"running"}:Ne)}:se),ce),Ke(N),bt.current===te&&(bt.current=null),tt(N,ce),Os(J,ce,N);return}}catch{}}}catch(G){const Z=G?.sessionId;Z&&L==="direct"&&ve.current===N&&(ls(Z),At(K=>K.map(F=>F.id===Ve?{...F,id:Z}:F)),Xn(J).then(K=>{if(ve.current!==N)return;qs(K);const F=K.find(se=>se.id===Z);F&&At(se=>se.some(De=>De.id===F.id)?se.map(De=>De.id===F.id?F:De):[F,...se])})),rr(G)&&ar();const ce=ir(G,o);ce?_e(N,K=>{const F=[...K],se=F.findIndex(Ne=>Ne.id===re);if(se>=0){const Ne=F[se].segments??[];F[se]={...F[se],text:ce,isError:!0,segments:[...Ne,{type:"text",content:ce}]}}return F},le):_e(N,K=>{const F=[...K],se=F.findIndex(Ne=>Ne.id===re);if(se>=0){const Ne=F[se];if(!(Ne.text||Ne.segments&&Ne.segments.length>0&&Ne.segments.some(Pe=>Pe.type==="text"&&(Pe.content||Pe.thinking)||Pe.type==="tool")))return K.filter(Pe=>Pe.id!==re);F[se]={...Ne,isStopped:!0}}return F},le)}_e(N,G=>{const Z=[...G],ce=Z.findIndex(K=>K.id===re);if(ce>=0){const K=(Z[ce].segments??[]).map(F=>F.type==="tool"&&F.status==="running"?{...F,status:"stopped"}:F);Z[ce]={...Z[ce],segments:K}}return Z},le),te.signal.aborted&&_e(N,G=>{const Z=[...G],ce=Z.findIndex(K=>K.id===re);if(ce>=0){const K=Z[ce];if(!(K.text||K.segments&&K.segments.length>0&&K.segments.some(se=>se.type==="text"&&(se.content||se.thinking)||se.type==="tool")))return G.filter(se=>se.id!==re);Z[ce]={...K,isStopped:!0}}return Z},le);const fe=(xt.get(N)??[]).find(G=>G.id===re),Te=Le&&Le!==Ve?Le:null,Qe=fe?.text||fe?.segments?.some(G=>G.type==="text"&&G.content||G.type==="tool");fe&&!Qe&&L==="direct"&&Te&&!te.signal.aborted&&await(async(Z,ce)=>{for(let K=0;K<Z;K++){await new Promise(F=>setTimeout(F,ce));try{const se=(await M.sessions.getMessages(Te,2)).messages.find(Ne=>Ne.role==="assistant");if(se?.content){const Ne=zr(se);_e(N,De=>{const Pe=[...De],Ee=Pe.findIndex(Ze=>Ze.id===re);return Ee>=0&&(Pe[Ee]={...Pe[Ee],text:Ne.text,segments:Ne.segments}),Pe},le);return}}catch{}}})(5,3e3);const Tt=Ke(N);le&&ft(N,le),U(N),bt.current===te||bt.current===null?(bt.current=null,Dt.delete(le??N),ve.current===N&&(lt(Tt>0),Tt===0&&Vt([]))):Dt.delete(le??N)}};ga.current=Zs;const[Qi,ka]=n.useState(null),[Zn,_r]=n.useState(null),Zi=n.useMemo(()=>{for(let t=Ge.length-1;t>=0;t--)if(Ge[t]?.sender==="agent"&&!Ge[t]?.isActivityLog)return Ge[t].id;return null},[Ge]),Ji=n.useCallback(t=>{const c=t.segments?t.segments.filter(d=>d.type==="text").map(d=>d.content).join(`
|
|
39
|
-
`):t.text;navigator.clipboard.writeText(c),ka(t.id),setTimeout(()=>ka(d=>d===t.id?null:d),2e3)},[]),Ir=n.useCallback((t,c,d)=>{const x=ve.current,P=xt.get(x)??Ge,z=P.findIndex(Y=>Y.id===t.id);if(z<0)return;const q=c&&z>0&&P[z-1]?.id===c.id;_e(x,Y=>{const N=Y.findIndex(O=>O.id===(q?c.id:t.id));return N>=0?Y.slice(0,N):Y}),Zs(d,{isRetry:!0})},[Ge,_e]),eo=n.useCallback(t=>{const c=ve.current,d=xt.get(c)??Ge,x=d.findIndex(Y=>Y.id===t.id);if(x<0)return;let P=null;for(let Y=x-1;Y>=0;Y--)if(d[Y]?.sender==="user"){P=d[Y];break}const z=P?.text??"";if(!z)return;if(x<d.length-1){const Y=d.length-1-x;_r({retryMsg:t,userMsg:P,retryText:z,followCount:Y});return}Ir(t,P,z)},[Ge,Ir]),to=n.useCallback(t=>{const c=ve.current;(xt.get(c)??Ge).findIndex(P=>P.id===t.id)<0||(_e(c,P=>{const z=[...P],q=z.findIndex(O=>O.id===t.id);if(q<0)return P;const Y=z[q],N=[...Y.segments??[]];for(;N.length>0;){const O=N[N.length-1];if(O.type==="tool"&&(O.status==="stopped"||O.status==="running"))N.pop();else if(O.type==="text"&&!O.content)N.pop();else break}return z[q]={...Y,segments:N,isStopped:!1,isError:!1},z}),Zs("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0}))},[Ge,_e]),so=n.useCallback(t=>{const c=t.sender==="user"?a?.name??o("page.fallbackYou"):t.agentName??o("page.fallbackAgent");if(Xe({id:t.id,sender:c,text:t.text}),L==="channel"&&t.sender==="agent"&&t.agentName){const d=`@${t.agentName} `;Et(x=>x.startsWith(d)?x:d+x)}os.current?.focus()},[a?.name,L,o]),Jn=async t=>{const c=Le;ls(t.id),Ls(!1),as(!1),Jt.current=null,ts.current=!0,Ds(!1),$s.current=0,Ys(0);const d=ve.current,x=ct(d),P=!!x&&(x.has(t.id)||x.has(Ve)),z=Ie(d)&&P;lt(z),Vt(z?Dt.get(t.id)??[]:[]),Pt.set(d,t.id),J&&vr(J,t.id),c&&c!==Ve&&qt(d,c),it(d,t.id),At(Y=>Y.some(N=>N.id===t.id)?Y:[...Y,t]),J&&Pi(J,t.id),await Er(t.id,d);const q=t.metadata?.modelOverride;Bn(q?.provider&&q?.model?{provider:q.provider,model:q.model}:null),J&&!z&&Os(J,t.id,d)},no=t=>{if(At(c=>c.filter(d=>d.id!==t)),J&&t!==Ve&&Mi(J,t),Le===t){const c=zn.filter(d=>d.id!==t);c.length>0?Jn(c[c.length-1]):Lr()}},Na=n.useCallback(async t=>{if(t.length<2){ws([]);return}ca(!0);try{const c=L==="channel"?"channel":L==="direct"?"direct":"all",d=L==="channel"?Ae:void 0,{results:x}=await M.messages.search(t,{scope:c,channel:d,limit:30});ws(x)}catch{ws([])}ca(!1)},[L,Ae]),ro=n.useCallback(t=>{Us(t),Cr.current&&clearTimeout(Cr.current),Cr.current=setTimeout(()=>Na(t),300)},[Na]),ao=n.useCallback(t=>{yn(!1),Us(""),ws([]),t.source==="channel"&&t.channel?(Oe("channel"),kt(t.channel)):t.source==="direct"&&t.agentId&&(Oe("direct"),ot(t.agentId)),setTimeout(()=>{const c=document.getElementById(`msg-${t.id}`);c&&(c.scrollIntoView({behavior:"smooth",block:"center"}),c.classList.add("bg-brand-500/10"),setTimeout(()=>c.classList.remove("bg-brand-500/10"),2e3))},500)},[]),Lr=()=>{ls(Ve);const t=ve.current;me(t),St([]),as(!1),Jt.current=null,Ls(!1),At(c=>{const d=c.filter(x=>x.id!==Ve);return[{id:Ve,agentId:J??"",userId:null,title:o("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...d]})},io=t=>{Et(t);const c=os.current?.selectionStart??t.length,d=t.slice(0,c),x=d.lastIndexOf("@");if(x>=0){const P=x===0?"":d[x-1];if(x===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(P)){const q=d.slice(x+1);if(!q.includes(" ")&&!q.includes(`
|
|
40
|
-
`)){Bi(),vn(!0),$i(q.toLowerCase()),Gs(0);return}}}vn(!1)},er=(t,c,d)=>{const x=os.current?.selectionStart??st.length,z=st.slice(0,x).lastIndexOf("@"),q=st.slice(x),Y=c&&d?`@[${t}](${c}:${d})`:t.includes(" ")?`@[${t}]`:`@${t}`,N=st.slice(0,z)+Y+" "+q;Et(N),vn(!1),Gs(0);const O=z+Y.length+1;requestAnimationFrame(()=>{os.current?.setSelectionRange(O,O)})},oo=10*1024*1024,Sa=5,lo=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),Js=n.useCallback(t=>t.type.startsWith("image/")||lo.has(t.type),[]),Rr=t=>t.dataUrl.startsWith("data:image/"),co=(t,c)=>{if(Rr({dataUrl:c}))return null;const d=t.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[d]??"📁"},Cn=n.useCallback(t=>{const c=Array.from(t).filter(Js);if(c.length!==0)for(const d of c){if(d.size>oo)continue;const x=new FileReader;x.onload=()=>{const P=x.result;hr(z=>z.length>=Sa||z.some(q=>q.dataUrl===P)?z:[...z,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:P,name:d.name}])},x.readAsDataURL(d)}},[Js]),uo=n.useCallback(t=>{hr(c=>c.filter(d=>d.id!==t))},[]),mo=n.useCallback(t=>{const c=t.clipboardData?.files;if(c&&c.length>0){const d=Array.from(c).filter(Js);d.length>0&&(t.preventDefault(),Cn(d))}},[Cn,Js]),xo=n.useCallback(t=>{t.preventDefault();const c=t.dataTransfer?.files;c&&c.length>0&&Cn(Array.from(c).filter(Js))},[Cn,Js]),fo=n.useCallback(t=>{t.preventDefault()},[]),et=f.find(t=>t.id===J),Dr=a?.name??o("page.fallbackYou"),Ca=ht[ht.length-1],go=Ct&&Ca?.sender==="agent",ho=xr&&Ca?.sender==="agent",Ta=n.useMemo(()=>{if(L!=="channel")return null;if(Ae.startsWith("group:custom:")){const c=pt.find(d=>d.channelKey===Ae);return c?.members?new Set(c.members.filter(d=>d.type==="agent").map(d=>d.id)):null}if(!nt)return null;const t=es.find(c=>c.id===nt);return t?new Set(t.members.filter(c=>c.type==="agent").map(c=>c.id)):null},[L,Ae,nt,es,pt]),Ma=f.filter(t=>Ta?Ta.has(t.id):!0).filter(t=>t.name.toLowerCase().includes(xa)),Pa=Oi.filter(t=>t.name.toLowerCase().includes(xa)),po={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},Fs=n.useMemo(()=>[...Ma.map(t=>({kind:"agent",agent:t})),...Pa.map(t=>({kind:"entity",entity:t}))],[Ma,Pa]),$r=w.find(t=>t.id===rt),Or=rt===a?.id||!rt,Ft=pt.find(t=>t.channelKey===Ae);n.useEffect(()=>{if(s||!Ae.startsWith("group:custom:"))return;const t=pt.find(c=>c.channelKey===Ae);!t||t.members||M.groupChats.getById(t.id).then(c=>{c.chat.members&&pn(d=>d.map(x=>x.id===t.id?{...x,members:c.chat.members}:x))}).catch(()=>{})},[s,Ae,pt]);const Fr=n.useCallback(async()=>{if(s||L!=="direct"||!J){jr([]);return}try{Oo("/approvals");const{approvals:t}=await M.approvals.list("pending");jr(t.filter(c=>c.status==="pending"&&Array.isArray(c.questions)&&c.questions.length>0&&(c.details?.agentId??c.agentId)===J))}catch{}},[s,L,J]);n.useEffect(()=>{Fr();let t=null;const c=()=>{t||(t=setTimeout(()=>{t=null,Fr()},400))},d=We.on("approval:requested",c),x=We.on("notification",c),P=()=>c();return window.addEventListener("markus:notifications-changed",P),()=>{t&&clearTimeout(t),d(),x(),window.removeEventListener("markus:notifications-changed",P)}},[Fr]);const bo=n.useCallback(async(t,c)=>{aa(t);try{await M.approvals.respond(t,c.approved,a?.id,c.comment,c.selectedOption,c.answers),jr(d=>d.filter(x=>x.id!==t)),wr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}aa(null)},[a?.id]),Ea=L==="channel"?Ft?.name??Ae:L==="direct"?et?.name??o("page.selectAgent"):L==="dm"?Or?o("chat.myNotes"):$r?.name??o("page.directMessage"):o("page.chatTitle"),yo=n.useMemo(()=>Math.floor(Math.random()*5),[J,Le]),Aa=J?o(`page.placeholder.directOptions.${yo}`):"",Tn=L==="direct"&&!!et&&et.status==="offline",vo=L==="channel"?Ft?o("page.placeholder.channel",{name:Ft.name}):o("page.placeholder.channelWithMention",{name:Ae}):L==="dm"?Or?o("page.placeholder.dmSelf"):o("page.placeholder.dmOther",{name:$r?.name??""}):o(Tn?"page.placeholder.agentOffline":J?"page.placeholder.direct":"page.placeholder.noAgent"),jo=v&&p==="chat",Mn=k==="chat"&&ht.length===0&&!Ct&&!sa,Bt=k==="chat"&&ht.length>0;return br.current=Bt,e.jsxs("div",{ref:ie,className:"flex-1 overflow-hidden flex relative",children:[!g&&e.jsx(hl,{authUser:a,agents:f,teams:es,humans:w,tasks:Hn,externalAgents:Ii,groupChats:pt,chatMode:L,selectedAgent:J,activeChannel:Ae,activeDmUserId:rt,previewMode:s,onSelectAgent:t=>{Oe("direct"),ot(t),_("chat"),gt(!1),v&&B()},onSelectChannel:t=>{Oe("channel"),kt(t),_("chat"),gt(!1),v&&B()},onSelectDm:t=>{Oe("dm"),Ms(t),_("chat"),gt(!1),v&&B()},onSelectTeam:t=>{const c=pt.find(x=>x.type==="team"&&x.teamId===t),d=c?.channelKey??`group:${t}`;v?R(t):(Oe("channel"),kt(d),_("chat"),gt(!1),!Kt&&!He&&vt(!0),c||(Ks(),_t()))},selectedTeamId:nt??(L==="direct"&&et?.teamId?et.teamId:null),onRefreshTeams:_t,onRefreshAgents:Ot,onRefreshHumans:Sn,onRefreshGroupChats:Ks,onViewProfile:wt,onManageGroupMembers:t=>{Oe("channel"),kt(t),_("chat"),gt(!0),v&&B()},unreadByAgent:Gn,unreadByChannel:Un,width:v?void 0:$e.width,onResizeStart:v?void 0:$e.onResizeStart,hidden:v&&p!=="roster"||!v&&ne,onCollapse:()=>Ce(!0),initialLoading:A}),v&&p==="team"&&S&&(()=>{const t=es.find(x=>x.id===S);if(!t)return null;const c=f.filter(x=>x.teamId===S),d=pt.find(x=>x.type==="team"&&x.teamId===S);return e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[e.jsx("button",{onClick:()=>{window.location.hash=ut.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:t.name}),e.jsx("p",{className:"text-[10px] text-fg-tertiary",children:o("chat.members_other",{count:t.members?.length||c.length})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[d&&(()=>{const x=Un[d.channelKey]??0;return e.jsxs("button",{onClick:()=>{Oe("channel"),kt(d.channelKey),_("chat"),B()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:d.name}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("chat.groupChat")})]}),x>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:x}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),c.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:o("chat.agents")}),c.map(x=>{const P=Gn.get(x.id)??0,z=x.status==="offline";return e.jsxs("button",{onClick:()=>{Oe("direct"),ot(x.id),_("chat"),B()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${z?"opacity-50":""}`,children:[e.jsx(yt,{name:x.name||"Agent",avatarUrl:x.avatarUrl,size:36}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"text-sm font-medium text-fg-primary truncate flex items-center gap-1.5",children:[x.name,z&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:o("common:status.offline")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:x.role||x.status})]}),P>0?e.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:P}):e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${x.status==="idle"?"bg-green-500":x.status==="working"?"bg-blue-500":"bg-gray-400"}`})]},x.id)})]})]})]})})(),!g&&Kt&&!He&&!v&&!ne&&(()=>{const t=nt??(L==="direct"?et?.teamId:void 0);if(!t)return null;const c=es.find(x=>x.id===t);if(!c)return null;const d=pt.find(x=>x.type==="team"&&x.teamId===t);return e.jsx(Ua,{team:c,agents:f,humans:w,authUser:a,groupChat:d,chatMode:L,selectedAgent:J,activeChannel:Ae,teams:es,onSelectAgent:x=>{Oe("direct"),ot(x),_("chat"),gt(!1)},onSelectChannel:x=>{Oe("channel"),kt(x),_("chat"),gt(!1)},onSelectDm:x=>{Oe("dm"),Ms(x),_("chat"),gt(!1)},onBack:()=>vt(!1),onViewProfile:wt,onRefreshAgents:Ot,onRefreshTeams:_t,unreadByAgent:Gn,width:mt.width,onResizeStart:mt.onResizeStart})})(),!g&&Be&&!v&&!ne&&(()=>{const t=nt??(L==="direct"?et?.teamId:void 0);if(!t)return null;const c=es.find(x=>x.id===t);if(!c)return null;const d=pt.find(x=>x.type==="team"&&x.teamId===t);return e.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:$e.width+6},children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>jt(!1)}),e.jsx("div",{className:"relative h-full",style:{width:mt.width+8},children:e.jsx(Ua,{team:c,agents:f,humans:w,authUser:a,groupChat:d,chatMode:L,selectedAgent:J,activeChannel:Ae,teams:es,onSelectAgent:x=>{Oe("direct"),ot(x),_("chat"),gt(!1),jt(!1)},onSelectChannel:x=>{Oe("channel"),kt(x),_("chat"),gt(!1),jt(!1)},onSelectDm:x=>{Oe("dm"),Ms(x),_("chat"),gt(!1),jt(!1)},onBack:()=>jt(!1),onViewProfile:x=>{wt(x),jt(!1)},onRefreshAgents:Ot,onRefreshTeams:_t,unreadByAgent:Gn,width:mt.width})})]})})(),!g&&(!v||jo)&&e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v||Q?"min-w-0":"min-w-[400px]"}`,children:[e.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[e.jsx("button",{onClick:()=>{window.location.hash=E.current},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("span",{className:"font-semibold text-sm truncate min-w-0 flex-1",children:Ea}),L==="direct"&&et&&e.jsx(gi,{agent:et,tasks:Hn,onViewProfile:wt,streamActive:Jr})]}),e.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[e.jsx("button",{onClick:()=>{us(k)?history.back():_("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${k==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o("page.chatTitle")}),e.jsx("button",{onClick:()=>{us(k)||bs()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${us(k)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o(L==="channel"?"page.teamTab":"page.profileTab")}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:()=>{yn(!Rs),Rs||(Us(""),ws([]))},className:`p-1 rounded-md transition-colors shrink-0 ${Rs?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),L==="channel"&&Ft?.type==="custom"&&e.jsxs("button",{onClick:()=>gt(!bn),className:`text-[11px] px-2 py-1 rounded-md font-medium shrink-0 flex items-center gap-1 ${bn?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ft.members?.length??Ft.memberCount??0]}),L==="direct"&&!us(k)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Lr,className:"text-[11px] text-brand-500 px-2 py-1 rounded-md bg-brand-500/10 font-medium shrink-0",children:o("page.newChatPlus")}),e.jsx("button",{ref:Wn,onClick:()=>Ls(!Is),className:`p-1 rounded-md transition-colors shrink-0 ${Is?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}):(()=>{const t=nt?es.find(O=>O.id===nt):void 0,c=L==="direct"&&J?Gl:L==="channel"&&nt?Kl:["chat"],d=async()=>{const O=Rn.trim();if(!O){Wt(!1);return}try{L==="direct"&&J?(await M.agents.updateConfig(J,{name:O}),Ot()):L==="channel"&&nt&&(await M.teams.update(nt,{name:O}),_t())}catch{}Wt(!1)},x=async()=>{try{L==="direct"&&J?(await M.agents.updateConfig(J,{roleDescription:Qt}),Ot()):L==="channel"&&nt&&(await M.teams.update(nt,{description:Qt}),_t())}catch{}un(!1)},P=L==="direct"?et?.name:L==="channel"?t?.name??Ft?.name:$r?.name??"",z=L==="direct"?et?.role||"":L==="channel"&&t?.description||"",q=L==="direct"?et?.avatarUrl:void 0,Y=P||"U",N=L==="direct"&&J||L==="channel"&&nt;return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center px-4 h-14 gap-2.5",children:[ne&&!v&&e.jsx("button",{onClick:()=>Ce(!1),className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",title:o("page.toggleSidebar"),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),(!Kt||He)&&(L==="channel"&&nt||L==="direct"&&et?.teamId)&&e.jsx("button",{onClick:nn,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${Be?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),N&&(L==="channel"&&nt?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):e.jsx(yt,{name:Y,avatarUrl:q,size:36,className:"rounded-xl shrink-0"})),N?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[It?e.jsx("input",{ref:Hs,value:Rn,onChange:O=>dn(O.target.value),onBlur:d,onKeyDown:O=>{O.key==="Enter"&&d(),O.key==="Escape"&&Wt(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):e.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{dn(P??""),Wt(!0)},title:"Click to edit name",children:P}),L==="direct"&&et&&e.jsx(gi,{agent:et,tasks:Hn,onViewProfile:wt,streamActive:Jr})]}),(L==="direct"||L==="channel"&&nt)&&(Ws?e.jsx("input",{ref:Lt,value:Qt,onChange:O=>Cs(O.target.value),onBlur:x,onKeyDown:O=>{O.key==="Enter"&&x(),O.key==="Escape"&&un(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add description...",autoFocus:!0}):e.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{Cs(z),un(!0)},title:"Click to edit description",children:z||"No description"}))]}):e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:Ea}),L==="dm"&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:Or?o("page.privateNotepad"):""})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>{yn(!Rs),Rs||(Us(""),ws([]))},className:`p-1.5 rounded-md transition-colors ${Rs?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.searchMessages"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),L==="channel"&&Ft?.type==="custom"&&e.jsxs("button",{onClick:()=>gt(!bn),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${bn?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ft.members?.length??Ft.memberCount??0]}),L==="direct"&&et&&k==="chat"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:Lr,className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:o("page.newChatButton")}),e.jsx("button",{ref:Wn,onClick:()=>Ls(!Is),className:`p-1.5 rounded-md transition-colors ${Is?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),!v&&de&&e.jsx("button",{onClick:()=>de.toggleRightPanel(),className:`p-1.5 rounded-md transition-colors ${Q?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.rightPanelToggle",{defaultValue:"Toggle side panel"}),children:e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),e.jsx("path",{d:"M15 4v16"})]})})]})]}),c.length>1&&e.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:c.map(O=>e.jsxs("button",{onClick:()=>_(O),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${k===O?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{children:Xl(O)}),Yl(O,o)]},O))})]})})(),Rs&&e.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/50 px-4 py-2 space-y-2 animate-in slide-in-from-top-2 duration-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),e.jsx("input",{autoFocus:!0,value:oa,onChange:t=>ro(t.target.value),onKeyDown:t=>{t.key==="Escape"&&(yn(!1),Us(""),ws([]))},placeholder:o("page.searchPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),e.jsx("button",{onClick:()=>{yn(!1),Us(""),ws([])},className:"text-fg-tertiary hover:text-fg-secondary text-xs px-1",children:"✕"})]}),la&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary py-1",children:[e.jsxs("svg",{className:"animate-spin h-3 w-3",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),o("page.searching")]}),!la&&oa.length>=2&&Sr.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:o("page.noSearchResults")}),Sr.length>0&&e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:Sr.map(t=>e.jsxs("button",{onClick:()=>ao(t),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-surface-elevated transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-tertiary mb-0.5",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${t.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:t.source==="channel"?"#":"1:1"}),t.senderName&&e.jsx("span",{children:t.senderName}),e.jsx("span",{children:new Date(t.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),e.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 group-hover:text-fg-primary transition-colors",children:t.text.length>200?t.text.slice(0,200)+"…":t.text})]},t.id))})]}),L==="direct"&&J&&k==="chat"&&zn.length>1&&e.jsx("div",{className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:zn.map(t=>e.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${t.id===Le?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(t.id===Ve){ls(Ve);const c=ve.current;me(c),St([])}else Jn(t)},children:[t.isMain&&e.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),e.jsx("span",{className:"truncate",children:t.id===Ve?o("page.newChat"):t.isMain?o("page.sessionMain"):t.title||o("page.sessionConversation")}),!t.isMain&&e.jsx("button",{onClick:c=>{c.stopPropagation(),no(t.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},t.id))}),L==="channel"&&Ft?.type==="custom"&&bn&&(()=>{const t=Ft,c=t.members??[],d=[];for(const x of f)c.some(P=>P.id===x.id)||d.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of w)c.some(P=>P.id===x.id)||d.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||""});return e.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",c.length,")"]}),e.jsx("button",{onClick:()=>gt(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(x=>e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${x.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[e.jsx(yt,{name:x.name,size:16,bgClass:x.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),x.name,x.id!==a?.id&&e.jsx("button",{onClick:async()=>{try{await M.groupChats.removeMember(t.id,x.id),pn(P=>P.map(z=>z.id===t.id?{...z,members:(z.members??[]).filter(q=>q.id!==x.id),memberCount:(z.memberCount??1)-1}:z))}catch{}},className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},x.id))}),d.length>0&&e.jsx("div",{className:"mt-1",children:e.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:async x=>{const P=x.target.value;if(!P)return;const z=d.find(q=>q.id===P);if(z)try{await M.groupChats.addMember(t.id,z.id,z.type,z.name),pn(q=>q.map(Y=>Y.id===t.id?{...Y,members:[...Y.members??[],{id:z.id,name:z.name,type:z.type}],memberCount:(Y.memberCount??0)+1}:Y))}catch{}},children:[e.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),d.map(x=>e.jsxs("option",{value:x.id,children:["[",x.type==="agent"?"Agent":"Human","] ",x.name]},x.id))]})})]})})(),L==="direct"&&J&&Is&&e.jsxs("div",{ref:kr,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:o("page.historyTitle")}),e.jsx("button",{onClick:()=>Ls(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[na.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:o("page.noConversationsYet")}),(()=>{const t=new Date,c=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),d=c-864e5,x=c-7*864e5,P=[],z=[],q=[],Y=[],N=[];for(const O of na){const Me=new Date(O.lastMessageAt).getTime();Me>=c?z.push(O):Me>=d?q.push(O):Me>=x?Y.push(O):N.push(O)}return z.length>0&&P.push({label:o("page.dateToday"),items:z}),q.length>0&&P.push({label:o("page.dateYesterday"),items:q}),Y.length>0&&P.push({label:o("page.datePrevious7Days"),items:Y}),N.length>0&&P.push({label:o("page.dateOlder"),items:N}),P.map(O=>e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:O.label}),O.items.map(Me=>e.jsxs("button",{onClick:()=>{Jn(Me)},className:`w-full text-left px-3 py-2.5 rounded-lg text-xs mb-0.5 transition-colors ${Me.id===Le?"bg-brand-600/20 text-brand-500":"text-fg-secondary hover:bg-surface-elevated"}`,children:[e.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[Me.isMain&&e.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),Me.isMain?o("page.sessionMain"):Me.title||o("page.sessionConversation")]}),e.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(Me.lastMessageAt).toLocaleString()})]},Me.id))]},O.label))})()]})]})]}),v&&k==="profile"&&L==="direct"&&J&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Ka,{agentId:J,onBack:()=>_("chat"),inline:!0,defaultTab:Ln,highlightMailboxId:cn,onSwipeBack:()=>{us(pe.current)?history.back():_("chat")},authUser:a})}),v&&k==="profile"&&L==="channel"&&nt&&e.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:v?Rt.onTouchStart:void 0,onTouchEnd:v?Rt.onTouchEnd:void 0,children:e.jsx(mi,{teamId:nt,onBack:()=>_("chat"),inline:!0,onSelectAgent:t=>{Oe("direct"),ot(t),_("chat")}})}),!v&&us(k)&&L==="direct"&&J&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Ka,{agentId:J,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:k,highlightMailboxId:cn,authUser:a})}),!v&&us(k)&&L==="channel"&&nt&&e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:e.jsx(mi,{teamId:nt,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:k,onSelectAgent:t=>{Oe("direct"),ot(t),_("chat")}})}),e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${Mn?"justify-center":""} ${k!=="chat"?"hidden":""}`,children:[sa&&ht.length===0&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3",children:[e.jsxs("svg",{className:"animate-spin h-6 w-6 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e.jsx("span",{className:"text-xs text-fg-tertiary animate-pulse",children:o("page.loadingChat",{defaultValue:"Loading conversation…"})})]}),gr&&e.jsxs("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center items-center gap-2 py-2 bg-gradient-to-b from-surface-primary/90 to-transparent pointer-events-none",children:[e.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.loadingEarlierMessages")})]}),e.jsxs("div",{ref:wn,className:`${Mn?"hidden":"flex-1"} overflow-y-auto ${v?"p-2.5":`p-5 ${V}`}`,onScroll:Ki,onTouchStart:v?Rt.onTouchStart:void 0,onTouchEnd:v?Rt.onTouchEnd:void 0,children:[ht.length>0&&e.jsx("div",{style:{height:cs.getTotalSize(),width:"100%",position:"relative"},children:cs.getVirtualItems().map(t=>{const c=t.index,d=ht[c],x=c>0?ht[c-1]:null,P=Ba(d.rawCreatedAt),z=x?Ba(x.rawCreatedAt):"",q=!!(P&&z&&P!==z),Y=c===ht.length-1,O=go&&Y&&Ct||!!d.isStreaming,Me=ho&&Y||O,je=L==="channel"||!O||d.isStopped;return e.jsx("div",{"data-index":c,ref:cs.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${t.start}px)`},children:e.jsxs("div",{className:"pb-3",children:[q&&e.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[e.jsx("div",{className:"flex-1 h-px bg-border-default"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:Xo(d.rawCreatedAt,u)}),e.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),e.jsxs("div",{id:`msg-${d.id}`,className:"group/msg flex gap-3 transition-colors rounded-lg",children:[L==="channel"?e.jsx("div",{className:"shrink-0 cursor-pointer",onClick:xe=>{if(d.sender==="agent"&&d.agentId){const re=xe.currentTarget.getBoundingClientRect();ns({agentId:d.agentId,top:re.top,left:re.right+8})}},children:e.jsx(yt,{name:d.sender==="user"?Dr:d.agentName??o("page.fallbackAgent"),avatarUrl:d.sender==="user"?a?.avatarUrl:f.find(xe=>xe.id===d.agentId)?.avatarUrl,size:32,bgClass:d.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:d.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):e.jsx("div",{className:"shrink-0",children:e.jsx(yt,{name:d.sender==="user"?Dr:d.agentName??(L==="direct"?et?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),avatarUrl:d.sender==="user"?a?.avatarUrl:f.find(xe=>xe.id===(d.agentId??(L==="direct"?et?.id:void 0)))?.avatarUrl,size:32,bgClass:d.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:d.sender==="user"?Dr:L==="channel"?d.agentName??o("page.fallbackAgent"):e.jsx(Fo,{name:d.agentName??(L==="direct"?et?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),agentId:d.agentId??(L==="direct"?et?.id:void 0),agents:f,onViewProfile:wt})}),e.jsx("span",{className:"text-xs text-fg-tertiary",title:d.rawCreatedAt?new Date(d.rawCreatedAt).toLocaleString():"",children:Qo(d.time,d.rawCreatedAt,u)})]}),d.replyToId&&d.replyToSender&&e.jsxs("button",{onClick:()=>{const xe=document.getElementById(`msg-${d.replyToId}`);xe&&(xe.scrollIntoView({behavior:"smooth",block:"center"}),xe.classList.add("bg-brand-500/10"),setTimeout(()=>xe.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[e.jsx("span",{className:"font-medium text-brand-500",children:d.replyToSender}),e.jsx("span",{className:"truncate max-w-[250px]",children:d.replyToText??"..."})]}),e.jsxs("div",{className:`mt-0.5 ${d.sender==="agent"?"py-1":"bg-surface-secondary rounded-2xl px-3.5 py-2.5 w-fit max-w-full"} ${Me&&d.sender==="agent"?"streaming-bubble":""}`,children:[d.sender==="user"?e.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[d.images&&d.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:d.images.map((xe,re)=>e.jsx("img",{src:xe,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(xe,"_blank")},re))}),L==="channel"?Da(d.text,f,(xe,re)=>{const Re=re.currentTarget.getBoundingClientRect();ns({agentId:xe.id,top:Re.bottom,left:Re.left})}):d.text&&e.jsx("span",{className:"leading-relaxed",children:Da(d.text,f,(xe,re)=>{const Re=re.currentTarget.getBoundingClientRect();ns({agentId:xe.id,top:Re.bottom,left:Re.left})})})]}):d.sender==="agent"&&L==="channel"&&!(d.segments&&d.segments.length>0)?e.jsx(Ra,{resetKeys:[d.text],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:d.text}),children:e.jsx(or,{content:d.text,className:"text-sm text-fg-secondary",onMentionClick:Ht,knownNames:xn})}):e.jsx(Ra,{resetKeys:[d.id,d.text,d.segments?.length,O],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:d.text}),children:e.jsx(Bo,{msg:d,isStreaming:O,liveActivities:O?ur:[],onMentionClick:Ht,knownNames:xn})}),d.isNotification&&e.jsx(zo,{priority:d.notifyPriority})]}),je&&!s&&e.jsx("div",{className:`transition-opacity ${d.isStopped||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:e.jsx(Wo,{msg:d,onCopy:Ji,onRetry:eo,onResume:to,onReply:so,isCopied:Qi===d.id,isLastAgentMsg:d.id===Zi})})]})]})]})},d.id)})}),L==="channel"&&Zr.length>0&&e.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:Zr.map(t=>e.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors group/think",onClick:()=>{Oe("direct"),ot(t.id),_("chat")},children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(yt,{name:t.name,avatarUrl:t.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-600"}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-secondary truncate",children:t.name}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.agentThinking")})]}),e.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary opacity-0 group-hover/think:opacity-100 transition-opacity",children:"→"})]},t.id))}),e.jsx("div",{ref:zi})]}),Ui&&k==="chat"&&e.jsx("div",{className:`absolute ${v?"bottom-4":"bottom-28"} inset-x-0 z-10 pointer-events-none ${v?"px-3":`px-5 ${V}`}`,children:e.jsx("div",{className:`${v?"":"max-w-3xl mx-auto"} flex justify-center`,children:e.jsxs("button",{onClick:()=>{ts.current=!0,Qs("smooth"),Ds(!1),$s.current=0,Ys(0)},className:"pointer-events-auto flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/95 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary",children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})}),pa>0?o("page.newMessages",{count:pa}):o("page.scrollToBottom")]})})}),Ns&&(()=>{const t=f.find(c=>c.id===Ns.agentId);return t?e.jsx(Ho,{agent:t,anchorRect:{top:Ns.top,left:Ns.left},onClose:()=>ns(null),onViewProfile:wt}):null})(),Mn&&Aa&&e.jsx("div",{className:"text-center mb-4",children:e.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:Aa})}),L==="direct"&&ra.length>0&&e.jsx("div",{className:`${v?"px-3":"px-5"} pb-1 shrink-0 ${Mn?"":V}`,children:e.jsx("div",{className:`${v?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:ra.map(t=>e.jsxs("button",{onClick:()=>wr(t),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[e.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"}),e.jsx("path",{d:"M12 8v4"}),e.jsx("path",{d:"M12 16h.01"})]})}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-fg-primary truncate",children:t.title}),e.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:o("page.userInputPrompt",{count:t.questions?.length??1,defaultValue:`${t.questions?.length??1} question(s) awaiting your response`})})]}),e.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[o("page.userInputRespond",{defaultValue:"Respond"}),e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},t.id))})}),hn&&e.jsx(Vo,{approval:hn,submitting:Ai===hn.id,readOnly:hn.status!=="pending",onClose:()=>wr(null),onSubmit:t=>bo(hn.id,t)}),Zn&&e.jsx(An,{variant:"primary",title:o("page.retry",{defaultValue:"Retry"}),message:Zn.followCount===1?o("page.retryConfirmSingular"):o("page.retryConfirmPlural",{count:Zn.followCount}),confirmLabel:o("common:confirm"),onConfirm:()=>{const t=Zn;_r(null),Ir(t.retryMsg,t.userMsg,t.retryText)},onCancel:()=>_r(null)}),e.jsx("div",{className:`${v?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${Mn?"":V}`,onDrop:xo,onDragOver:fo,children:e.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${v?`${Bt?"rounded-2xl p-2":"rounded-2xl p-3"}`:`${Bt?"rounded-2xl p-2":"rounded-2xl p-3"} max-w-3xl mx-auto`}`,children:[ma&&Fs.length>0&&e.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:o("page.mentionAgent")}),Fs.map((t,c)=>t.kind==="agent"?e.jsxs("button",{ref:d=>{c===jn&&d&&d.scrollIntoView({block:"nearest"})},onClick:()=>er(t.agent.name),onMouseEnter:()=>Gs(c),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${c===jn?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx(yt,{name:t.agent.name,avatarUrl:t.agent.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.agent.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.agent.role})]},`agt-${t.agent.id}`):e.jsxs("button",{ref:d=>{c===jn&&d&&d.scrollIntoView({block:"nearest"})},onClick:()=>er(t.entity.name,t.entity.entityType,t.entity.id),onMouseEnter:()=>Gs(c),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${c===jn?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("span",{className:"w-6 h-6 flex items-center justify-center text-sm shrink-0",children:po[t.entity.entityType]??"📄"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.entity.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.entity.role})]},`${t.entity.entityType}-${t.entity.id}`))]}),Zt.length>0&&e.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:Zt.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 max-w-[240px] pl-2 pr-1 py-1 rounded-lg bg-brand-500/10 text-brand-500 text-xs border border-brand-500/20",title:t.content,children:[e.jsx("span",{className:"truncate",children:t.label}),e.jsx("button",{onClick:()=>mr(c=>c.filter(d=>d.id!==t.id)),className:"w-4 h-4 flex items-center justify-center rounded hover:bg-brand-500/20 shrink-0","aria-label":o("common:remove",{defaultValue:"Remove"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},t.id))}),Ut.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Ut.map(t=>e.jsxs("div",{className:"relative group/img shrink-0",children:[Rr(t)?e.jsx("img",{src:t.dataUrl,alt:t.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):e.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:t.name,children:[e.jsx("span",{className:"text-xl leading-none",children:co(t.name,t.dataUrl)}),e.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:t.name.split(".").pop()?.toUpperCase()})]}),e.jsx("button",{onClick:()=>uo(t.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},t.id)),Ut.length<Sa&&e.jsx("button",{onClick:()=>pr.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:o("page.addMoreFiles"),children:e.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),Ut.length>0&&Ut.some(t=>Rr(t))&&et&&et.modelSupportsVision===!1&&e.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[e.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),o("page.visionWarning")]}),e.jsx("input",{ref:pr,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:t=>{t.target.files&&Cn(t.target.files),t.target.value=""}}),ys&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[e.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[e.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:ys.sender}),e.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:ys.text})]}),e.jsx("button",{onClick:()=>Xe(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("button",{onClick:()=>pr.current?.click(),disabled:L==="direct"&&(!J||Tn),className:`${Bt?"p-1.5 mb-0.5":"px-2.5 py-2.5"} text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated shrink-0`,title:o("page.attachFilesTitle"),children:e.jsx("svg",{className:Bt?"w-[18px] h-[18px]":"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsx("textarea",{ref:os,value:st,onChange:t=>{io(t.target.value),gn()},onKeyDown:t=>{if(ma&&Fs.length>0){const c=t.key==="ArrowUp"||t.ctrlKey&&t.key==="p",d=t.key==="ArrowDown"||t.ctrlKey&&t.key==="n",x=t.key==="Enter"||t.key==="Tab",P=t.key==="Escape";if(c){t.preventDefault(),Gs(z=>(z-1+Fs.length)%Fs.length);return}if(d){t.preventDefault(),Gs(z=>(z+1)%Fs.length);return}if(x){t.preventDefault();const z=Fs[jn];z&&(z.kind==="agent"?er(z.agent.name):er(z.entity.name,z.entity.entityType,z.entity.id));return}if(P){t.preventDefault(),vn(!1);return}}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Zs())},onPaste:mo,placeholder:vo,disabled:L==="direct"&&(!J||Tn),rows:Bt?1:2,className:`flex-1 min-w-0 bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-hidden leading-relaxed placeholder:text-fg-secondary ${Bt?"px-2 py-1.5":"px-4 py-3"}`,style:{minHeight:Bt?"36px":"52px",maxHeight:Bt?"160px":"120px"}}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pb-0.5",children:[L==="direct"&&e.jsx(ql,{value:Fn,disabled:!J||Tn,onSelect:(t,c)=>{Bn(t);const d=Le&&Le!==Ve?Le:null;Ul(d,t,c).catch(()=>{}),d&&qs(x=>x.map(P=>P.id===d?{...P,metadata:{...P.metadata??{},modelOverride:t}}:P))}}),Ct&&L!=="dm"?e.jsx("button",{onClick:Xi,className:`${Bt?"w-8 h-8 rounded-full flex items-center justify-center":"px-3 py-2.5 rounded-xl"} bg-red-600 hover:bg-red-500 text-white text-sm transition-colors`,title:o("page.stopAgent"),children:e.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}):e.jsx("button",{onClick:()=>{Zs()},disabled:L==="direct"&&(!J||Tn)||!st.trim()&&Ut.length===0,className:Bt?"w-8 h-8 rounded-full flex items-center justify-center bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white transition-colors":"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",title:o("common:send"),children:Bt?e.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"M12 19V5M5 12l7-7 7 7",strokeLinecap:"round",strokeLinejoin:"round"})}):o("common:send")})]})]})]})})]})]}),!v&&Q&&be&&e.jsx(Nl,{payload:Q,onClose:be,width:g?Gt:hs,onResizeStart:cr,onAddToChat:zs,tabs:H,activeTabId:ee,onSelectTab:de?.setActiveRightPanelTab,onCloseTab:de?.closeRightPanelTab,onNewTab:()=>{if(!ge)return;const t=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ge({kind:"url",url:"about:blank",title:"New Tab",browserId:t})},fullscreen:g,onToggleFullscreen:de?.toggleRightPanelFullscreen})]})}function gi({agent:i,tasks:a,onViewProfile:s,streamActive:r}){const{t:o}=Ue(["team","common"]),[l,u]=n.useState(!1),m=n.useRef(null),f=n.useRef(null),y=i.status==="working"||!!r,w=i.status==="error",j=y?a.find(T=>T.assignedAgentId===i.id&&T.status==="in_progress"):null,A=i.currentActivity;n.useEffect(()=>{w&&i.lastError&&rr(i.lastError)&&ar()},[w,i.lastError]),n.useEffect(()=>{if(!l)return;const T=C=>{m.current&&!m.current.contains(C.target)&&u(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[l]),n.useLayoutEffect(()=>{if(!l||!f.current)return;const T=f.current,C=T.getBoundingClientRect(),p=window.innerWidth;C.right>p-8&&(T.style.left="auto",T.style.right="0"),C.left<8&&(T.style.left="0",T.style.right="auto");const S=p-16;C.width>S&&(T.style.width=`${S}px`)},[l]);const b=w?"bg-red-400 animate-pulse":y?"bg-blue-400 animate-pulse":"bg-green-400",v=o(w?"common:status.error":y?"common:status.working":"common:status.idle"),D=A?A.type==="heartbeat"?o("page.activityHeartbeat",{name:A.heartbeatName??A.label}):A.type==="chat"?A.label:A.type==="task"?o("page.activityTask",{label:A.label}):A.label:o("page.processing");return e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{onClick:()=>u(T=>!T),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors ${y?"bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20":w?"bg-red-500/10 border border-red-500/20 hover:bg-red-500/20":"bg-green-500/10 border border-green-500/20 hover:bg-green-500/20"}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${b}`}),e.jsx("span",{className:`text-xs ${w?"text-red-500":y?"text-blue-500":"text-green-600"}`,children:v}),i.mailboxDepth!=null&&i.mailboxDepth>0&&e.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:i.mailboxDepth})]}),l&&w&&e.jsxs("div",{ref:f,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:o("page.errorDetails")}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[e.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:ir(i.lastError,o)||i.lastError||o("page.agentErrorFallback")}),i.lastErrorAt&&e.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(i.lastErrorAt).toLocaleString()})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(i.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:o("page.viewAgentProfileArrow")})]}),l&&y&&e.jsxs("div",{ref:f,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:o("page.currentActivity")}),j?e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{u(!1),xs.navigate(ut.WORK,{openTask:j.id})},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-brand-500 truncate",children:j.title}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("page.workingOnTaskHint")})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${A?.type==="heartbeat"||A?.type==="chat","bg-blue-400 animate-pulse"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:D}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:A?.type==="heartbeat"?o("page.activityDescHeartbeat"):A?.type==="chat"?o("page.activityDescChat"):o("page.activityDescFallback")})]})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(i.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:o("page.viewMindArrow")})]})]})}export{oc as TeamPage};
|