@useorgx/openclaw-plugin 0.7.25 → 0.7.27
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/dashboard/dist/assets/BGqqzQfq.js +1 -0
- package/dashboard/dist/assets/BGqqzQfq.js.br +0 -0
- package/dashboard/dist/assets/BGqqzQfq.js.gz +0 -0
- package/dashboard/dist/assets/BIW2kmQr.js +1 -0
- package/dashboard/dist/assets/BIW2kmQr.js.br +0 -0
- package/dashboard/dist/assets/BIW2kmQr.js.gz +0 -0
- package/dashboard/dist/assets/{BZCkOZ20.js → BLCzNocO.js} +1 -1
- package/dashboard/dist/assets/BLCzNocO.js.br +0 -0
- package/dashboard/dist/assets/BLCzNocO.js.gz +0 -0
- package/dashboard/dist/assets/BYsvgOkA.js +1 -0
- package/dashboard/dist/assets/BYsvgOkA.js.br +0 -0
- package/dashboard/dist/assets/BYsvgOkA.js.gz +0 -0
- package/dashboard/dist/assets/BafISmbX.js +1 -0
- package/dashboard/dist/assets/BafISmbX.js.br +0 -0
- package/dashboard/dist/assets/BafISmbX.js.gz +0 -0
- package/dashboard/dist/assets/CDsk---g.js +1 -0
- package/dashboard/dist/assets/CDsk---g.js.br +0 -0
- package/dashboard/dist/assets/CDsk---g.js.gz +0 -0
- package/dashboard/dist/assets/{BvFcH_Iy.js → CJ0ozAqs.js} +1 -1
- package/dashboard/dist/assets/CJ0ozAqs.js.br +0 -0
- package/dashboard/dist/assets/CJ0ozAqs.js.gz +0 -0
- package/dashboard/dist/assets/{MrW1ixGx.js → CKUnb6Tt.js} +1 -1
- package/dashboard/dist/assets/CKUnb6Tt.js.br +0 -0
- package/dashboard/dist/assets/CKUnb6Tt.js.gz +0 -0
- package/dashboard/dist/assets/{B_LdOJUa.js → CPfdWIdE.js} +1 -1
- package/dashboard/dist/assets/CPfdWIdE.js.br +0 -0
- package/dashboard/dist/assets/CPfdWIdE.js.gz +0 -0
- package/dashboard/dist/assets/{B6VftyY6.js → CQceXoUm.js} +1 -1
- package/dashboard/dist/assets/CQceXoUm.js.br +0 -0
- package/dashboard/dist/assets/CQceXoUm.js.gz +0 -0
- package/dashboard/dist/assets/{BANQdlC4.js → CgCm4tUc.js} +1 -1
- package/dashboard/dist/assets/CgCm4tUc.js.br +0 -0
- package/dashboard/dist/assets/CgCm4tUc.js.gz +0 -0
- package/dashboard/dist/assets/{DJYl7gyA.js → Cgp0m1Ld.js} +1 -1
- package/dashboard/dist/assets/Cgp0m1Ld.js.br +0 -0
- package/dashboard/dist/assets/Cgp0m1Ld.js.gz +0 -0
- package/dashboard/dist/assets/{DZtNMX0t.js → CjGl4MOt.js} +1 -1
- package/dashboard/dist/assets/CjGl4MOt.js.br +0 -0
- package/dashboard/dist/assets/CjGl4MOt.js.gz +0 -0
- package/dashboard/dist/assets/DNCNDTzi.js +212 -0
- package/dashboard/dist/assets/DNCNDTzi.js.br +0 -0
- package/dashboard/dist/assets/DNCNDTzi.js.gz +0 -0
- package/dashboard/dist/assets/dgbgHLWm.js +1 -0
- package/dashboard/dist/assets/dgbgHLWm.js.br +0 -0
- package/dashboard/dist/assets/dgbgHLWm.js.gz +0 -0
- package/dashboard/dist/assets/h2T7lbDc.js +1 -0
- package/dashboard/dist/assets/h2T7lbDc.js.br +0 -0
- package/dashboard/dist/assets/h2T7lbDc.js.gz +0 -0
- package/dashboard/dist/assets/oWHKFgkC.js +1 -0
- package/dashboard/dist/assets/oWHKFgkC.js.br +0 -0
- package/dashboard/dist/assets/oWHKFgkC.js.gz +0 -0
- package/dashboard/dist/assets/{CqRNb2EL.js → qD5absr0.js} +1 -1
- package/dashboard/dist/assets/qD5absr0.js.br +0 -0
- package/dashboard/dist/assets/qD5absr0.js.gz +0 -0
- package/dashboard/dist/assets/wzn4QuPG.css +1 -0
- package/dashboard/dist/assets/wzn4QuPG.css.br +0 -0
- package/dashboard/dist/assets/wzn4QuPG.css.gz +0 -0
- package/dashboard/dist/index.html +2 -2
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/openclaw.plugin.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/B6VftyY6.js.br +0 -0
- package/dashboard/dist/assets/B6VftyY6.js.gz +0 -0
- package/dashboard/dist/assets/BANQdlC4.js.br +0 -0
- package/dashboard/dist/assets/BANQdlC4.js.gz +0 -0
- package/dashboard/dist/assets/BPL4CL3c.js +0 -1
- package/dashboard/dist/assets/BPL4CL3c.js.br +0 -0
- package/dashboard/dist/assets/BPL4CL3c.js.gz +0 -0
- package/dashboard/dist/assets/BZCkOZ20.js.br +0 -0
- package/dashboard/dist/assets/BZCkOZ20.js.gz +0 -0
- package/dashboard/dist/assets/B_LdOJUa.js.br +0 -0
- package/dashboard/dist/assets/B_LdOJUa.js.gz +0 -0
- package/dashboard/dist/assets/Bfp-wdwb.css +0 -1
- package/dashboard/dist/assets/Bfp-wdwb.css.br +0 -0
- package/dashboard/dist/assets/Bfp-wdwb.css.gz +0 -0
- package/dashboard/dist/assets/BvFcH_Iy.js.br +0 -0
- package/dashboard/dist/assets/BvFcH_Iy.js.gz +0 -0
- package/dashboard/dist/assets/By0MIBj_.js +0 -1
- package/dashboard/dist/assets/By0MIBj_.js.br +0 -0
- package/dashboard/dist/assets/By0MIBj_.js.gz +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js +0 -212
- package/dashboard/dist/assets/C0i7ABUU.js.br +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js.gz +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js +0 -1
- package/dashboard/dist/assets/CFB0MM7j.js.br +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js.gz +0 -0
- package/dashboard/dist/assets/CQSRb1yu.js +0 -1
- package/dashboard/dist/assets/CQSRb1yu.js.br +0 -0
- package/dashboard/dist/assets/CQSRb1yu.js.gz +0 -0
- package/dashboard/dist/assets/CUoQoSm-.js +0 -1
- package/dashboard/dist/assets/CUoQoSm-.js.br +0 -0
- package/dashboard/dist/assets/CUoQoSm-.js.gz +0 -0
- package/dashboard/dist/assets/Ckd1R1iE.js +0 -1
- package/dashboard/dist/assets/Ckd1R1iE.js.br +0 -0
- package/dashboard/dist/assets/Ckd1R1iE.js.gz +0 -0
- package/dashboard/dist/assets/CqRNb2EL.js.br +0 -0
- package/dashboard/dist/assets/CqRNb2EL.js.gz +0 -0
- package/dashboard/dist/assets/DClUc9rw.js +0 -1
- package/dashboard/dist/assets/DClUc9rw.js.br +0 -0
- package/dashboard/dist/assets/DClUc9rw.js.gz +0 -0
- package/dashboard/dist/assets/DF2PMTwT.js +0 -1
- package/dashboard/dist/assets/DF2PMTwT.js.br +0 -0
- package/dashboard/dist/assets/DF2PMTwT.js.gz +0 -0
- package/dashboard/dist/assets/DJYl7gyA.js.br +0 -0
- package/dashboard/dist/assets/DJYl7gyA.js.gz +0 -0
- package/dashboard/dist/assets/DZtNMX0t.js.br +0 -0
- package/dashboard/dist/assets/DZtNMX0t.js.gz +0 -0
- package/dashboard/dist/assets/DlEa8PI0.js +0 -1
- package/dashboard/dist/assets/DlEa8PI0.js.br +0 -0
- package/dashboard/dist/assets/DlEa8PI0.js.gz +0 -0
- package/dashboard/dist/assets/M4QxcXjh.js +0 -1
- package/dashboard/dist/assets/M4QxcXjh.js.br +0 -0
- package/dashboard/dist/assets/M4QxcXjh.js.gz +0 -0
- package/dashboard/dist/assets/MrW1ixGx.js.br +0 -0
- package/dashboard/dist/assets/MrW1ixGx.js.gz +0 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BIW2kmQr.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/dgbgHLWm.js","assets/BLCzNocO.js","assets/eeHXe_OQ.js","assets/h2T7lbDc.js","assets/oWHKFgkC.js","assets/qD5absr0.js","assets/CJ0ozAqs.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/BGqqzQfq.js","assets/CDsk---g.js","assets/CSlBSRyv.js","assets/BafISmbX.js","assets/CQceXoUm.js","assets/CjGl4MOt.js","assets/BYsvgOkA.js","assets/CKUnb6Tt.js","assets/Cgp0m1Ld.js","assets/CgCm4tUc.js","assets/CPfdWIdE.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var cd=Object.defineProperty;var dd=(e,t,s)=>t in e?cd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var ss=(e,t,s)=>dd(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as ud,d as md}from"./Dj2k1r16.js";import{u as ao,a as pd,b as Dn,c as ei,Q as fd,d as hd}from"./DMKyYAtD.js";import{m as ue,A as bt,u as xs}from"./eeHXe_OQ.js";import{a7 as gd}from"./cX2e-TLi.js";import{D as Io}from"./BjK42gtU.js";import{T as xd,u as yd}from"./BV0BcV1u.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(r){if(r.ep)return;r.ep=!0;const a=s(r);fetch(r.href,a)}})();const bd="modulepreload",vd=function(e){return"/orgx/live/"+e},No={},sn=function(t,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));r=l(s.map(u=>{if(u=vd(u),u in No)return;No[u]=!0;const p=u.endsWith(".css"),h=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const y=document.createElement("link");if(y.rel=p?"stylesheet":bd,p||(y.as="script"),y.crossOrigin="",y.href=u,d&&y.setAttribute("nonce",d),document.head.appendChild(y),p)return new Promise((g,w)=>{y.addEventListener("load",g),y.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})},jo=()=>{const e=new Date,t=r=>new Date(e.getTime()-r*60*1e3).toISOString(),s=r=>new Date(e.getTime()-r*60*60*1e3).toISOString(),i=r=>new Date(e.getTime()-r*24*60*60*1e3).toISOString();return{connection:"connected",lastActivity:"1m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:3,sessions:{groups:[{id:"init-1",label:"Content Engine: Dogfood the Larry Playbook",status:"active"},{id:"init-2",label:"Live View UX Redesign — The Conductor's Display",status:"active"},{id:"init-3",label:"Directory Submissions & External References",status:"active"},{id:"init-4",label:"Revenue Expansion Q2",status:"completed"},{id:"init-5",label:"Incident Replay & Reliability",status:"blocked"}],edges:[{parentId:"run-100",childId:"run-101"},{parentId:"run-100",childId:"run-102"},{parentId:"run-100",childId:"run-103"},{parentId:"run-200",childId:"run-201"},{parentId:"run-200",childId:"run-202"},{parentId:"run-200",childId:"run-203"},{parentId:"run-300",childId:"run-301"},{parentId:"run-300",childId:"run-302"},{parentId:"run-300",childId:"run-303"}],nodes:[{id:"run-100",parentId:null,runId:"run-100",title:"Content Engine: Program orchestrator",agentId:"holt",agentName:"Holt",status:"running",progress:52,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(4),updatedAt:t(1),lastEventAt:t(1),lastEventSummary:"Stall scan complete; queue advanced to blog QA and distribution prep.",blockers:[],phase:"execution",state:"running",eta:"26m",checkpointCount:18,runtimeClient:"codex",runtimeLabel:"Codex Dispatch",runtimeProvider:"codex",instanceId:"instance-codex-01",lastHeartbeatAt:t(1)},{id:"run-101",parentId:"run-100",runId:"run-101",title:"Long-form article generation",agentId:"kimi",agentName:"Kimi",status:"in_progress",progress:61,initiativeId:"init-1",workstreamId:"ws-content-1",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(2),updatedAt:t(4),lastEventAt:t(4),lastEventSummary:"Two draft sections passed quality checks; awaiting review handoff.",blockers:[],phase:"review",state:"running",eta:"14m",checkpointCount:6,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Runner",runtimeProvider:"openclaw",instanceId:"instance-openclaw-03",lastHeartbeatAt:t(2)},{id:"run-102",parentId:"run-100",runId:"run-102",title:"Persona QA and legal sweep",agentId:"holt",agentName:"Holt",status:"blocked",progress:34,initiativeId:"init-1",workstreamId:"ws-content-legal",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(3),updatedAt:t(7),lastEventAt:t(7),lastEventSummary:"Blocked: legal sign-off timeout on compliance language.",blockers:["Legal sign-off overdue for compliance language","Persona claim needs policy exception approval"],phase:"blocked",state:"error",blockerReason:"Legal reviewer did not respond before SLA timeout.",eta:"Waiting on decision",checkpointCount:4,runtimeClient:"codex",runtimeLabel:"Codex Review Worker",runtimeProvider:"codex",instanceId:"instance-codex-07",lastHeartbeatAt:t(7),blockerDiagnostics:{reason:"Legal review is pending and blocked downstream publication.",source:"orgx",errorCode:"LEGAL_REVIEW_TIMEOUT",errorCategory:"dependency",retryable:!1,suggestedActions:["Escalate to legal duty reviewer","Approve fallback compliant copy variant"],eventId:"evt-legal-401",eventType:"question_timeout_started",eventTimestamp:t(9),context:{initiativeId:"init-1",workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",taskIds:["task-legal-2"],milestoneIds:["mile-content-2"],sliceRunId:"slice-run-104",parallelMode:"serial",logPath:"/tmp/orgx/legal-review.log",outputPath:"/tmp/orgx/legal-review-summary.md"}}},{id:"run-103",parentId:"run-100",runId:"run-103",title:"Distribution schedule and channel mapping",agentId:"pace",agentName:"Pace",status:"review",progress:82,initiativeId:"init-1",workstreamId:"ws-content-ops",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(2),updatedAt:t(20),lastEventAt:t(20),lastEventSummary:"Schedule proposal complete; waiting for owner confirmation.",blockers:["Owner confirmation pending"],phase:"review",state:"idle",eta:"11m after approval",checkpointCount:7,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Planner",runtimeProvider:"openclaw",instanceId:"instance-openclaw-04",lastHeartbeatAt:t(18)},{id:"run-200",parentId:null,runId:"run-200",title:"Live View UX Redesign — Orchestrator",agentId:"orgx",agentName:"OrgX",status:"running",progress:39,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(5),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Dispatching layout and timeline polish slices.",blockers:[],phase:"execution",state:"running",eta:"48m",checkpointCount:12,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Orchestrator",runtimeProvider:"openclaw",instanceId:"instance-openclaw-01",lastHeartbeatAt:t(1)},{id:"run-201",parentId:"run-200",runId:"run-201",title:"Activity feed readability pass",agentId:"dana",agentName:"Dana",status:"in_progress",progress:48,initiativeId:"init-2",workstreamId:"ws-ux-activity",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(2),updatedAt:t(6),lastEventAt:t(6),lastEventSummary:"Adjusted semantic grouping and status labels in timeline rows.",blockers:[],phase:"execution",state:"running",eta:"22m",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-02",lastHeartbeatAt:t(2)},{id:"run-202",parentId:"run-200",runId:"run-202",title:"Developer-mode feature gating",agentId:"holt",agentName:"you",status:"running",progress:73,initiativeId:"init-2",workstreamId:"ws-ux-devmode",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(3),updatedAt:t(3),lastEventAt:t(3),lastEventSummary:"Gated chat affordances and context cards behind developer mode.",blockers:[],phase:"execution",state:"running",eta:"9m",checkpointCount:9,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-03",lastHeartbeatAt:t(1)},{id:"run-203",parentId:"run-200",runId:"run-203",title:"Grouped section collapse spacing regression",agentId:"kimi",agentName:"Kimi",status:"blocked",progress:46,initiativeId:"init-2",workstreamId:"ws-ux-collapse",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(2),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Needs design decision on collapsed spacing token in grouped sections.",blockers:["Spacing token decision required for collapsed groups","Visual QA needs final approved baseline screenshot"],phase:"blocked",state:"error",blockerReason:"Design token ambiguity for collapsed section gap.",eta:"Waiting on decision",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-05",lastHeartbeatAt:t(2),blockerDiagnostics:{reason:"Layout engine requires explicit collapsed gap token before patching.",source:"agent",errorCode:"COLLAPSE_GAP_TOKEN_MISSING",errorCategory:"configuration",retryable:!0,suggestedActions:["Approve 8px collapsed gap token","Approve 0px gap for fully collapsed sections"],eventId:"evt-ux-778",eventType:"decision_needed",eventTimestamp:t(2),context:{initiativeId:"init-2",workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",taskIds:["task-ux-41"],milestoneIds:["mile-ux-12"],sliceRunId:"slice-run-101",parallelMode:"parallel",logPath:"/tmp/orgx/collapse-gap.log",outputPath:"/tmp/orgx/collapse-gap-plan.md"}}},{id:"run-300",parentId:null,runId:"run-300",title:"Directory Submissions & External References",agentId:"ops",agentName:"Ops",status:"running",progress:36,initiativeId:"init-3",workstreamId:null,groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(3),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Multi-lane pipeline active: import retries, QA verification, and outreach copy drafting.",blockers:["One vendor lane still rate-limited; recovery in progress"],phase:"execution",state:"running",blockerReason:"Partial dependency degradation on one vendor lane.",eta:"42m",checkpointCount:8,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Intake",runtimeProvider:"openclaw",instanceId:"instance-openclaw-08",lastHeartbeatAt:t(2)},{id:"run-301",parentId:"run-300",runId:"run-301",title:"Enrichment import pipeline",agentId:"pace",agentName:"Pace",status:"running",progress:27,initiativeId:"init-3",workstreamId:"ws-directory-import",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(1),updatedAt:t(3),lastEventAt:t(3),lastEventSummary:"Import retries active after vendor sandbox rate limits.",blockers:["Clearbit sandbox rate-limited; retry window opens in 6 minutes"],phase:"execution",state:"running",eta:"31m",checkpointCount:4,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Pipeline Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-09",lastHeartbeatAt:t(1)},{id:"run-302",parentId:"run-300",runId:"run-302",title:"Reference verification QA lane",agentId:"kimi",agentName:"Kimi",status:"running",progress:58,initiativeId:"init-3",workstreamId:"ws-directory-qa",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(2),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Citation verification batch completed; QA memo and mismatch ledger attached.",blockers:[],phase:"execution",state:"running",eta:"18m",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex QA Worker",runtimeProvider:"codex",instanceId:"instance-codex-09",lastHeartbeatAt:t(1)},{id:"run-303",parentId:"run-300",runId:"run-303",title:"External partner outreach copy",agentId:"mark",agentName:"Mark",status:"running",progress:41,initiativeId:"init-3",workstreamId:"ws-directory-outreach",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(2),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Outreach sequence draft in progress with two channel variants.",blockers:[],phase:"execution",state:"running",eta:"24m",checkpointCount:4,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Content Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-13",lastHeartbeatAt:t(2)},{id:"run-400",parentId:null,runId:"run-400",title:"Incident Replay & Reliability",agentId:"ops",agentName:"Ops",status:"blocked",progress:22,initiativeId:"init-5",workstreamId:null,groupId:"init-5",groupLabel:"Incident Replay & Reliability",startedAt:s(6),updatedAt:t(25),lastEventAt:t(25),lastEventSummary:"Replay reconstruction failed due to missing archived logs.",blockers:["Archive bucket retention policy removed required replay logs","Manual restore approval from platform owner required"],phase:"blocked",state:"error",blockerReason:"Missing archived logs prevent deterministic replay.",eta:"Waiting on restore decision",checkpointCount:11,runtimeClient:"api",runtimeLabel:"OrgX Replay Service",runtimeProvider:"orgx",instanceId:"instance-orgx-01",lastHeartbeatAt:t(25)},{id:"run-500",parentId:null,runId:"run-500",title:"Revenue Expansion Q2 closeout",agentId:"mark",agentName:"Mark",status:"completed",progress:100,initiativeId:"init-4",workstreamId:"ws-revenue-closeout",groupId:"init-4",groupLabel:"Revenue Expansion Q2",startedAt:s(8),updatedAt:t(40),lastEventAt:t(40),lastEventSummary:"Closeout report approved and milestone marked complete.",blockers:[],phase:"completed",state:"idle",checkpointCount:9,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Revenue Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-12",lastHeartbeatAt:t(40)}]},activity:[{id:"activity-200",type:"decision_requested",title:"Decision requested: collapsed section spacing",description:"Choose collapsed group spacing behavior to ship the gap regression fix.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-203",initiativeId:"init-2",timestamp:t(2),decisionRequired:!0,metadata:{event:"decision_needed",event_name:"question_asked",source:"agent",parsed_status:"blocked",decision_title:"Collapse spacing token",decisions_needed:[{title:"Use 8px collapsed gap",id:"decision-100"},{title:"Use 0px collapsed gap",id:"decision-100b"}],blocker:{description:"Layout cannot merge without explicit spacing token.",waiting_on:"you"}}},{id:"activity-201",type:"blocker_created",title:"Blocker created: grouped section gap",description:"Spacing token conflict detected while collapsing grouped sections.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-203",initiativeId:"init-2",timestamp:t(3),metadata:{event:"autopilot_slice_result",event_name:"autopilot_slice_result",source:"agent",parsed_status:"blocked",blocked_reason:"Collapsed section gap token unresolved.",blocker:{description:"Collapsed group spacing token is undefined across variants.",waiting_on:"design_owner"},decisions_needed:[{title:"Approve spacing token",id:"decision-100"}]}},{id:"activity-202",type:"artifact_created",title:"Artifact created: developer-mode gating patch",description:"Prepared patch and screenshot evidence for developer-mode-only controls.",agentId:"holt",agentName:"you",requesterAgentId:"holt",requesterAgentName:"you",executorAgentId:"holt",executorAgentName:"you",runId:"run-202",initiativeId:"init-2",timestamp:t(4),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{pr_url:"https://github.com/useorgx/orgx-openclaw-plugin/pull/312",pr_number:312,commit_sha:"1f4b2c9",commit_url:"https://github.com/useorgx/orgx-openclaw-plugin/commit/1f4b2c9",tests:{passed:31,failed:0,skipped:4}},task_updates:[{title:"Gate chat icon under developer mode",status:"completed"},{title:"Gate mic icon under developer mode",status:"completed"},{title:"Gate context card under developer mode",status:"completed"}]}},{id:"activity-203",type:"delegation",title:"Dispatch: readability pass",description:"Orchestrator dispatched readability polish while feature gating continues.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-200",initiativeId:"init-2",timestamp:t(6),metadata:{event:"autopilot_slice_dispatched",event_name:"autopilot_slice_dispatched",source:"orchestrator",parsed_status:"running",run_id:"slice-run-106",dispatch_selection_reason:"Queue selected highest confidence unblocked UI slice"}},{id:"activity-204",type:"run_started",title:"Slice started: enrichment import retry",description:"Started retry batch after rate limit window reopened.",agentId:"pace",agentName:"Pace",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-301",initiativeId:"init-3",timestamp:t(8),metadata:{event:"autopilot_slice_started",event_name:"autopilot_slice_started",source:"agent",parsed_status:"running",run_id:"slice-run-102"}},{id:"activity-225",type:"artifact_created",title:"Artifact created: reference QA packet",description:"Published mismatch ledger and verification memo for the latest reference batch.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-302",initiativeId:"init-3",timestamp:t(5),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:2,tests:{passed:14,failed:0,skipped:1},task_updates:2},task_updates:[{title:"Run citation verification across 120 references",status:"completed"},{title:"Publish mismatch ledger for reviewer approval",status:"completed"}],artifacts:[{id:"artifact-dir-qa-1",type:"report",title:"Reference verification memo",url:null},{id:"artifact-dir-qa-2",type:"spreadsheet",title:"Citation mismatch ledger",url:null}]}},{id:"activity-226",type:"delegation",title:"Dispatch: partner outreach copy lane",description:"Orchestrator launched a copy lane to draft partner outreach and handoff templates.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-300",initiativeId:"init-3",timestamp:t(9),metadata:{event:"autopilot_slice_dispatched",event_name:"autopilot_slice_dispatched",source:"orchestrator",parsed_status:"running",run_id:"slice-run-112",dispatch_selection_reason:"Reference verification can proceed in parallel with outreach preparation."}},{id:"activity-227",type:"run_started",title:"Slice started: outreach sequence draft",description:"Mark began drafting outreach sequence copy for external partners.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-303",initiativeId:"init-3",timestamp:t(8),metadata:{event:"autopilot_slice_started",event_name:"autopilot_slice_started",source:"agent",parsed_status:"running",run_id:"slice-run-112"}},{id:"activity-228",type:"artifact_created",title:"Artifact created: outreach copy sequence",description:"Drafted email + LinkedIn outreach variants and handoff checklist.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-303",initiativeId:"init-3",timestamp:t(6),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:1,tests:{passed:8,failed:0,skipped:0}},task_updates:[{title:"Produce 2 outreach channel variants",status:"completed"},{title:"Attach partner-ready handoff checklist",status:"completed"}],artifacts:[{id:"artifact-dir-outreach-1",type:"brief",title:"Partner outreach sequence v1",url:null}]}},{id:"activity-205",type:"decision_requested",title:"Decision requested: legal-safe copy variant",description:"Select fallback copy variant to unblock compliance gate.",agentId:"holt",agentName:"Holt",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"holt",executorAgentName:"Holt",runId:"run-102",initiativeId:"init-1",timestamp:t(10),decisionRequired:!0,metadata:{event:"question_asked",event_name:"question_asked",source:"agent",parsed_status:"blocked",decision_title:"Legal-safe phrasing for claim section",decisions_needed:[{title:"Choose fallback compliant claim",id:"decision-101"}],blocker:{description:"Cannot publish until legal-safe variant is selected.",waiting_on:"you"}}},{id:"activity-206",type:"blocker_created",title:"Blocker created: vendor rate limit",description:"Clearbit sandbox returned 429 and paused enrichment imports.",agentId:"pace",agentName:"Pace",requesterAgentId:"pace",requesterAgentName:"Pace",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-301",initiativeId:"init-3",timestamp:t(12),metadata:{event:"autopilot_slice_timeout",event_name:"autopilot_slice_timeout",source:"agent",parsed_status:"blocked",blocked_reason:"Rate limit hit during vendor enrichment fetch.",blocker:{description:"Vendor sandbox has 60 req/hour cap.",waiting_on:"vendor_api"}}},{id:"activity-207",type:"handoff_requested",title:"Handoff requested: editorial review",description:"Content draft is ready for editor review before publish scheduling.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"main",executorAgentName:"You",runId:"run-101",initiativeId:"init-1",timestamp:t(14),metadata:{event:"autopilot_slice_handoff",event_name:"autopilot_slice_handoff",source:"agent",parsed_status:"review"}},{id:"activity-208",type:"decision_resolved",title:"Decision resolved: hide non-dev controls",description:"Approved developer-mode gating for non-production controls.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-202",initiativeId:"init-2",timestamp:t(18),metadata:{event:"decision_resolved",event_name:"decision_resolved",source:"user",parsed_status:"completed",decision_id:"decision-108",selected_option_id:"decision-108-approve"}},{id:"activity-209",type:"run_completed",title:"Run completed: distribution schedule draft",description:"Channel mapping draft completed and attached for final owner sign-off.",agentId:"pace",agentName:"Pace",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-103",initiativeId:"init-1",timestamp:t(21),metadata:{event:"autopilot_slice_result",event_name:"autopilot_slice_result",source:"agent",parsed_status:"completed",run_id:"slice-run-105",outcomes:{tests:{passed:11,failed:0,skipped:1},artifact_count:1},task_updates:[{title:"Distribution schedule build",status:"completed"}]}},{id:"activity-210",type:"run_failed",title:"Run failed: incident replay reconstruction",description:"Replay service failed due to missing archived log segment.",agentId:"ops",agentName:"Ops",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"ops",executorAgentName:"Ops",runId:"run-400",initiativeId:"init-5",timestamp:t(25),metadata:{event:"workflow_error",event_name:"workflow_error",source:"system",parsed_status:"failed",blocked_reason:"Replay logs missing from archive.",decisions_needed:[{title:"Approve restore from backup snapshot",id:"decision-103"}]}},{id:"activity-211",type:"delegation",title:"Dispatch: legal review branch",description:"Orchestrator dispatched compliance fallback drafting branch.",agentId:"holt",agentName:"Holt",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-100",initiativeId:"init-1",timestamp:t(29),metadata:{event:"orchestrator_dispatch",event_name:"orchestrator_dispatch",source:"orchestrator",parsed_status:"running"}},{id:"activity-212",type:"milestone_completed",title:"Milestone completed: developer-mode controls",description:"Mission Control and Activity controls are now hidden for non-developer mode.",agentId:"dana",agentName:"Dana",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-202",initiativeId:"init-2",timestamp:t(34),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed"}},{id:"activity-213",type:"run_started",title:"Run started: content orchestrator",description:"Autopilot started for Larry playbook initiative.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-100",initiativeId:"init-1",timestamp:t(72),metadata:{event:"auto_continue_started",event_name:"auto_continue_started",source:"user",parsed_status:"running"}},{id:"activity-214",type:"blocker_created",title:"Blocker created: vendor credential handshake",description:"Directory submission pipeline is waiting for external vendor credentials.",agentId:"ops",agentName:"Ops",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"ops",executorAgentName:"Ops",runId:"run-300",initiativeId:"init-3",timestamp:t(54),metadata:{event:"spawn_guard_blocked",event_name:"spawn_guard_blocked",source:"system",parsed_status:"blocked",blocked_reason:"Credentials not provisioned in secret manager."}},{id:"activity-230",type:"milestone_completed",title:"Milestone completed: readability foundation",description:"Baseline readability hierarchy shipped and adopted in activity and mission panels.",agentId:"dana",agentName:"Dana",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-201",initiativeId:"init-2",timestamp:i(2),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed",outcomes:{artifact_count:1,tests:{passed:22,failed:0,skipped:3}},artifacts:[{id:"artifact-ux-activity-legacy",type:"design",title:"Readability hierarchy baseline",url:null}]}},{id:"activity-231",type:"artifact_created",title:"Artifact created: executive notes and next-up alignment",description:"You captured final guidance so completed work maps cleanly to what starts next.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:i(1),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"user",parsed_status:"completed",outcomes:{artifact_count:1,task_updates:1},task_updates:[{title:"Connect closeout outputs to next-up backlog",status:"completed"}],artifacts:[{id:"artifact-revenue-7",type:"brief",title:"Executive closeout notes",url:null}]}},{id:"activity-219",type:"run_started",title:"Run started: revenue closeout",description:"Revenue closeout automation launched for Q2 finalize workflow.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:s(8),metadata:{event:"session_start",event_name:"session_start",source:"user",parsed_status:"running"}},{id:"activity-220",type:"delegation",title:"Dispatch: finance reconciliation slice",description:"Orchestrator delegated reconciliation and closeout reporting to Mark.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:s(7),metadata:{event:"orchestrator_dispatch",event_name:"orchestrator_dispatch",source:"orchestrator",parsed_status:"running",run_id:"slice-run-110"}},{id:"activity-221",type:"artifact_created",title:"Artifact created: closeout package",description:"Published closeout report, variance sheet, and stakeholder brief.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:s(5),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:3,tests:{passed:6,failed:0,skipped:0}}}},{id:"activity-222",type:"decision_resolved",title:"Decision resolved: approve final variance handling",description:"Approved finance variance interpretation and finalized closeout notes.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:s(4),metadata:{event:"decision_resolved",event_name:"decision_resolved",source:"user",parsed_status:"completed",decision_id:"decision-revenue-4",selected_option_id:"decision-revenue-4-approve"}},{id:"activity-223",type:"handoff_fulfilled",title:"Handoff fulfilled: executive sign-off",description:"Executive review completed and closeout approved for publication.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:t(95),metadata:{event:"autopilot_slice_handoff",event_name:"autopilot_slice_handoff",source:"agent",parsed_status:"review"}},{id:"activity-224",type:"milestone_completed",title:"Milestone completed: Q2 closeout pack",description:"All closeout deliverables finalized and attached to the initiative.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:t(42),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed"}},{id:"activity-218",type:"run_completed",title:"Run completed: revenue closeout",description:"Final Q2 closeout report submitted and approved.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:t(40),metadata:{event:"run_completed",event_name:"run_completed",source:"agent",parsed_status:"completed"}},{id:"activity-215",type:"run_started",title:"Run started: UX redesign orchestrator",description:"Autopilot started for live view redesign initiative.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-200",initiativeId:"init-2",timestamp:t(89),metadata:{event:"auto_continue_started",event_name:"auto_continue_started",source:"user",parsed_status:"running"}},{id:"activity-216",type:"run_started",title:"Run started: directory intake",description:"Directory submissions initiative entered queued intake phase.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-300",initiativeId:"init-3",timestamp:t(110),metadata:{event:"session_start",event_name:"session_start",source:"user",parsed_status:"queued"}},{id:"activity-217",type:"run_started",title:"Heartbeat",description:"System health check across active runtime instances.",agentId:"system",agentName:"System",requesterAgentId:"system",requesterAgentName:"System",executorAgentId:"system",executorAgentName:"System",runId:"run-200",initiativeId:"init-2",timestamp:t(1),metadata:{event:"heartbeat",event_name:"heartbeat",source:"system"}}],handoffs:[{id:"handoff-200",title:"Editorial approval for long-form section",status:"created",priority:"high",summary:"Need human editorial approval before publishing section 3 and section 4.",currentActorType:"user",currentActorId:"you",createdAt:t(14),updatedAt:t(6),events:[{id:"handoff-event-200-1",handoffId:"handoff-200",eventType:"created",actorType:"agent",actorId:"kimi",payload:{summary:"Draft content is ready for editorial pass."},createdAt:t(14)},{id:"handoff-event-200-2",handoffId:"handoff-200",eventType:"claimed",actorType:"user",actorId:"you",payload:{summary:"Reviewing section drafts now."},createdAt:t(6)}]},{id:"handoff-201",title:"UX patch verification run",status:"claimed",priority:"medium",summary:"Patch is implemented and needs targeted visual verification before merge.",currentActorType:"agent",currentActorId:"dana",createdAt:t(37),updatedAt:t(18),events:[{id:"handoff-event-201-1",handoffId:"handoff-201",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Patch created for developer-mode visibility controls."},createdAt:t(37)},{id:"handoff-event-201-2",handoffId:"handoff-201",eventType:"claimed",actorType:"agent",actorId:"holt",payload:{summary:"Taking ownership of QA capture and merge readiness checks."},createdAt:t(18)}]},{id:"handoff-202",title:"Incident replay restore request",status:"created",priority:"high",summary:"Platform owner approval is required to restore archived logs from backup snapshot.",currentActorType:"user",currentActorId:"you",createdAt:t(29),updatedAt:t(25),events:[{id:"handoff-event-202-1",handoffId:"handoff-202",eventType:"created",actorType:"system",actorId:"orgx",payload:{summary:"Replay pipeline blocked by retention policy loss."},createdAt:t(29)}]},{id:"handoff-203",title:"Revenue closeout executive review",status:"fulfilled",priority:"medium",summary:"Executive sign-off complete and closeout artifacts accepted.",currentActorType:"agent",currentActorId:"mark",createdAt:s(5),updatedAt:t(95),events:[{id:"handoff-event-203-1",handoffId:"handoff-203",eventType:"created",actorType:"agent",actorId:"mark",payload:{summary:"Requested executive review of closeout package."},createdAt:s(5)},{id:"handoff-event-203-2",handoffId:"handoff-203",eventType:"claimed",actorType:"user",actorId:"you",payload:{summary:"Executive review in progress."},createdAt:s(4)},{id:"handoff-event-203-3",handoffId:"handoff-203",eventType:"fulfilled",actorType:"agent",actorId:"mark",payload:{summary:"Sign-off captured and initiative unblocked."},createdAt:t(95)}]}],decisions:[{id:"decision-100",title:"Choose collapsed section spacing behavior",context:"Grouped section collapse bug fix needs an explicit spacing token before merge.",status:"pending",priority:"high",decisionType:"ui_behavior",agentName:"you",agentId:"holt",initiativeId:"init-2",workstreamId:"ws-ux-collapse",dueAt:t(-30),requestedAt:t(2),updatedAt:t(2),waitingMinutes:2,sourceSystem:"orgx_live",recommendedAction:"Approve 8px spacing token for collapsed grouped sections.",occurrenceCount:1,sourceRunId:"run-203",metadata:{severity:"high",blockedWorkstreams:1,impactedScreens:["Activity","Mission Control"]},options:[{id:"decision-100-approve-8",label:"Use 8px collapsed spacing",description:"Keeps visual grouping while removing layout hole.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-100-approve-0",label:"Use 0px collapsed spacing",description:"Removes all gaps in collapsed state.",impliedStatus:"approved",actionType:"confirm_scope",requiresNote:!0},{id:"decision-100-defer",label:"Defer and park fix",description:"Move this slice to queue and continue with others.",impliedStatus:"cancelled",actionType:"defer",requiresNote:!0}]},{id:"decision-101",title:"Select legal-safe copy variant",context:"Legal review timeout blocked publication of Larry playbook draft.",status:"pending",priority:"critical",decisionType:"compliance",agentName:"Holt",agentId:"holt",initiativeId:"init-1",workstreamId:"ws-content-legal",dueAt:t(-20),requestedAt:t(10),updatedAt:t(7),waitingMinutes:10,sourceSystem:"orgx_live",recommendedAction:"Approve fallback variant B that removes unsupported claims.",occurrenceCount:2,sourceRunId:"run-102",metadata:{severity:"critical",blockedWorkstreams:2,downstreamBlockedCount:5},options:[{id:"decision-101-variant-b",label:"Approve variant B",description:"Compliant copy with conservative claims.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-101-request-legal",label:"Request legal context",description:"Ask legal reviewer for targeted edits.",impliedStatus:null,actionType:"request_info",requiresNote:!0},{id:"decision-101-reject",label:"Reject current options",description:"Restart copy drafting with stricter constraints.",impliedStatus:"declined",actionType:"reject",requiresNote:!0}]},{id:"decision-102",title:"Unblock vendor sandbox rate limits",context:"Directory enrichment pipeline is repeatedly throttled by vendor sandbox limits.",status:"pending",priority:"medium",decisionType:"ops_routing",agentName:"Pace",agentId:"pace",initiativeId:"init-3",workstreamId:"ws-directory-import",dueAt:t(-45),requestedAt:t(12),updatedAt:t(3),waitingMinutes:12,sourceSystem:"orgx_live",recommendedAction:"Promote queue priority for paid-tier vendor credentials.",occurrenceCount:3,sourceRunId:"run-301",metadata:{severity:"medium",blockedWorkstreams:1},options:[{id:"decision-102-queue-top",label:"Queue paid-tier credential setup",description:"Move credential provisioning to top of ops queue.",impliedStatus:"approved",actionType:"queue_top",requiresNote:!1},{id:"decision-102-retry",label:"Retry in 10 minutes",description:"Continue on sandbox and retry later.",impliedStatus:null,actionType:"retry",requiresNote:!1}]},{id:"decision-103",title:"Approve replay log restoration",context:"Incident replay is blocked because archive retention removed required logs.",status:"pending",priority:"critical",decisionType:"incident_recovery",agentName:"Ops",agentId:"ops",initiativeId:"init-5",workstreamId:"ws-reliability-replay",dueAt:t(-15),requestedAt:t(25),updatedAt:t(25),waitingMinutes:25,sourceSystem:"orgx_live",recommendedAction:"Approve restore from backup snapshot 2026-03-04T20:00Z.",occurrenceCount:1,sourceRunId:"run-400",metadata:{severity:"critical",blockedWorkstreams:3,downstreamBlockedCount:7},options:[{id:"decision-103-restore",label:"Restore snapshot",description:"Restore archived logs and resume replay.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-103-escalate",label:"Escalate to platform owner",description:"Escalate if restore permissions are unavailable.",impliedStatus:null,actionType:"escalate",requiresNote:!0}]},{id:"decision-104",title:"Confirm external reference verification policy",context:"Need policy confirmation for linking third-party directory references in generated content.",status:"pending",priority:"low",decisionType:"policy",agentName:"Ops",agentId:"ops",initiativeId:"init-3",workstreamId:"ws-directory-policy",dueAt:s(-6),requestedAt:t(41),updatedAt:t(19),waitingMinutes:41,sourceSystem:"orgx_live",recommendedAction:"Use strict verification and citation for all imported references.",occurrenceCount:1,sourceRunId:"run-300",metadata:{severity:"low",blockedWorkstreams:0},options:[{id:"decision-104-confirm",label:"Require strict verification",description:"Only include references with successful source validation.",impliedStatus:"approved",actionType:"confirm_scope",requiresNote:!1},{id:"decision-104-defer",label:"Defer to later milestone",description:"Proceed with placeholders and finalize references later.",impliedStatus:"cancelled",actionType:"defer",requiresNote:!0}]}],sliceRuns:[{id:"slice-run-100",sliceRunId:"slice-run-100",runId:"run-202",initiativeId:"init-2",workstreamId:"ws-ux-devmode",workstreamTitle:"Developer-mode feature gating",taskIds:["task-ux-31","task-ux-32","task-ux-33"],milestoneIds:[],status:"running",statusExplainer:"Patch implementation is running and waiting for final QA capture.",primaryAction:"review_output",hasArtifact:!0,artifactCount:2,artifacts:[{id:"artifact-ux-devmode-1",type:"diff_pack",title:"Developer mode gating patch",url:null,createdAt:t(4)},{id:"artifact-ux-devmode-2",type:"screenshot_set",title:"Visibility verification screenshots",url:null,createdAt:t(3)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(3),updatedAt:t(1),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(1),lastEventSummary:"Final QA pending before merge request.",correlationId:"run-202",confidence:"high",scope:"workstream",scopeProgress:{totalTasks:5,completedTasks:4}},{id:"slice-run-101",sliceRunId:"slice-run-101",runId:"run-203",initiativeId:"init-2",workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",taskIds:["task-ux-41"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Blocked pending spacing-token decision.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-101-opt-approve-8",label:"Approve 8px spacing",description:"Proceed with 8px collapsed group spacing.",impliedStatus:"approved",requiresNote:!1},{id:"slice-run-101-opt-approve-0",label:"Approve 0px spacing",description:"Proceed with 0px collapsed group spacing.",impliedStatus:"approved",requiresNote:!0}],sourceClient:"codex",runtimeState:"idle",startedAt:s(2),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting for a decision before patch can finalize.",correlationId:"run-203",confidence:"high",scope:"task",scopeProgress:{totalTasks:2,completedTasks:1}},{id:"slice-run-102",sliceRunId:"slice-run-102",runId:"run-301",initiativeId:"init-3",workstreamId:"ws-directory-import",workstreamTitle:"Enrichment import pipeline",taskIds:["task-dir-12"],milestoneIds:[],status:"failed",statusExplainer:"Failed due to vendor rate limiting; retry action available.",primaryAction:"retry_slice",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-102-opt-retry",label:"Retry after cooldown",description:"Retry once vendor cooldown period ends.",impliedStatus:null,requiresNote:!1}],sourceClient:"openclaw",runtimeState:"error",startedAt:s(1),updatedAt:t(3),completedAt:null,failedAt:t(12),archivedAt:null,lastEventAt:t(3),lastEventSummary:"Retry cycle started; previous run failed from API 429.",correlationId:"run-301",confidence:"medium",scope:"task",scopeProgress:{totalTasks:3,completedTasks:1}},{id:"slice-run-103",sliceRunId:"slice-run-103",runId:"run-101",initiativeId:"init-1",workstreamId:"ws-content-1",workstreamTitle:"Long-form article generation",taskIds:["task-content-12","task-content-13"],milestoneIds:["mile-content-2"],status:"needs_review",statusExplainer:"Draft complete; waiting for editorial review.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-content-21",type:"document",title:"Larry playbook draft v3",url:null,createdAt:t(14)}],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-103-opt-open",label:"Open draft",description:"Inspect draft and approve editorial handoff.",impliedStatus:null,requiresNote:!1}],sourceClient:"openclaw",runtimeState:"idle",startedAt:s(2),updatedAt:t(14),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(14),lastEventSummary:"Ready for editorial sign-off.",correlationId:"run-101",confidence:"high",scope:"task",scopeProgress:{totalTasks:4,completedTasks:3}},{id:"slice-run-104",sliceRunId:"slice-run-104",runId:"run-102",initiativeId:"init-1",workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",taskIds:["task-legal-2"],milestoneIds:["mile-content-2"],status:"awaiting_input",statusExplainer:"Waiting for legal-safe variant decision.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-104-opt-variant-b",label:"Approve legal variant B",description:"Proceed using conservative compliant variant.",impliedStatus:"approved",requiresNote:!1},{id:"slice-run-104-opt-request-info",label:"Request legal context",description:"Request legal reviewer notes before proceeding.",impliedStatus:null,requiresNote:!0}],sourceClient:"codex",runtimeState:"idle",startedAt:s(3),updatedAt:t(7),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(7),lastEventSummary:"Awaiting legal-safe variant selection.",correlationId:"run-102",confidence:"high",scope:"task",scopeProgress:{totalTasks:2,completedTasks:1}},{id:"slice-run-105",sliceRunId:"slice-run-105",runId:"run-103",initiativeId:"init-1",workstreamId:"ws-content-ops",workstreamTitle:"Distribution schedule and channel mapping",taskIds:["task-content-ops-7"],milestoneIds:["mile-content-3"],status:"completed",statusExplainer:"Completed with deliverable attached.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-content-ops-3",type:"plan",title:"Distribution schedule matrix",url:null,createdAt:t(21)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:s(2),updatedAt:t(21),completedAt:t(21),failedAt:null,archivedAt:null,lastEventAt:t(21),lastEventSummary:"Schedule matrix generated and shared for review.",correlationId:"run-103",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:3,completedTasks:3}},{id:"slice-run-106",sliceRunId:"slice-run-106",runId:"run-201",initiativeId:"init-2",workstreamId:"ws-ux-activity",workstreamTitle:"Activity feed readability pass",taskIds:["task-ux-18","task-ux-19"],milestoneIds:[],status:"running",statusExplainer:"Active polish pass with live preview updates.",primaryAction:"review_output",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(2),updatedAt:t(6),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(6),lastEventSummary:"Refining hierarchy labels and status chips.",correlationId:"run-201",confidence:"medium",scope:"workstream",scopeProgress:{totalTasks:4,completedTasks:2}},{id:"slice-run-107",sliceRunId:"slice-run-107",runId:"run-300",initiativeId:"init-3",workstreamId:"ws-directory-intake",workstreamTitle:"Directory intake coordination",taskIds:["task-dir-1"],milestoneIds:[],status:"queued",statusExplainer:"Queued behind credential provisioning dependency.",primaryAction:"none",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-107-opt-queue-top",label:"Prioritize credentials",description:"Move credential provisioning to top of queue.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"openclaw",runtimeState:"stale",startedAt:s(2),updatedAt:t(11),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(11),lastEventSummary:"Awaiting secret manager updates.",correlationId:"run-300",confidence:"medium",scope:"workstream",scopeProgress:{totalTasks:2,completedTasks:0}},{id:"slice-run-108",sliceRunId:"slice-run-108",runId:"run-400",initiativeId:"init-5",workstreamId:"ws-reliability-replay",workstreamTitle:"Incident replay reconstruction",taskIds:["task-rel-44"],milestoneIds:["mile-rel-9"],status:"failed",statusExplainer:"Failed due to missing archive logs and blocked restore.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-rel-2",type:"report",title:"Replay failure diagnostics",url:null,createdAt:t(25)}],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-108-opt-restore",label:"Approve restore",description:"Restore backup snapshot and retry replay.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"api",runtimeState:"error",startedAt:s(6),updatedAt:t(25),completedAt:null,failedAt:t(25),archivedAt:null,lastEventAt:t(25),lastEventSummary:"Replay failed: archive segment missing.",correlationId:"run-400",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:5,completedTasks:1}},{id:"slice-run-109",sliceRunId:"slice-run-109",runId:"run-100",initiativeId:"init-1",workstreamId:"ws-content-orchestration",workstreamTitle:"Content engine orchestration",taskIds:["task-content-orch-1","task-content-orch-2"],milestoneIds:["mile-content-1"],status:"running",statusExplainer:"Coordinator slice is dispatching and reconciling downstream tasks.",primaryAction:"none",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(4),updatedAt:t(1),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(1),lastEventSummary:"Orchestrator heartbeat healthy and dispatching.",correlationId:"run-100",confidence:"high",scope:"workstream",scopeProgress:{totalTasks:7,completedTasks:4}},{id:"slice-run-110",sliceRunId:"slice-run-110",runId:"run-500",initiativeId:"init-4",workstreamId:"ws-revenue-closeout",workstreamTitle:"Revenue Expansion Q2 closeout",taskIds:["task-revenue-19"],milestoneIds:["mile-revenue-4"],status:"completed",statusExplainer:"Completed and approved by stakeholders.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:3,artifacts:[{id:"artifact-revenue-4",type:"report",title:"Q2 revenue closeout summary",url:null,createdAt:s(5)},{id:"artifact-revenue-5",type:"spreadsheet",title:"Q2 variance reconciliation sheet",url:null,createdAt:s(5)},{id:"artifact-revenue-6",type:"brief",title:"Executive stakeholder brief",url:null,createdAt:t(40)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:s(8),updatedAt:t(40),completedAt:t(40),failedAt:null,archivedAt:null,lastEventAt:t(40),lastEventSummary:"Closeout summary delivered and approved.",correlationId:"run-500",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:1,completedTasks:1}},{id:"slice-run-111",sliceRunId:"slice-run-111",runId:"run-302",initiativeId:"init-3",workstreamId:"ws-directory-qa",workstreamTitle:"Reference verification QA lane",taskIds:["task-dir-qa-1","task-dir-qa-2"],milestoneIds:["mile-dir-2"],status:"running",statusExplainer:"Verification memo published; reconciling final citation mismatches.",primaryAction:"review_output",hasArtifact:!0,artifactCount:2,artifacts:[{id:"artifact-dir-qa-1",type:"report",title:"Reference verification memo",url:null,createdAt:t(5)},{id:"artifact-dir-qa-2",type:"spreadsheet",title:"Citation mismatch ledger",url:null,createdAt:t(5)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(2),updatedAt:t(5),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(5),lastEventSummary:"QA packet shipped; final mismatch reconciliation in progress.",correlationId:"run-302",confidence:"high",scope:"task",scopeProgress:{totalTasks:4,completedTasks:2}},{id:"slice-run-112",sliceRunId:"slice-run-112",runId:"run-303",initiativeId:"init-3",workstreamId:"ws-directory-outreach",workstreamTitle:"External partner outreach copy",taskIds:["task-dir-outreach-1","task-dir-outreach-2"],milestoneIds:["mile-dir-3"],status:"running",statusExplainer:"Draft sequence underway with channel variants attached for quick review.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-dir-outreach-1",type:"brief",title:"Partner outreach sequence v1",url:null,createdAt:t(6)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"active",startedAt:s(2),updatedAt:t(6),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(6),lastEventSummary:"Email + LinkedIn variants drafted; QA polish remaining.",correlationId:"run-303",confidence:"medium",scope:"task",scopeProgress:{totalTasks:3,completedTasks:1}}],runtimeInstances:[{id:"instance-codex-01",sourceClient:"codex",displayName:"Codex Dispatch Primary",providerLogo:"codex",state:"active",runId:"run-100",correlationId:"run-100",initiativeId:"init-1",workstreamId:null,taskId:null,agentId:"holt",agentName:"Holt",phase:"execution",progressPct:52,currentTask:"Queue scoring + legal branch dispatch",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Stall scan clear; queue advancing.",metadata:{queueDepth:5,source:"dispatch_job"}},{id:"instance-codex-03",sourceClient:"codex",displayName:"Codex UI Worker",providerLogo:"codex",state:"active",runId:"run-202",correlationId:"run-202",initiativeId:"init-2",workstreamId:"ws-ux-devmode",taskId:"task-ux-31",agentId:"holt",agentName:"Holt",phase:"execution",progressPct:73,currentTask:"QA screenshot capture and merge checklist",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Awaiting final visual verify before merge.",metadata:{branch:"feat/live-devmode-gates"}},{id:"instance-codex-05",sourceClient:"codex",displayName:"Codex UI Worker",providerLogo:"codex",state:"stale",runId:"run-203",correlationId:"run-203",initiativeId:"init-2",workstreamId:"ws-ux-collapse",taskId:"task-ux-41",agentId:"kimi",agentName:"Kimi",phase:"blocked",progressPct:46,currentTask:"Waiting on spacing-token decision",lastHeartbeatAt:t(2),lastEventAt:t(2),lastMessage:"Decision required before continuing.",metadata:{blockerCode:"COLLAPSE_GAP_TOKEN_MISSING"}},{id:"instance-openclaw-09",sourceClient:"openclaw",displayName:"OpenClaw Pipeline Worker",providerLogo:"openclaw",state:"active",runId:"run-301",correlationId:"run-301",initiativeId:"init-3",workstreamId:"ws-directory-import",taskId:"task-dir-12",agentId:"pace",agentName:"Pace",phase:"execution",progressPct:27,currentTask:"Retrying enrichment pull after cooldown",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Vendor cooldown window reopened.",metadata:{retryAttempt:3,vendor:"clearbit-sandbox"}},{id:"instance-codex-09",sourceClient:"codex",displayName:"Codex QA Worker",providerLogo:"codex",state:"active",runId:"run-302",correlationId:"run-302",initiativeId:"init-3",workstreamId:"ws-directory-qa",taskId:"task-dir-qa-2",agentId:"kimi",agentName:"Kimi",phase:"execution",progressPct:58,currentTask:"Reconciling citation mismatches after verification pass",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"QA memo published; validating final mismatch set.",metadata:{artifactIds:["artifact-dir-qa-1","artifact-dir-qa-2"]}},{id:"instance-openclaw-13",sourceClient:"openclaw",displayName:"OpenClaw Content Worker",providerLogo:"openclaw",state:"active",runId:"run-303",correlationId:"run-303",initiativeId:"init-3",workstreamId:"ws-directory-outreach",taskId:"task-dir-outreach-2",agentId:"mark",agentName:"Mark",phase:"execution",progressPct:41,currentTask:"Drafting partner outreach sequence",lastHeartbeatAt:t(2),lastEventAt:t(2),lastMessage:"Outreach variants drafted; preparing QA polish.",metadata:{artifactId:"artifact-dir-outreach-1"}},{id:"instance-orgx-01",sourceClient:"api",displayName:"OrgX Replay Service",providerLogo:"orgx",state:"error",runId:"run-400",correlationId:"run-400",initiativeId:"init-5",workstreamId:"ws-reliability-replay",taskId:"task-rel-44",agentId:"ops",agentName:"Ops",phase:"blocked",progressPct:22,currentTask:"Waiting for archive restore approval",lastHeartbeatAt:t(25),lastEventAt:t(25),lastMessage:"Replay failed: missing archive segment.",metadata:{incidentId:"inc-4471",severity:"sev2"}},{id:"instance-openclaw-04",sourceClient:"openclaw",displayName:"OpenClaw Planner",providerLogo:"openclaw",state:"stopped",runId:"run-103",correlationId:"run-103",initiativeId:"init-1",workstreamId:"ws-content-ops",taskId:"task-content-ops-7",agentId:"pace",agentName:"Pace",phase:"completed",progressPct:100,currentTask:"Awaiting owner sign-off",lastHeartbeatAt:t(21),lastEventAt:t(21),lastMessage:"Distribution schedule artifact attached.",metadata:{artifactId:"artifact-content-ops-3"}},{id:"instance-openclaw-12",sourceClient:"openclaw",displayName:"OpenClaw Revenue Worker",providerLogo:"openclaw",state:"stopped",runId:"run-500",correlationId:"run-500",initiativeId:"init-4",workstreamId:"ws-revenue-closeout",taskId:"task-revenue-19",agentId:"mark",agentName:"Mark",phase:"completed",progressPct:100,currentTask:"Closeout approved",lastHeartbeatAt:t(40),lastEventAt:t(40),lastMessage:"Q2 closeout summary approved.",metadata:{artifactIds:["artifact-revenue-4","artifact-revenue-5","artifact-revenue-6"],handoffId:"handoff-203"}}],timelineNarrative:[{projectionVersion:2,sliceRunId:"slice-run-100",title:"Developer-mode controls gated",occurredAt:t(1),actorProvenance:{actorType:"agent",actorId:"holt",displayName:"Holt",avatarKey:"holt"},intent:"Hide non-production controls unless developer mode is enabled.",dispatch:"Patch and QA capture were dispatched in parallel.",highlights:["Chat icon gated behind developer mode","Mic icon gated behind developer mode","Context card gated behind developer mode"],outcome:{state:"succeeded_with_artifacts",summary:"Patch complete with QA evidence; pending merge.",artifactCount:2},nextAction:{actionType:"open_pr",label:"Open PR and merge",payloadSchema:{prNumber:"number"},primary:!0},technicalTrace:{eventCount:12,eventIds:["activity-202","activity-208","activity-212"]}},{projectionVersion:2,sliceRunId:"slice-run-101",title:"Collapse-gap fix waiting on spacing decision",occurredAt:t(2),actorProvenance:{actorType:"agent",actorId:"kimi",displayName:"Kimi",avatarKey:"kimi"},intent:"Remove visual gap between grouped sections when collapsed.",dispatch:"Debugged layout tree and isolated spacing-token source.",highlights:["Collapsed layout path identified","Two viable spacing tokens proposed"],outcome:{state:"needs_input",summary:"Implementation blocked until spacing token is approved.",artifactCount:0},nextAction:{actionType:"review_decision",label:"Resolve spacing decision",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:7,eventIds:["activity-200","activity-201"]}},{projectionVersion:2,sliceRunId:"slice-run-104",title:"Legal sweep blocked by compliance response timeout",occurredAt:t(7),actorProvenance:{actorType:"agent",actorId:"holt",displayName:"Holt",avatarKey:"holt"},intent:"Finalize policy-safe copy before publication.",dispatch:"Escalated to legal and prepared fallback copy variants.",highlights:["Fallback variant B prepared","Compliance queue escalated"],outcome:{state:"needs_input",summary:"Awaiting legal-safe variant decision.",artifactCount:0},nextAction:{actionType:"review_decision",label:"Approve legal-safe variant",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:9,eventIds:["activity-205"]}},{projectionVersion:2,sliceRunId:"slice-run-102",title:"Enrichment import recovered from rate limiting",occurredAt:t(3),actorProvenance:{actorType:"agent",actorId:"pace",displayName:"Pace",avatarKey:"pace"},intent:"Ingest external references and keep queue moving.",dispatch:"Entered cooldown and resumed once rate window reopened.",highlights:["Vendor cooldown tracked","Retry workflow resumed automatically"],outcome:{state:"failed_actionable",summary:"Earlier failure remains actionable; retry is in progress.",artifactCount:0},nextAction:{actionType:"retry",label:"Retry enrichment slice",payloadSchema:{delayMinutes:"number"},primary:!0},technicalTrace:{eventCount:8,eventIds:["activity-204","activity-206"]}},{projectionVersion:2,sliceRunId:"slice-run-103",title:"Long-form draft prepared for editorial review",occurredAt:t(14),actorProvenance:{actorType:"agent",actorId:"kimi",displayName:"Kimi",avatarKey:"kimi"},intent:"Produce publication-ready long-form article draft.",dispatch:"Generated drafts and handed off for human editorial review.",highlights:["Three sections completed","Editorial handoff created"],outcome:{state:"succeeded_with_artifacts",summary:"Draft artifact created and waiting for review.",artifactCount:1},nextAction:{actionType:"open_artifact",label:"Open draft artifact",payloadSchema:{artifactId:"string"},primary:!0},technicalTrace:{eventCount:6,eventIds:["activity-207"]}},{projectionVersion:2,sliceRunId:"slice-run-105",title:"Distribution schedule finalized",occurredAt:t(21),actorProvenance:{actorType:"agent",actorId:"pace",displayName:"Pace",avatarKey:"pace"},intent:"Map finalized content to channels and publish windows.",dispatch:"Generated channel matrix and queued owner confirmation.",highlights:["Cross-channel schedule matrix generated","Owner sign-off request prepared"],outcome:{state:"succeeded_with_artifacts",summary:"Completed with one planning artifact.",artifactCount:1},nextAction:{actionType:"open_artifact",label:"Open schedule matrix",payloadSchema:{artifactId:"string"},primary:!1},technicalTrace:{eventCount:5,eventIds:["activity-209"]}},{projectionVersion:2,sliceRunId:"slice-run-108",title:"Incident replay blocked by missing archive logs",occurredAt:t(25),actorProvenance:{actorType:"system",actorId:"orgx",displayName:"OrgX",avatarKey:"orgx"},intent:"Reconstruct replay timeline for incident root-cause validation.",dispatch:"Replay attempted with available segments and failed on missing archive block.",highlights:["Archive block 2026-03-01 missing","Recovery decision raised for snapshot restore"],outcome:{state:"failed_actionable",summary:"Awaiting restore decision to continue replay.",artifactCount:1},nextAction:{actionType:"review_blocker",label:"Approve restore path",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:10,eventIds:["activity-210"]}},{projectionVersion:2,sliceRunId:"slice-run-109",title:"Orchestrator heartbeat and queue health",occurredAt:t(1),actorProvenance:{actorType:"system",actorId:"orgx",displayName:"OrgX",avatarKey:"orgx"},intent:"Keep active initiatives progressing through dispatch automation.",dispatch:"Heartbeat checked stalls, queue depth, and pending decisions.",highlights:["No task stalls detected in current window","Decision queue remains actionable for two initiatives"],outcome:{state:"succeeded_without_artifacts",summary:"Control-plane checks healthy; dispatch continues.",artifactCount:0},nextAction:null,technicalTrace:{eventCount:4,eventIds:["activity-217"]}},{projectionVersion:2,sliceRunId:"slice-run-110",title:"Revenue closeout completed",occurredAt:t(40),actorProvenance:{actorType:"agent",actorId:"mark",displayName:"Mark",avatarKey:"mark"},intent:"Finalize Q2 closeout and publish approved summary.",dispatch:"Closeout reporting and stakeholder review were executed sequentially.",highlights:["Run started and delegated by orchestrator","Closeout artifacts package published (3 artifacts)","Decision resolved for variance interpretation","Executive handoff fulfilled","Milestone and run marked complete"],outcome:{state:"succeeded_with_artifacts",summary:"Revenue closeout completed successfully.",artifactCount:3},nextAction:null,technicalTrace:{eventCount:7,eventIds:["activity-219","activity-220","activity-221","activity-222","activity-223","activity-224","activity-218"]}}],runningWorkSlices:5,needsInputTotal:3,failedActionableTotal:2,completedTodayTotal:7,consistencyFlags:[],outbox:{pendingTotal:4,pendingByQueue:{activity:2,artifacts:1,decisions:1},oldestEventAt:t(19),newestEventAt:t(2),replayStatus:"running",lastReplayAttemptAt:t(1),lastReplaySuccessAt:t(30),lastReplayFailureAt:t(3),lastReplayError:"Temporary timeout while replaying 1 decision event."},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},xa="all";function fs(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function wd(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return fs(e.get("workspace_id"))??fs(e.get("workspaceId"))??fs(e.get("command_center_id"))??fs(e.get("commandCenterId"))??fs(e.get("center"))??fs(e.get("project_id"))??fs(e.get("projectId"))}catch{return null}}function gs(e,t,s){const i=fs(t);if(!i){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",xa),e.set("command_center_id",xa),e.set("center",xa));return}e.set("workspace_id",i),e.set("command_center_id",i),e.set("center",i)}function kd(e){const t=fs(e);return t?{"x-orgx-workspace-id":t}:{}}function Ot(e){const t={};e.contentTypeJson&&(t["Content-Type"]="application/json"),e.embedMode&&(t["X-Orgx-Embed"]="true"),e.authToken&&(t.Authorization=`Bearer ${e.authToken}`);const s=e.workspaceId??wd();return Object.assign(t,kd(s)),t}const Id=[[/opus/i,"Opus"],[/sonnet/i,"Sonnet"],[/haiku/i,"Haiku"],[/kimi/i,"Kimi"],[/gemini/i,"Gemini"],[/gpt-4o/i,"GPT-4o"],[/gpt-4/i,"GPT-4"],[/qwen/i,"Qwen"],[/deepseek/i,"DeepSeek"],[/llama/i,"Llama"]];function Ki(e){if(!e)return"";for(const[s,i]of Id)if(s.test(e))return i;const t=e.split("/");return t[t.length-1]??e}const ac=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,oc=/^[0-9a-f]{20,}$/i;function Ss(e){return ac.test(e)?`#${e.slice(0,4)}`:oc.test(e)?`#${e.slice(0,4)}`:e}function Wn(e){return ac.test(e)||oc.test(e)}function zn(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const i=s.split("/");return i.length>t&&(s=i.slice(-t).join("/")),s}function Xe(e){let t=e;return t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,s=>`#${s.slice(0,4)}`),t=t.replace(/(?:anthropic|openrouter|openai)\/[a-z0-9._/-]+/gi,s=>Ki(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>zn(s)),t}function It(e){let t=e;return t=t.replace(/\[?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]?/gi,""),t=t.replace(/\[workstream\s*\]/gi,""),t=t.replace(/\[workstream\b[^\]]*\]/gi,""),t=t.replace(/\/var\/folders\/[^\s"']*/g,"(local file)"),t=t.replace(/\/tmp\/[^\s"']*/g,"(temp file)"),t=t.replace(/\/Users\/[^\s"']*/g,s=>zn(s)),t=t.replace(/telegram:\d+/g,"Telegram session"),t=t.replace(/discord:\d+/g,"Discord session"),t=t.replace(/\s{2,}/g," ").trim(),t||"Untitled session"}function ya(e){const t=e.toLowerCase().trim();return t==="main"?"You":t==="system"||t==="system / unknown"||t==="openclaw"||t==="local_openclaw"?"OrgX":t==="not assigned"||t==="unassigned"?"Pending":e}function Js(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ci(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function Nd(e,t){if(!e)return null;for(const s of t){const i=e[s];if(!(typeof i!="number"||!Number.isFinite(i)))return i}return null}function Ao(e){const t=Js(e);if(!t)return null;const s=Js(t.error),i=s??t,r=Ci(i,["message","detail","error_description"])??(s?null:Ci(t,["error"])),a=Ci(i,["code","error_code","type"]),l=Nd(i,["status","httpStatusCode"]),c=Ci(i,["requestId","request_id"]),d=Ci(i,["docsUrl","docs_url"]);return!r&&!a&&l==null&&!c&&!d?null:{code:a,message:r,status:l,requestId:c,docsUrl:d}}function jd(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),i=Ao(s);if(i)return i;const r=t.indexOf("{"),a=t.lastIndexOf("}");if(r>=0&&a>r){const p=t.slice(r,a+1);try{const h=JSON.parse(p),y=Ao(h);if(y)return y}catch{}}const l=t.match(/"message"\s*:\s*"([^"]+)"/i),c=t.match(/"code"\s*:\s*"([^"]+)"/i);return!l&&!c?null:{code:((d=c==null?void 0:c[1])==null?void 0:d.trim())||null,message:((u=l==null?void 0:l[1])==null?void 0:u.trim())||null,status:null,requestId:null,docsUrl:null}}function _o(e){return e.replace(/"requestId"\s*:\s*"[^"]*"/gi,"").replace(/"timestamp"\s*:\s*"[^"]*"/gi,"").replace(/"docsUrl"\s*:\s*"[^"]*"/gi,"").replace(/\brequest[_\s-]?id[:=]\s*[\w-]+/gi,"").replace(/\bdocsUrl[:=]\s*\S+/gi,"").replace(/\btimestamp[:=]\s*\S+/gi,"").replace(/[{}]/g," ").replace(/\s{2,}/g," ").trim()}function Xt(e){var c;const t=jd(e),s=((c=t==null?void 0:t.code)==null?void 0:c.toLowerCase())??"",i=(t==null?void 0:t.message)??null,r=(i==null?void 0:i.toLowerCase())??"";if(s==="internal_error"||r.includes("internal server error"))return/list decision|load decision|decision/i.test(r)?"Decisions are temporarily unavailable. Try refreshing in a moment.":"OrgX hit a temporary server issue. We will retry automatically.";if(s==="unauthorized"||s==="forbidden"||r.includes("unauthorized")||r.includes("forbidden"))return"Authentication needs attention. Reconnect OrgX in Settings.";const a=_o(i||e),l=a.toLowerCase();return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(l)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(l)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(l)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(l)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(l)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(l)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(l)?"This session is no longer available.":/500|internal_error|internal server error/i.test(l)?"Something went wrong on the server. Retrying automatically.":/econnrefused|network error|fetch failed/i.test(l)?"Connection issue. Retrying automatically.":/40[13]/.test(l)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(l)?"This item was paused without a specific reason.":It(Xe(a))}function Ad(e,t){if(e==null&&t==null||e===0&&t||e===0&&!t)return null;const s=e??0,i=t??0,r=a=>a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:`${a}`;return i>0?`${r(s)} / ${r(i)} (${Math.round(s/i*100)}%)`:r(s)}function _d(e){const t=(e==null?void 0:e.event_name)??(e==null?void 0:e.event)??"";if(t){const i=Xe(t);if(i&&i!=="Untitled session")return i}const s=(e==null?void 0:e.task_title)??(e==null?void 0:e.workstream_title)??(e==null?void 0:e.initiative_title)??"";return s.trim()?s.trim():"Activity event"}function Un(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function Sd(e,t){if(!e)return[];for(const s of t){const i=e[s];if(!Array.isArray(i))continue;const r=i.filter(a=>typeof a=="string").map(a=>It(a)).filter(Boolean);if(r.length>0)return r}return[]}function Ws(e){const t=new Set,s=[];for(const i of e){if(!i)continue;const r=It(i),a=r.toLowerCase();t.has(a)||(t.add(a),s.push(r))}return s}function So(e,t){if(!Array.isArray(e))return[];const s=[];for(const i of e){const r=Js(i);if(!r)continue;const a=Un(r,[`${t.toLowerCase()}_title`,`${t.toLowerCase()}Title`,"title","name"])??Un(r,[`${t.toLowerCase()}_id`,`${t.toLowerCase()}Id`]),l=Un(r,["status","state"]),c=Un(r,["reason","summary","description","note"]),d=[a?`${t}: ${a}`:t,l?`-> ${Xe(l)}`:null,c?`· ${It(c)}`:null].filter(Boolean);d.length>0&&s.push(d.join(" "))}return s}function Cd(e){if(!e)return[];const t=e.artifacts;return Array.isArray(t)?Ws(t.map(s=>{if(typeof s=="string")return s;const i=Js(s);return i?Un(i,["title","name","artifact_title","artifactTitle"])??Un(i,["url","path"])??Un(i,["type","artifact_type","artifactType"]):null})):Ws([Un(e,["artifact_title","artifactTitle"]),Un(e,["pr_url","prUrl"])?"Pull request attached":null,Un(e,["commit_sha","commitSha"])?"Commit attached":null])}function wi(e){const t=Js(e.metadata)??{},s=Js(t.result),i=Js(t.outcomes),r=[t,s,i].filter(k=>!!k),a=k=>{for(const T of r){const D=Un(T,k);if(D)return D}return null},l=k=>{for(const T of r){const D=Sd(T,k);if(D.length>0)return D}return[]},c=l(["scope_hierarchy","scopeHierarchy"]),d=Ws([c.length>0?c.join(" › "):null,[a(["initiative_title","initiativeTitle"]),a(["workstream_title","workstreamTitle"]),a(["task_title","taskTitle"])].filter(Boolean).join(" › ")])[0]??null,u=Ws([a(["user_summary","userSummary","decision_summary","decisionSummary","summary","description","message"]),e.summary,e.description])[0]??null,p=a(["stop_reason","stopReason"]),h=a(["parsed_status","parsedStatus","current_run_state","currentRunState","runtime_state","runtimeState","status","state"])??p,y=h?It(fi(h)??Xe(h)):null,g=Ws(r.flatMap(k=>Cd(k))),w=Ws([...r.flatMap(k=>So(k.task_updates??k.taskUpdates,"Task")),...r.flatMap(k=>So(k.milestone_updates??k.milestoneUpdates,"Milestone")),a(["required_action","requiredAction"])?`Required action: ${a(["required_action","requiredAction"])}`:null,a(["recommended_action","recommendedAction"])?`Recommended: ${a(["recommended_action","recommendedAction"])}`:null,a(["impact_if_delayed","impactIfDelayed"])?`Impact if delayed: ${a(["impact_if_delayed","impactIfDelayed"])}`:null]),N=Ws([a(["next_step","nextStep"]),...l(["next_actions","nextActions"]),a(["required_action","requiredAction"])]);return{update:u,scope:d,status:y,artifacts:g.slice(0,6),outcomes:w.slice(0,6),nextUp:N.slice(0,5)}}const Td={auto_continue_stopped:"Autopilot paused",budget_exhausted:"Token budget reached",error:"Encountered an error",blocked:"Waiting for input",stopped:"Manually stopped",rate_limited:"Rate limited — retrying shortly",timeout:"Timed out",timed_out:"Timed out",cancelled:"Cancelled",completed:"Completed"};function fi(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Td[t]??e.replace(/_/g," ")}const Md={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function $x(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Md[t]??e.replace(/_/g," ")}function Px(e,t){return e.toLowerCase().includes("path")?zn(t):Wn(t)?Ss(t):t.includes(",")?t.split(",").map(i=>{const r=i.trim();return Wn(r)?Ss(r):r}).join(", "):It(t)}function Ed(e){if(!Number.isFinite(e)||e<1)return"just now";if(e<60)return`${Math.round(e)} min`;const t=Math.floor(e/60),s=Math.round(e%60);if(t<24)return s>0?`${t} hr ${s} min`:`${t} hr`;const i=Math.floor(t/24);return i<7?`${i} day${i===1?"":"s"}`:i<14?"over a week":`${Math.floor(i/7)} weeks`}function Ox(e){const t=Ed(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Kr(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function Rt(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const i=Math.floor(Math.abs(s)/1e3),r=s<0?"past":"future";if(i<10)return r==="past"?"just now":"soon";if(i<60)return r==="past"?`${i}s ago`:`in ${i}s`;const a=Math.floor(i/60);if(a<60)return r==="past"?`${a}m ago`:`in ${a}m`;const l=Math.floor(a/60);if(l<24)return r==="past"?`${l}h ago`:`in ${l}h`;const c=Math.floor(l/24);return r==="past"?`${c}d ago`:`in ${c}d`}const Rd=8e3,Ld=320,Dd=300,$d=80,Pd=80,Od=120,Co=6e4,qd=4e3,Fd=4e3,Bd=240,Ud=3,zd=24,To=24,Ti=new WeakMap,oo={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},ur={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Zs={threads:[],total:0,updatedAt:null},Mo={running:0,active:0,queued:1,in_progress:1,working:1,planning:1,handoff:1,review:2,pending:2,blocked:3,failed:4,cancelled:5,paused:6,completed:6,archived:7},lc=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),mr=10*6e4;function Wd(e){const t=e.trim().toLowerCase();return t?t.includes("aborterror")||t.includes("signal is aborted")||t.includes("aborted")||t.includes("request cancelled")||t.includes("request canceled"):!1}function Hd(e){const t=e.trim().toLowerCase();if(!t)return"";if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("request canceled")||t.includes("signal is aborted"))return"Live sync is slower than expected. Some panels may refresh a few seconds late.";if(t.includes("unauthorized")||t.includes("forbidden"))return"OrgX authorization needs attention. Reconnect your API key in Settings.";if(t.includes("unknown api endpoint")||t.includes("route is unavailable"))return"This plugin runtime is missing required live routes. Restart the plugin after updating.";const s=e.replace(/^[^:]+:\s*/,"").replace(/\s+/g," ").trim();return Xt(s.length>0?s:e.trim())}function Kd(e){const t=e.map(s=>Hd(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function Nt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Vr(e,t){const s=Mo[e.status]??99,i=Mo[t.status]??99;if(s!==i)return s-i;const r=Nt(e.updatedAt??e.lastEventAt??e.startedAt),a=Nt(t.updatedAt??t.lastEventAt??t.startedAt);return r!==a?a-r:e.id.localeCompare(t.id)}function Vd(e){return(e??"").trim().toLowerCase()}function Eo(e){return lc.has(Vd(e.status))}function ba(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Ro(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const g=Date.now(),w=e.nodes.filter(T=>{const D=Nt(T.updatedAt??T.lastEventAt??T.startedAt);if(Eo(T))return!0;const _=["completed","archived","failed"].includes((T.status??"").toLowerCase())?mr/3:mr;return g-D<=_});if(!w.length)return t;const N=new Set(w.map(T=>T.id)),k=new Set(w.map(T=>T.groupId));return{nodes:w.sort(Vr),edges:e.edges.filter(T=>N.has(T.parentId)&&N.has(T.childId)),groups:e.groups.filter(T=>k.has(T.id))}}const s=new Set,i=[...t.nodes];for(const g of t.nodes)for(const w of ba(g))s.add(w);const r=Date.now(),a=[];for(const g of e.nodes){if(ba(g).some(b=>s.has(b)))continue;const N=Nt(g.updatedAt??g.lastEventAt??g.startedAt),T=["completed","archived","failed"].includes((g.status??"").toLowerCase())?mr/3:mr,D=r-N<=T;if(Eo(g)||D){a.push(g),i.push(g);for(const b of ba(g))s.add(b)}}if(!a.length)return t;const l=new Set(i.map(g=>g.id)),c=new Map(e.groups.map(g=>[g.id,g])),d=new Map(t.groups.map(g=>[g.id,g])),u=[...t.groups];for(const g of a){if(d.has(g.groupId))continue;const w=c.get(g.groupId)??{id:g.groupId,label:g.groupLabel||g.agentName||"Ungrouped",status:null};d.set(g.groupId,w),u.push(w)}const p=g=>`${g.parentId}->${g.childId}`,h=new Set,y=[];for(const g of t.edges){if(!l.has(g.parentId)||!l.has(g.childId))continue;const w=p(g);h.has(w)||(h.add(w),y.push(g))}for(const g of e.edges){if(!l.has(g.parentId)||!l.has(g.childId))continue;const w=p(g);h.has(w)||(h.add(w),y.push(g))}return{nodes:i.sort(Vr),edges:y,groups:u}}function Mi(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Vr).slice(0,t),i=new Set(s.map(a=>a.id)),r=new Set(s.map(a=>a.groupId));return{nodes:s,edges:e.edges.filter(a=>i.has(a.parentId)&&i.has(a.childId)),groups:e.groups.filter(a=>r.has(a.id))}}function Lo(e,t){return e.length<=t?e:[...e].sort((s,i)=>Nt(i.updatedAt)-Nt(s.updatedAt)).slice(0,t)}function Gd(e){const t=e.requestedAt??e.updatedAt??null,s=e.updatedAt??t,i=Number.isFinite(e.waitingMinutes)?Math.max(0,Math.floor(e.waitingMinutes)):t?Math.max(0,Math.floor((Date.now()-Nt(t))/6e4)):0;return{id:e.id,title:e.title,context:e.context??null,status:e.status??"pending",agentName:e.agentName??null,requestedAt:t,updatedAt:s,waitingMinutes:i,metadata:e.metadata}}function cc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].timestamp!==t[s].timestamp||e[s].type!==t[s].type||e[s].title!==t[s].title||e[s].requesterAgentId!==t[s].requesterAgentId||e[s].requesterAgentName!==t[s].requesterAgentName||e[s].executorAgentId!==t[s].executorAgentId||e[s].executorAgentName!==t[s].executorAgentName)return!1;return!0}function Do(e,t){if(e.nodes.length!==t.nodes.length||e.edges.length!==t.edges.length||e.groups.length!==t.groups.length)return!1;for(let s=0;s<e.nodes.length;s+=1){const i=e.nodes[s],r=t.nodes[s];if(i.id!==r.id||i.status!==r.status||i.title!==r.title||i.progress!==r.progress||i.updatedAt!==r.updatedAt||i.lastEventAt!==r.lastEventAt)return!1}for(let s=0;s<e.edges.length;s+=1){const i=e.edges[s],r=t.edges[s];if(i.parentId!==r.parentId||i.childId!==r.childId)return!1}for(let s=0;s<e.groups.length;s+=1){const i=e.groups[s],r=t.groups[s];if(i.id!==r.id||i.label!==r.label||i.status!==r.status)return!1}return!0}function $o(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function Po(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function dc(e){if(!e||typeof e!="object")return oo;const t=e.pendingByQueue&&typeof e.pendingByQueue=="object"?Object.fromEntries(Object.entries(e.pendingByQueue).filter(([i])=>typeof i=="string"&&i.length>0).map(([i,r])=>[i,Number.isFinite(Number(r))?Math.max(0,Math.floor(Number(r))):0])):{},s=e.replayStatus==="running"||e.replayStatus==="success"||e.replayStatus==="error"?e.replayStatus:"idle";return{pendingTotal:Number.isFinite(e.pendingTotal)?Math.max(0,Math.floor(e.pendingTotal)):Object.values(t).reduce((i,r)=>i+r,0),pendingByQueue:t,oldestEventAt:e.oldestEventAt??null,newestEventAt:e.newestEventAt??null,replayStatus:s,lastReplayAttemptAt:e.lastReplayAttemptAt??null,lastReplaySuccessAt:e.lastReplaySuccessAt??null,lastReplayFailureAt:e.lastReplayFailureAt??null,lastReplayError:e.lastReplayError??null}}function Xd(e,t){if(e.pendingTotal!==t.pendingTotal||e.oldestEventAt!==t.oldestEventAt||e.newestEventAt!==t.newestEventAt||e.replayStatus!==t.replayStatus||e.lastReplayAttemptAt!==t.lastReplayAttemptAt||e.lastReplaySuccessAt!==t.lastReplaySuccessAt||e.lastReplayFailureAt!==t.lastReplayFailureAt||e.lastReplayError!==t.lastReplayError)return!1;const s=Object.keys(e.pendingByQueue),i=Object.keys(t.pendingByQueue);if(s.length!==i.length)return!1;for(const r of s)if(e.pendingByQueue[r]!==t.pendingByQueue[r])return!1;return!0}function Gr(e,t=0){if(e==null)return"null";const s=typeof e;if(s==="string")return`s:${e}`;if(s==="number")return`n:${Number.isFinite(e)?String(e):"nan"}`;if(s==="boolean")return`b:${e?"1":"0"}`;if(s==="bigint")return`i:${String(e)}`;if(s!=="object")return`${s}:${String(e)}`;const i=e,r=Ti.get(i);if(r)return r;if(t>=Ud){const h=Array.isArray(e)?"[…]":"{…}";return Ti.set(i,h),h}if(Ti.set(i,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const h=e.slice(0,To).map(w=>Gr(w,t+1)).join(","),y=e.length>To?",…":"",g=`[${h}${y}]`;return Ti.set(i,g),g}const a=e,l=Object.keys(a).sort(),c=l.slice(0,zd),d=c.map(h=>`${h}:${Gr(a[h],t+1)}`).join("|"),u=l.length>c.length?"|…":"",p=`{${d}${u}}`;return Ti.set(i,p),p}function Qd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Fs(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function Yd(e){const t=Qd(e.metadata),s=t==null?void 0:t.event,i=typeof s=="string"?s.trim().toLowerCase():"",r=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??Fs(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=Fs(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??Fs(t,["initiative_id","initiativeId"]),c=Fs(t,["workstream_id","workstreamId"]),d=Fs(t,["task_id","taskId"]),u=Fs(t,["stop_reason","stopReason"]),p=Fs(t,["parsed_status","parsedStatus"]),h=(e.title??"").trim().toLowerCase();return!i&&!r&&!a||!r&&!a&&!c&&!d?null:[i,l??"",c??"",d??"",r??"",a??"",u??"",p??"",h].join("|")}function pr(e){let t=0;const s=e.metadata;return s&&(t+=Object.keys(s).length),e.summary&&(t+=2),e.description&&(t+=2),e.agentName&&(t+=1),e.runtimeLabel&&(t+=1),e.runtimeProvider&&(t+=1),e.phase&&(t+=1),e.state&&(t+=1),t}function uc(e,t){const s=new Set,i=new Set,r=new Map,a=[];for(const l of e){if(s.has(l.id)){const d=a.findIndex(u=>u.id===l.id);d>=0&&pr(l)>pr(a[d])&&(a[d]=l);continue}s.add(l.id);const c=Yd(l);if(c&&i.has(c)){const d=r.get(c);pr(l)>pr(a[d])&&(a[d]=l);continue}if(c&&(i.add(c),r.set(c,a.length)),a.push(l),a.length>=t)break}return a}function Jd(e,t,s){if(t.length===0)return e;const i=new Map,r=new Map;for(const d of e)i.set(d.id,d),r.set(d.id,Gr(d.metadata));let a=!1;for(const d of t){const u=i.get(d.id),p=Gr(d.metadata);if(!u){i.set(d.id,d),r.set(d.id,p),a=!0;continue}(u.timestamp!==d.timestamp||u.type!==d.type||u.title!==d.title||u.description!==d.description||u.summary!==d.summary||u.kind!==d.kind||u.agentId!==d.agentId||u.agentName!==d.agentName||u.requesterAgentId!==d.requesterAgentId||u.requesterAgentName!==d.requesterAgentName||u.executorAgentId!==d.executorAgentId||u.executorAgentName!==d.executorAgentName||u.runId!==d.runId||u.initiativeId!==d.initiativeId||u.decisionRequired!==d.decisionRequired||r.get(d.id)!==p)&&(i.set(d.id,d),r.set(d.id,p),a=!0)}if(!a)return e;const l=Array.from(i.values()).sort((d,u)=>{const p=Nt(u.timestamp)-Nt(d.timestamp);return p!==0?p:u.id.localeCompare(d.id)}),c=uc(l,s);return cc(e,c)?e:c}function va(e,t){const s=[...e].sort((i,r)=>{const a=Nt(r.timestamp)-Nt(i.timestamp);return a!==0?a:r.id.localeCompare(i.id)});return uc(s,t)}function Oo(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(Gd).sort((a,l)=>a.waitingMinutes!==l.waitingMinutes?l.waitingMinutes-a.waitingMinutes:Nt(l.requestedAt??l.updatedAt)-Nt(a.requestedAt??a.updatedAt)).slice(0,t),i=new Set,r=[];for(const a of s)i.has(a.id)||(i.add(a.id),r.push(a));return r}function qo(e){return e==="run_failed"||e==="blocker_created"?"blocked":e==="run_completed"||e==="milestone_completed"?"completed":e==="decision_requested"||e==="handoff_requested"?"pending":e==="decision_resolved"||e==="handoff_fulfilled"?"completed":"running"}function Zd(e){const t=e.toLowerCase();return t==="running"||t==="active"?"running":t==="queued"||t==="pending"?"queued":t==="blocked"?"blocked":t==="failed"?"failed":t==="completed"||t==="done"?"completed":"archived"}function eu(e,t){return!!(lc.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function fr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function wa(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)typeof s=="string"&&s.trim().length>0&&t.push(s.trim());return t}function tu(e,t,s){const i=new Map,r=[...e].sort((c,d)=>Nt(d.timestamp)-Nt(c.timestamp));for(const c of r){if(!c.runId)continue;const d=c.runId,u=i.get(d),p=c.timestamp;if(!u){const h=c.initiativeId??null;i.set(d,{id:d,parentId:null,runId:d,title:c.title,agentId:c.agentId??null,agentName:c.agentName??null,status:qo(c.type),progress:null,initiativeId:h,workstreamId:null,groupId:h??"unscoped",groupLabel:fr(h),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!u.startedAt||Nt(p)<Nt(u.startedAt))&&(u.startedAt=p),Nt(p)>=Nt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=p,u.lastEventAt=p,u.lastEventSummary=c.title,u.status=qo(c.type),c.agentName&&(u.agentName=c.agentName),c.agentId&&(u.agentId=c.agentId),c.initiativeId&&(u.initiativeId=c.initiativeId,u.groupId=c.initiativeId,u.groupLabel=fr(c.initiativeId)),(!u.title||u.title.length<4)&&(u.title=c.title)),c.type==="blocker_created"&&c.description&&(u.blockers.includes(c.description)||u.blockers.push(c.description))}for(const c of t??[]){const d=c.runId??`agent:${c.id}`,u=i.get(d),p=Zd(c.status),h=new Date().toISOString(),y=eu(c,p),g=c.startedAt??(y?h:null),w=c.initiativeId??null,N=c.currentTask&&c.currentTask.trim().length>0?c.currentTask.trim():`${c.name??c.id} ${p==="archived"?"idle":p}`;if(!u){i.set(d,{id:d,parentId:null,runId:d,title:N,agentId:c.id,agentName:c.name??c.id,status:p,progress:null,initiativeId:w,workstreamId:null,groupId:w??"unscoped",groupLabel:fr(w),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:c.currentTask,blockers:wa(c.blockers)});continue}!u.agentName&&c.name&&(u.agentName=c.name),u.agentId||(u.agentId=c.id),(!u.title||u.title===u.runId)&&(u.title=N),y&&(u.updatedAt=g??u.updatedAt??h,u.lastEventAt=g??u.lastEventAt??h),u.status==="archived"&&p!=="archived"&&(u.status=p),wa(c.blockers).length>0&&(u.blockers=wa(c.blockers)),w&&!u.initiativeId&&(u.initiativeId=w,u.groupId=w,u.groupLabel=fr(w))}const a=Array.from(i.values()).sort(Vr).slice(0,s),l=new Map;for(const c of a)l.has(c.groupId)||l.set(c.groupId,{id:c.groupId,label:c.groupLabel,status:c.status});return{nodes:a,edges:[],groups:Array.from(l.values())}}async function Fo(e,t,s){var p;const i=typeof(s==null?void 0:s.timeoutMs)=="number"&&Number.isFinite(s.timeoutMs)?Math.max(100,Math.floor(s.timeoutMs)):0,r=i>0?new AbortController:null,a=t==null?void 0:t.signal,l=(r==null?void 0:r.signal)??a,c=l?{...t??{},signal:l}:t??{};let d=null,u=null;if(r){if(a!=null&&a.aborted)r.abort();else if(a){const h=()=>r.abort();a.addEventListener("abort",h,{once:!0}),u=()=>a.removeEventListener("abort",h)}d=setTimeout(()=>r.abort(),i)}try{const h=await fetch(e,c),g=(((p=h.headers.get("content-type"))==null?void 0:p.toLowerCase())??"").includes("application/json");if(!h.ok){let w=`${h.status} ${h.statusText}`;if(g){const N=await h.json().catch(()=>null);N!=null&&N.error&&(w=`${h.status} ${N.error}`)}else{const N=(await h.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);N.length>0&&(w=`${h.status} ${N}`)}return{ok:!1,status:h.status,data:null,error:w}}if(!g){const w=(await h.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:h.status,data:null,error:`Unexpected content type for ${e}${w?`: ${w}`:""}`}}return{ok:!0,status:h.status,data:await h.json(),error:null}}catch(h){const y=h instanceof Error?h.message:"Network error",g=!!(r!=null&&r.signal.aborted)&&!(a!=null&&a.aborted);return h instanceof DOMException&&h.name==="AbortError"||Wd(y)?{ok:!1,status:0,data:null,error:g&&i>0?`request timed out after ${i}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:y}}finally{d&&clearTimeout(d),u&&u()}}function nu(e,t,s,i,r=[],a=oo,l=null,c=1,d=[],u=Zs,p){var w,N,k;const h=((w=t[0])==null?void 0:w.timestamp)??null,y=((N=i[0])==null?void 0:N.requestedAt)??((k=i[0])==null?void 0:k.updatedAt)??null,g=Nt(h)>=Nt(y)?h:y;return{connection:"connected",lastActivity:g?Rt(g):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:i,sliceRuns:r,outbox:dc(a),chat:Pr(u),runtimeInstances:d,workSliceProjections:(p==null?void 0:p.workSliceProjections)??[],needsInputItems:(p==null?void 0:p.needsInputItems)??[],timelineNarrative:(p==null?void 0:p.timelineNarrative)??[],nextUpByInitiative:(p==null?void 0:p.nextUpByInitiative)??[],runningWorkSlices:(p==null?void 0:p.runningWorkSlices)??0,needsInputTotal:(p==null?void 0:p.needsInputTotal)??0,failedActionableTotal:(p==null?void 0:p.failedActionableTotal)??0,completedTodayTotal:(p==null?void 0:p.completedTodayTotal)??0,consistencyFlags:(p==null?void 0:p.consistencyFlags)??[],dataHealth:(p==null?void 0:p.dataHealth)??void 0}}function Bo(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const i=s.id.trim();i&&t.set(i,s)}return Array.from(t.values()).sort((s,i)=>Nt(i.lastEventAt??i.lastHeartbeatAt)-Nt(s.lastEventAt??s.lastHeartbeatAt))}function Uo(e,t){const s=e??[],i=t??[];if(s.length!==i.length)return!1;for(let r=0;r<s.length;r+=1)if(s[r].id!==i[r].id||s[r].state!==i[r].state||s[r].lastEventAt!==i[r].lastEventAt||s[r].runId!==i[r].runId||s[r].progressPct!==i[r].progressPct)return!1;return!0}function su(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const i=s.id.trim();i&&t.set(i,{...s,id:i,watcherIds:Array.isArray(s.watcherIds)?s.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.watcherNames)?s.watcherNames.filter(Boolean):[],latestLaunch:s.latestLaunch&&typeof s.latestLaunch=="object"?{...s.latestLaunch,watcherIds:Array.isArray(s.latestLaunch.watcherIds)?s.latestLaunch.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.latestLaunch.watcherNames)?s.latestLaunch.watcherNames.filter(Boolean):[],warnings:Array.isArray(s.latestLaunch.warnings)?s.latestLaunch.warnings.filter(Boolean):[]}:null})}return Array.from(t.values()).sort((s,i)=>Nt(i.lastActivityAt??i.updatedAt)-Nt(s.lastActivityAt??s.updatedAt))}function Pr(e){if(!e||typeof e!="object")return Zs;const t=su(Array.isArray(e.threads)?e.threads:[]),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(t.length,Math.floor(e.total)):t.length;return{threads:t,total:s,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}function iu(e,t){const s=e??Zs,i=t??Zs;if(s.total!==i.total||s.updatedAt!==i.updatedAt||s.threads.length!==i.threads.length)return!1;for(let r=0;r<s.threads.length;r+=1){const a=s.threads[r],l=i.threads[r];if(a.id!==l.id||a.status!==l.status||a.lastActivityAt!==l.lastActivityAt||a.lastSnippet!==l.lastSnippet||a.assigneeId!==l.assigneeId||a.launchCount!==l.launchCount||a.messageCount!==l.messageCount)return!1}return!0}function Or(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(i,r)=>{const a=[],l=c=>{if(typeof c!="string")return;const d=c.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(i))for(const c of i)l(c);else if(typeof i=="string")for(const c of i.split(/[\n,;]+/g))l(c);return r&&l(r),a};for(const i of e){if(!i||typeof i!="object")continue;const r=typeof i.sliceKind=="string"?i.sliceKind:typeof i.slice_kind=="string"?i.slice_kind:null,a=(r==null?void 0:r.trim().toLowerCase())??null;if(a&&a!=="work_slice")continue;const l=typeof i.sliceRunId=="string"&&i.sliceRunId.trim().length>0?i.sliceRunId.trim():typeof i.id=="string"&&i.id.trim().length>0?i.id.trim():null;if(!l)continue;const c=s(i.initiativeIds,i.initiativeId??null),d=s(i.workstreamIds,i.workstreamId??null),u=s(i.iwmtIds,i.iwmtId??null),p=typeof i.initiativeId=="string"&&i.initiativeId.trim().length>0?i.initiativeId.trim():c[0]??null,h=typeof i.workstreamId=="string"&&i.workstreamId.trim().length>0?i.workstreamId.trim():d[0]??null,y=typeof i.iwmtId=="string"&&i.iwmtId.trim().length>0?i.iwmtId.trim():u[0]??null;t.set(l,{...i,id:l,sliceRunId:l,sliceKind:a==="work_slice"?"work_slice":void 0,initiativeId:p,initiativeIds:c,workstreamId:h,workstreamIds:d,iwmtId:y,iwmtIds:u,artifacts:Array.isArray(i.artifacts)?i.artifacts:[],decisionOptions:Array.isArray(i.decisionOptions)?i.decisionOptions:[],pendingDecisions:Array.isArray(i.pendingDecisions)?i.pendingDecisions??[]:[],blockers:Array.isArray(i.blockers)?i.blockers??[]:[],taskIds:Array.isArray(i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i.milestoneIds)?i.milestoneIds:[]})}return Array.from(t.values()).sort((i,r)=>Nt(r.updatedAt??r.lastEventAt)-Nt(i.updatedAt??i.lastEventAt))}function Ei(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const i=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!i)continue;const r=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(i,{...s,sliceRunId:i,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(r==null?void 0:r.initiativeIds)?r.initiativeIds:[],initiativeTitles:Array.isArray(r==null?void 0:r.initiativeTitles)?r.initiativeTitles:[],workstreamIds:Array.isArray(r==null?void 0:r.workstreamIds)?r.workstreamIds:[],workstreamTitles:Array.isArray(r==null?void 0:r.workstreamTitles)?r.workstreamTitles:[],taskIds:Array.isArray(r==null?void 0:r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r==null?void 0:r.milestoneIds)?r.milestoneIds:[],iwmtIds:Array.isArray(r==null?void 0:r.iwmtIds)?r.iwmtIds:[],sliceRunId:i,sessionId:typeof(r==null?void 0:r.sessionId)=="string"?r.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,i)=>Nt(i.updatedAt??i.completedAt??i.failedAt)-Nt(s.updatedAt??s.completedAt??s.failedAt))}function ka(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const i=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;i&&t.set(i,{...s,sliceRunId:i,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,i)=>Nt(i.occurredAt)-Nt(s.occurredAt))}function Ia(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t&&typeof t=="object").map(t=>({initiativeId:typeof t.initiativeId=="string"&&t.initiativeId.trim().length>0?t.initiativeId.trim():null,initiativeTitle:typeof t.initiativeTitle=="string"&&t.initiativeTitle.trim().length>0?t.initiativeTitle.trim():"Unscoped initiative",pendingCount:typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.floor(t.pendingCount)):0,queue:Array.isArray(t.queue)?t.queue:[]})).sort((t,s)=>s.pendingCount-t.pendingCount)}function zo(e){var s;if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const i of e){if(i.sliceKind!=="work_slice")continue;const r=i.lineage.initiativeIds[0]??null,a=i.lineage.workstreamIds[0]??null,l=i.lineage.workstreamTitles[0]??i.lineage.workstreamIds[0]??null,c=i.outcomeState==="needs_input"?"awaiting_input":i.outcomeState==="failed_actionable"||i.outcomeState==="failed_non_actionable"?"failed":i.lifecycleState==="completed"&&i.outcomeState==="succeeded_without_artifacts"?"needs_review":i.lifecycleState,d=((s=i.actionContract)==null?void 0:s.actionType)??null,u=d==="open_artifact"||d==="open_logs"||d==="open_session"||d==="open_run"||d==="open_workstream"||d==="open_task"||d==="open_initiative"||d==="open_pr"||d==="open_diff"||d==="open_branch"?"open_artifact":d==="approve"||d==="reject"||d==="provide_context"||d==="request_info"||d==="confirm_scope"||d==="connect_provider"||d==="refresh_credentials"||d==="reassign"||d==="escalate"?"resolve_decision":d==="retry"||d==="resume"||d==="start"||d==="auto_fix"?"retry_slice":i.outcomeState==="succeeded_without_artifacts"?"review_output":"none";t.push({id:i.sliceRunId,sliceRunId:i.sliceRunId,sliceKind:"work_slice",runId:i.runId,initiativeId:r,initiativeIds:i.lineage.initiativeIds,workstreamId:a,workstreamIds:i.lineage.workstreamIds,iwmtId:i.lineage.iwmtIds[0]??null,iwmtIds:i.lineage.iwmtIds,workstreamTitle:l,taskIds:i.lineage.taskIds,milestoneIds:i.lineage.milestoneIds,status:c,statusExplainer:i.statusExplainer,primaryAction:u,hasArtifact:i.hasArtifact,artifactCount:i.artifactCount,artifacts:i.artifacts.map(p=>({id:p.artifactId,type:p.type,title:p.title,url:p.url,createdAt:p.producedAt})),decisionCount:i.outcomeState==="needs_input"?1:0,blockingDecisionCount:i.outcomeState==="needs_input"?1:0,decisionOptions:[],sourceClient:i.sourceClient,runtimeState:i.runtimeState,startedAt:null,updatedAt:i.updatedAt,completedAt:i.completedAt,failedAt:i.failedAt,archivedAt:i.archivedAt,lastEventAt:i.updatedAt,lastEventSummary:i.statusExplainer,correlationId:i.sliceRunId,confidence:i.confidence})}return Or(t)}function ru(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.status!==r.status||i.updatedAt!==r.updatedAt||i.lastEventAt!==r.lastEventAt||i.artifactCount!==r.artifactCount||i.decisionCount!==r.decisionCount||i.blockingDecisionCount!==r.blockingDecisionCount||i.runtimeState!==r.runtimeState)return!1}return!0}function Wo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.lifecycleState!==r.lifecycleState||i.outcomeState!==r.outcomeState||i.updatedAt!==r.updatedAt||i.artifactCount!==r.artifactCount||i.lineage.sessionId!==r.lineage.sessionId)return!1}return!0}function au(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.occurredAt!==r.occurredAt||i.outcome.state!==r.outcome.state||i.outcome.artifactCount!==r.outcome.artifactCount)return!1}return!0}function ou(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.initiativeId!==r.initiativeId||i.pendingCount!==r.pendingCount||i.queue.length!==r.queue.length)return!1}return!0}function lu(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function cu(e,t){return!e&&!t?!0:!e||!t?!1:e.status===t.status&&e.totals.slices===t.totals.slices&&e.totals.missingTerminal===t.totals.missingTerminal&&e.totals.lineageGap===t.totals.lineageGap&&e.totals.artifactMismatch===t.totals.artifactMismatch&&e.totals.invalidActor===t.totals.invalidActor}function du(e={}){const{enabled:t=!0,pollInterval:s=Rd,useMock:i=!1,enableDecisions:r=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=Ld,maxActivityItems:d=Dd,maxHandoffs:u=$d,maxDecisions:p=Pd,batchWindowMs:h=Od}=e,y=typeof a=="string"&&a.trim().length>0?a.trim():null,g=typeof l=="string"&&l.trim().length>0?l.trim():null,[w,N]=o.useState(jo()),[k,T]=o.useState(ur),[D,b]=o.useState(!i),[_,H]=o.useState(null),A=o.useRef(),O=o.useRef(null),se=o.useRef(null),[M,L]=o.useState(!1),[ae,be]=o.useState(typeof document>"u"?!0:document.visibilityState==="visible"),[ie,P]=o.useState(typeof navigator>"u"?!0:navigator.onLine!==!1),xe=o.useRef(0),ne=o.useRef(!1),K=o.useRef(!1),G=o.useRef(null),le=o.useRef(`${y??"__all__"}::${g??"__all__"}`),Le=o.useRef(!1),Me=o.useRef(null),me=o.useCallback((he,je)=>{Me.current&&(clearTimeout(Me.current),Me.current=null),T(he),je!=null&&je.autoResetMs&&je.autoResetMs>0&&(Me.current=setTimeout(()=>{Me.current=null,T(ur)},je.autoResetMs))},[]);o.useEffect(()=>()=>{Me.current&&(clearTimeout(Me.current),Me.current=null),G.current&&(clearTimeout(G.current),G.current=null)},[]),o.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const he=()=>{be(document.visibilityState==="visible")},je=()=>P(!0),R=()=>P(!1);return document.addEventListener("visibilitychange",he),window.addEventListener("online",je),window.addEventListener("offline",R),()=>{document.removeEventListener("visibilitychange",he),window.removeEventListener("online",je),window.removeEventListener("offline",R)}},[]),o.useEffect(()=>{const he=`${y??"__all__"}::${g??"__all__"}`;le.current!==he&&(le.current=he,Le.current=!0,K.current=!1,me(ur),N(je=>({...je,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Zs,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(je.snapshotVersion??0)+1})),b(!0),H(null))},[y,g,me]);const Ne=o.useCallback((he,je,R,Ae=null,Se=null,Ee=null,$e=null,ye=null,mt=null,Ce=null)=>{xe.current=Date.now(),ne.current=!1,N(_e=>{const ee=Le.current;ee&&(Le.current=!1);const dt=je===null?ee?[]:_e.activity:va(je,d),yt=R===null?ee?[]:_e.handoffs:Lo(R,u),Be=Mi(he===null?ee?{nodes:[],edges:[],groups:[]}:_e.sessions:ee?Mi(he,c):Ro(_e.sessions,Mi(he,c)),c),te=Ae===null?ee?[]:_e.decisions:Oo(Ae,p),B=Se===null?ee?[]:_e.sliceRuns:Or(Se),oe=Ee===null?ee?oo:_e.outbox:dc(Ee),pe=ye===null?ee?[]:_e.runtimeInstances??[]:Bo(ye),Pe=mt===null?ee?Zs:_e.chat??Zs:Pr(mt),We=(Ce==null?void 0:Ce.workSliceProjections)==null?ee?[]:_e.workSliceProjections??[]:Ei(Ce.workSliceProjections),rt=(Ce==null?void 0:Ce.needsInputItems)==null?ee?[]:_e.needsInputItems??[]:Ei(Ce.needsInputItems),ge=(Ce==null?void 0:Ce.timelineNarrative)==null?ee?[]:_e.timelineNarrative??[]:ka(Ce.timelineNarrative),Ve=(Ce==null?void 0:Ce.nextUpByInitiative)==null?ee?[]:_e.nextUpByInitiative??[]:Ia(Ce.nextUpByInitiative),ce=typeof(Ce==null?void 0:Ce.runningWorkSlices)=="number"&&Number.isFinite(Ce.runningWorkSlices)?Math.max(0,Math.floor(Ce.runningWorkSlices)):_e.runningWorkSlices??0,X=typeof(Ce==null?void 0:Ce.needsInputTotal)=="number"&&Number.isFinite(Ce.needsInputTotal)?Math.max(0,Math.floor(Ce.needsInputTotal)):_e.needsInputTotal??0,Te=typeof(Ce==null?void 0:Ce.failedActionableTotal)=="number"&&Number.isFinite(Ce.failedActionableTotal)?Math.max(0,Math.floor(Ce.failedActionableTotal)):_e.failedActionableTotal??0,Ze=typeof(Ce==null?void 0:Ce.completedTodayTotal)=="number"&&Number.isFinite(Ce.completedTodayTotal)?Math.max(0,Math.floor(Ce.completedTodayTotal)):_e.completedTodayTotal??0,at=(Ce==null?void 0:Ce.consistencyFlags)==null?_e.consistencyFlags??[]:Ce.consistencyFlags.filter(ht=>typeof ht=="string"),pt=(Ce==null?void 0:Ce.dataHealth)===void 0||(Ce==null?void 0:Ce.dataHealth)===null?_e.dataHealth:Ce.dataHealth,ct=(_e.snapshotVersion??0)+1;return Do(_e.sessions,Be)&&cc(_e.activity,dt)&&$o(_e.handoffs,yt)&&Po(_e.decisions,te)&&ru(_e.sliceRuns,B)&&Xd(_e.outbox,oe)&&iu(_e.chat,Pe)&&Uo(_e.runtimeInstances,pe)&&Wo(_e.workSliceProjections??[],We)&&Wo(_e.needsInputItems??[],rt)&&au(_e.timelineNarrative??[],ge)&&ou(_e.nextUpByInitiative??[],Ve)&&(_e.runningWorkSlices??0)===ce&&(_e.needsInputTotal??0)===X&&(_e.failedActionableTotal??0)===Te&&(_e.completedTodayTotal??0)===Ze&&lu(_e.consistencyFlags??[],at)&&cu(_e.dataHealth,pt)&&_e.lastSnapshotAt===$e&&_e.connection==="connected"?_e:nu(Be,dt,yt,te,B,oe,$e,ct,pe,Pe,{workSliceProjections:We,needsInputItems:rt,timelineNarrative:ge,nextUpByInitiative:Ve,runningWorkSlices:ce,needsInputTotal:X,failedActionableTotal:Te,completedTodayTotal:Ze,consistencyFlags:at,dataHealth:pt})}),b(!1)},[d,p,u,c]),E=o.useCallback(async()=>{if(!t){N(R=>R.connection==="disconnected"?R:{...R,connection:"disconnected"}),b(!1),H(null);return}const he=`${y??"__all__"}::${g??"__all__"}`;if(O.current&&se.current===he)return O.current;if(i){N(jo()),b(!1);return}const je=(async()=>{try{const R=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});g&&gs(R,g),y&&R.set("initiative",y);const Ae=Ot({workspaceId:g}),Se=new URLSearchParams({status:"pending",limit:String(p)});g&&gs(Se,g),y&&Se.set("initiative",y);const[Ee,$e]=await Promise.all([Fo(`/orgx/api/live/snapshot-v2?${R.toString()}`,{headers:Ae},{timeoutMs:qd}),r?Fo(`/orgx/api/live/decisions?${Se.toString()}`,{headers:Ae},{timeoutMs:Fd}):Promise.resolve(null)]);if(!Ee.ok||!Ee.data){if(Ee.status===401||Ee.status===403){const Re=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw Re.code="ORGX_AUTH",Re}throw new Error(Ee.error??"live/snapshot-v2 unavailable")}const ye=Ee.data;if(le.current!==he)return;const mt=Array.isArray(ye.degraded)?ye.degraded.filter(Re=>typeof Re=="string"):[],Ce=mt.map(Re=>Re.toLowerCase()),_e=(...Re)=>Ce.some(He=>Re.some(Ue=>He.includes(Ue))),ee=Array.isArray(ye.activity)?ye.activity:[],dt=Array.isArray(ye.handoffs)?ye.handoffs:[],yt=Array.isArray(ye.decisions)?ye.decisions:[],Be=$e!=null&&$e.ok&&$e.data&&Array.isArray($e.data.decisions)?$e.data.decisions:[],te=r&&Be.length>0?Be:yt,B=ee.length===0&&_e("activity unavailable","activity local fallback failed"),oe=_e("sessions unavailable","sessions local fallback failed"),pe=dt.length===0&&_e("handoffs unavailable"),Pe=te.length===0&&_e("decisions unavailable"),We=Ei(Array.isArray(ye.projections)?ye.projections:[]),rt=Pr(ye.chat??null),ge=ka(Array.isArray(ye.timelineNarrative)?ye.timelineNarrative:[]),Ve=Ia(Array.isArray(ye.nextUpByInitiative)?ye.nextUpByInitiative:[]),ce=We.length>0?zo(We):Or(Array.isArray(ye.sliceRuns)?ye.sliceRuns:[]),X=ye.sessions&&Array.isArray(ye.sessions.nodes)&&Array.isArray(ye.sessions.edges)&&Array.isArray(ye.sessions.groups)?ye.sessions:tu(ee,ye.agents,c),Te=ce.length===0&&We.length===0&&_e("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),Ze=Ve.length===0&&_e("next-up unavailable","next-up queue"),at=B?null:ee,pt=pe?null:dt,ct=Pe?null:te,ht=oe&&X.nodes.length===0?null:X,rn=Te?null:We,Z=Te?null:ge,ve=Te?null:ce,Oe=Ze?null:Ve;Ne(ht,at,pt,ct,ve,ye.outbox??null,ye.generatedAt??null,ye.runtimeInstances??null,rt,{workSliceProjections:rn,needsInputItems:Array.isArray(ye.needsInputItems)?ye.needsInputItems:null,timelineNarrative:Z,nextUpByInitiative:Oe,runningWorkSlices:Te?null:ye.runningWorkSlices??null,needsInputTotal:Te?null:ye.needsInput??null,failedActionableTotal:Te?null:ye.failedActionable??null,completedTodayTotal:Te?null:ye.completedToday??null,consistencyFlags:Array.isArray(ye.consistencyFlags)?ye.consistencyFlags:null,dataHealth:ye.dataHealth??null});const Ge=mt.length>0?Kd(mt):[];Ge.length>0?(H(`Partial live data: ${Ge.join("; ")}`),N(Re=>Re.connection==="connected"?Re:{...Re,connection:"connected"}),L(!1)):(H(null),N(Re=>Re.connection==="connected"?Re:{...Re,connection:"connected"}))}catch(R){if(le.current!==he)return;const Ae=R instanceof Error?R.message:"Unknown error",Se=R==null||typeof R!="object"||!("code"in R)?!1:R.code==="ORGX_AUTH";Se&&(ne.current=!0);const Ee=xe.current>0&&Date.now()-xe.current>Co;H(Ae),N($e=>{const ye=Se||Ee?"disconnected":"reconnecting";return $e.connection===ye?$e:{...$e,connection:ye}}),L(!Se),b(!1)}finally{se.current===he&&(O.current=null,se.current=null)}})();return O.current=je,se.current=he,je},[Ne,t,r,d,p,u,c,g,y,i]),W=o.useCallback(async(he,je,R)=>{var mt,Ce,_e;if(!r)throw new Error("OrgX decisions are unavailable while disconnected.");const Ae=Array.from(new Set(he.filter(Boolean)));if(Ae.length===0)return{updated:0,failed:0};const Se=((mt=R==null?void 0:R.note)==null?void 0:mt.trim())||void 0,Ee=((Ce=R==null?void 0:R.optionId)==null?void 0:Ce.trim())||void 0;if(i){const ee=new Set(Ae);return N(dt=>{const yt=dt.decisions.filter(oe=>ee.has(oe.id));if(yt.length===0)return dt;const Be=new Date().toISOString(),te=yt.map(oe=>({id:`decision:${je}:${oe.id}:${Date.now()}`,type:"decision_resolved",title:je==="approve"?`Approved: ${oe.title}`:`Rejected: ${oe.title}`,description:oe.context,agentId:null,agentName:oe.agentName,requesterAgentId:null,requesterAgentName:oe.agentName??null,executorAgentId:null,executorAgentName:oe.agentName??null,runId:null,initiativeId:null,timestamp:Be,metadata:{decisionId:oe.id,action:je}})),B=va(te.concat(dt.activity),d);return{...dt,decisions:dt.decisions.filter(oe=>!ee.has(oe.id)),activity:B,lastActivity:Rt(Be)}}),{updated:ee.size,failed:0,firstError:void 0}}const $e=new Date().toISOString(),ye=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ot({contentTypeJson:!0,workspaceId:g}),body:JSON.stringify({ids:Ae,action:je,...Se?{note:Se}:{},...Ee?{option_id:Ee}:{}})});try{const ee=await ye.json().catch(()=>null),dt=Array.isArray(ee==null?void 0:ee.results)?ee.results:[],yt=new Set(dt.filter(pe=>pe.ok).map(pe=>pe.id)),te=((_e=dt.filter(pe=>!pe.ok).find(pe=>typeof pe.error=="string"&&pe.error.trim().length>0))==null?void 0:_e.error)??(typeof(ee==null?void 0:ee.error)=="string"&&ee.error.trim().length>0?ee.error:void 0);if(!ye.ok&&ye.status!==207){const pe=te??`Decision action failed (${ye.status})`;throw new Error(pe)}if(yt.size===0&&ye.ok&&((ee==null?void 0:ee.failed)??0)===0)for(const pe of Ae)yt.add(pe);yt.size>0?N(pe=>{const Pe=pe.decisions.filter(ce=>yt.has(ce.id));if(Pe.length===0)return pe;const We=new Date().toISOString(),rt=Pe.map(ce=>({id:`decision:${je}:${ce.id}:${Date.now()}`,type:"decision_resolved",title:je==="approve"?`Approved: ${ce.title}`:`Rejected: ${ce.title}`,description:ce.context,agentId:null,agentName:ce.agentName,requesterAgentId:null,requesterAgentName:ce.agentName??null,executorAgentId:null,executorAgentName:ce.agentName??null,runId:null,initiativeId:null,timestamp:We,metadata:{decisionId:ce.id,action:je}})),ge=va(rt.concat(pe.activity),d);return{...pe,decisions:pe.decisions.filter(ce=>!yt.has(ce.id)),activity:ge,lastActivity:Rt(We)}}):ye.ok&&Ae.length>0&&N(pe=>({...pe,decisions:pe.decisions.filter(Pe=>!Ae.includes(Pe.id))})),E();const B=(ee==null?void 0:ee.updated)??yt.size,oe=(ee==null?void 0:ee.failed)??Math.max(0,Ae.length-yt.size);return me({phase:oe>0?"error":"success",action:je,targetCount:Ae.length,message:oe>0?`${je==="approve"?"Approve":"Reject"} completed with ${oe} failure${oe===1?"":"s"}.`:je==="approve"?`Approved ${B} decision${B===1?"":"s"}.`:`Rejected ${B} decision${B===1?"":"s"}.`,startedAt:$e,completedAt:new Date().toISOString()},{autoResetMs:oe>0?8e3:4e3}),{updated:B,failed:oe,firstError:te}}catch(ee){throw me({phase:"error",action:je,targetCount:Ae.length,message:ee instanceof Error?ee.message:"Decision update failed.",startedAt:$e,completedAt:new Date().toISOString()}),ee}},[r,E,d,g,me,i]),V=o.useCallback(async(he,je)=>W([he],"approve",je),[W]),Y=o.useCallback(async(he,je)=>W([he],"reject",je),[W]),Ie=o.useCallback(async()=>{let he=[];return N(je=>(he=je.decisions.map(R=>R.id),je)),he.length===0?{updated:0,failed:0}:W(he,"approve")},[W]),De=o.useCallback(async(he,je,R)=>W(he,je,R?{note:R}:void 0),[W]);return o.useEffect(()=>{r||me(ur)},[r,me]),o.useEffect(()=>{if(!t){L(!1),b(!1),H(null);return}if(i){E();return}K.current=!1;const he=new URLSearchParams;g&&gs(he,g),y&&he.set("initiative",y);const je=he.toString()?`/orgx/api/live/stream-v2?${he.toString()}`:"/orgx/api/live/stream-v2",R=new EventSource(je),Ae=()=>{G.current&&(clearTimeout(G.current),G.current=null),!(!ae||!ie)&&(G.current=setTimeout(()=>{G.current=null,!K.current&&!ne.current&&E()},Bd))};Ae();let Se=null,Ee=null,$e=null,ye=null,mt=[],Ce=null,_e;const ee=()=>{if(_e=void 0,Se){xe.current=Date.now(),ne.current=!1;const Be=Se;Se=null,$e=null,ye=null,mt=[],Ce=null,Ee=null,Ne(Be.sessions,Be.activity,Be.handoffs,Be.decisions,Be.sliceRuns,Be.outbox,Be.generatedAt,Be.runtimeInstances,Be.chat,Be.v2);return}!$e&&!ye&&!Ce&&!Ee&&mt.length===0||(xe.current=Date.now(),ne.current=!1,N(Be=>{var B;let te=Be;if($e){const oe=Mi($e,c),pe=Mi(Ro(te.sessions,oe),c);$e=null,Do(te.sessions,pe)||(te={...te,sessions:pe})}if(ye){const oe=Lo(ye,u);ye=null,$o(te.handoffs,oe)||(te={...te,handoffs:oe})}if(Ce){const oe=Oo(Ce,p);Ce=null,Po(te.decisions,oe)||(te={...te,decisions:oe})}if(Ee){const oe=Bo(Ee);Ee=null,Uo(te.runtimeInstances,oe)||(te={...te,runtimeInstances:oe})}if(mt.length>0){const oe=Jd(te.activity,mt,d);mt=[],oe!==te.activity&&(te={...te,activity:oe,lastActivity:(B=oe[0])!=null&&B.timestamp?Rt(oe[0].timestamp):te.lastActivity})}return te===Be?Be:te.connection==="connected"?te:{...te,connection:"connected"}}),H(null),b(!1))},dt=()=>{_e||(_e=setTimeout(ee,h))};R.onopen=()=>{xe.current=Date.now(),ne.current=!1,L(!1),N(Be=>Be.connection==="connected"?Be:{...Be,connection:"connected"}),H(null),Ae()},R.onerror=()=>{if(ne.current){N(te=>te.connection==="disconnected"?te:{...te,connection:"disconnected"}),L(!1);return}const Be=xe.current>0&&Date.now()-xe.current>Co;N(te=>te.connection===(Be?"disconnected":"reconnecting")?te:{...te,connection:Be?"disconnected":"reconnecting"}),L(!0)},R.addEventListener("snapshot",Be=>{try{K.current=!0,G.current&&(clearTimeout(G.current),G.current=null);const te=JSON.parse(Be.data),B=typeof te.generatedAt=="string"&&te.generatedAt.length>0?te.generatedAt:new Date().toISOString();Se={sessions:te.sessions,activity:te.activity??[],handoffs:te.handoffs??[],decisions:te.decisions??null,sliceRuns:Array.isArray(te.sliceRuns)?Or(te.sliceRuns):Array.isArray(te.projections)?zo(Ei(te.projections)):null,outbox:te.outbox??null,generatedAt:B,runtimeInstances:Array.isArray(te.runtimeInstances)?te.runtimeInstances:null,chat:Pr(te.chat??null),v2:{workSliceProjections:Array.isArray(te.projections)?Ei(te.projections):null,timelineNarrative:Array.isArray(te.timelineNarrative)?ka(te.timelineNarrative):null,nextUpByInitiative:Array.isArray(te.nextUpByInitiative)?Ia(te.nextUpByInitiative):null,runningWorkSlices:typeof te.runningWorkSlices=="number"?te.runningWorkSlices:null,needsInputTotal:typeof te.needsInput=="number"?te.needsInput:null,needsInputItems:Array.isArray(te.needsInputItems)?te.needsInputItems:null,failedActionableTotal:typeof te.failedActionable=="number"?te.failedActionable:null,completedTodayTotal:typeof te.completedToday=="number"?te.completedToday:null,consistencyFlags:Array.isArray(te.consistencyFlags)?te.consistencyFlags:null,dataHealth:te.dataHealth??null}},dt()}catch(te){H(te instanceof Error?te.message:"Invalid snapshot")}}),R.addEventListener("activity.appended",Be=>{try{const te=JSON.parse(Be.data);if(te.length===0)return;mt=mt.concat(te),dt()}catch{}}),R.addEventListener("session.updated",Be=>{try{$e=JSON.parse(Be.data),dt()}catch{}});const yt=Be=>{try{const te=JSON.parse(Be.data);Ee=Array.isArray(te)?te:[te],dt()}catch{}};return R.addEventListener("runtime.updated",yt),R.addEventListener("handoff.updated",Be=>{try{ye=JSON.parse(Be.data),dt()}catch{}}),R.addEventListener("decision.updated",Be=>{try{Ce=JSON.parse(Be.data),dt()}catch{}}),()=>{G.current&&(clearTimeout(G.current),G.current=null),_e&&clearTimeout(_e),R.close()}},[Ne,h,t,r,E,d,p,u,c,y,g,ae,ie,i]),o.useEffect(()=>{if(t&&!i&&(A.current&&clearInterval(A.current),!(!M||!ae||!ie)))return A.current=setInterval(()=>{E()},s),()=>{A.current&&clearInterval(A.current)}},[t,E,ae,ie,g,s,M,i]),o.useEffect(()=>{!t||i||M&&(!ae||!ie||E())},[t,E,ae,ie,M,i]),{data:w,isLoading:D,error:_,refetch:E,approveDecision:V,rejectDecision:Y,approveAllDecisions:Ie,bulkDecisionAction:De,decisionMutation:k}}const Vi=[{id:"live",label:"Last hour",minutes:null},{id:"24h",label:"Today",minutes:null},{id:"7d",label:"This week",minutes:10080},{id:"custom",label:"Custom",minutes:null},{id:"all",label:"All",minutes:null}];function mc(e){return Vi.find(t=>t.id===e)??Vi[0]}function Yi(e,t=Date.now()){if(e==="all")return null;if(e==="live")return t-60*6e4;if(e==="24h"){const i=new Date(t);return i.setHours(0,0,0,0),i.getTime()}if(e==="custom")return null;const s=Vi.find(i=>i.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function uu(e,t=Date.now()){const s=Yi(e,t);return s?new Date(s).toISOString():null}const Xr="orgx.sandbox_mode",Qr="orgx.demo_mode",Na="orgx.dev_mode",qr="orgx.show_synthetic_entities",Ka="orgx.selected_workspace_id",hr="orgx.onboarding.skip",mu=new Set(["ungrouped","unscoped","unknown"]);function ki(e){const t=(e??"").trim().toLowerCase();return!!(!t||mu.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function zi(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);if(e.get("sandbox")==="1"||e.get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Xr)==="1"||window.localStorage.getItem(Qr)==="1"}catch{return!1}}function Hn(){return zi()}function pu(){if(typeof window>"u")return!1;if(Hn())return!0;try{return window.localStorage.getItem(qr)==="1"}catch{return!1}}function fu(e){return Hn()?!0:!ki(e)}function Va(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function pc(e,t){const s=Va(t.timestamp)-Va(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function hu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function gu(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function fc(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=hu(e.metadata);return gu(s,["initiative_id","initiativeId"])}function ja(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ga(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null)return e===t;if(typeof e!="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let l=0;l<e.length;l+=1)if(!Ga(e[l],t[l]))return!1;return!0}const s=e,i=t,r=Object.keys(s).sort(),a=Object.keys(i).sort();if(r.length!==a.length)return!1;for(let l=0;l<r.length;l+=1){const c=r[l];if(c!==a[l]||!Ga(s[c],i[c]))return!1}return!0}const xu=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function xi(e,...t){}function yu(e,t,s,i){const r=new Map,a=t.sinceEpoch,l=t.untilEpoch;let c=0,d=0,u=0;for(const p of e??[]){if(!p||typeof p.id!="string")continue;if(s&&p.runId!==s){c++;continue}if(i&&fc(p)!==i){d++;continue}const h=Va(p.timestamp);if(h){if(a!==null&&h<a){u++;continue}if(l!==null&&h>l){u++;continue}r.set(p.id,p)}}return xi("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:r.size,runId:s,initiativeId:i,skippedRun:c,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:l?new Date(l).toISOString():null}),Array.from(r.values()).sort(pc)}function Ho(e,t){if(t.length===0)return e;const s=new Map;for(const l of e)s.set(l.id,l);let i=0,r=0,a=!1;for(const l of t){const c=s.get(l.id);if(!c){s.set(l.id,l),a=!0,i++;continue}(c.timestamp!==l.timestamp||c.type!==l.type||c.title!==l.title||c.description!==l.description||c.summary!==l.summary||!Ga(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),a=!0,r++)}return xi("mergeById",{currentCount:e.length,incomingCount:t.length,added:i,updated:r,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(pc):e}function bu(e){const{seed:t,timeFilterId:s,customSinceIso:i=null,customUntilIso:r=null,runId:a=null,initiativeId:l=null,projectId:c=null,pageSize:d=50,demoMode:u=Hn()}=e,p=o.useMemo(()=>ja(a),[a]),h=o.useMemo(()=>ja(l),[l]),y=o.useMemo(()=>ja(c),[c]),g=o.useMemo(()=>Yi(s),[s]),w=o.useMemo(()=>uu(s),[s]),N=o.useMemo(()=>{if(s==="custom"){const me=(i==null?void 0:i.trim())??"";return me.length>0?me:null}return w},[i,w,s]),k=o.useMemo(()=>{if(s!=="custom")return null;const me=(r==null?void 0:r.trim())??"";return me.length>0?me:null},[r,s]),T=o.useMemo(()=>{if(N){const me=Date.parse(N);if(Number.isFinite(me))return me}return g},[g,N]),D=o.useMemo(()=>{if(!k)return null;const me=Date.parse(k);return Number.isFinite(me)?me:null},[k]),b=o.useMemo(()=>yu(t,{sinceEpoch:T,untilEpoch:D},p,h),[t,T,D,p,h]),_=u?null:"",[H,A]=o.useState(b),[O,se]=o.useState(()=>_),[M,L]=o.useState(!1),[ae,be]=o.useState(null),[ie,P]=o.useState(null),xe=o.useRef(null),ne=o.useRef(!1),K=o.useRef(b);K.current=b;const G=o.useMemo(()=>`${p??""}|${h??""}|${s}|${N??""}|${k??""}|${y??""}|${u?"demo":"live"}`,[p,h,s,N,k,y,u]),le=o.useRef(G);o.useEffect(()=>{le.current!==G&&(le.current=G,xi("RESET",{reason:"filter/run change",runId:p,initiativeId:h,projectId:y,timeFilterId:s,sinceIso:N,untilIso:k,seedCount:K.current.length}),A(K.current),se(_),be(null),P(null),ne.current=!1)},[G,_,p,h,y,s,N,k]),o.useEffect(()=>{A(me=>{const Ne=Ho(me,b);return Ne!==me&&xi("SSE_MERGE",{prevCount:me.length,seedCount:b.length,nextCount:Ne.length,delta:Ne.length-me.length}),Ne})},[b]);const Le=o.useCallback(async()=>{if(u){se(null),be(null);return}if(O===null)return;if(xe.current)return xe.current;L(!0);const me=(async()=>{try{const Ne=new URLSearchParams;Ne.set("limit",String(Math.max(1,Math.min(500,d)))),O.trim().length>0&&Ne.set("cursor",O),N&&Ne.set("since",N),k&&Ne.set("until",k),p&&Ne.set("run",p),h&&Ne.set("initiative",h),y&&gs(Ne,y);const E=await fetch(`/orgx/api/live/activity/page?${Ne.toString()}`,{headers:Ot({workspaceId:y})}),W=await E.json().catch(()=>null);if(!E.ok||!W){const Ie=typeof(W==null?void 0:W.error)=="string"&&W.error.trim()||typeof(W==null?void 0:W.message)=="string"&&W.message.trim()||`Activity paging failed (${E.status})`;throw new Error(Ie)}const V=Array.isArray(W.activities)?W.activities:[],Y=V.filter(Ie=>!h||fc(Ie)===h);xi("PAGE_FETCH",{cursor:O,rawCount:V.length,afterFilter:Y.length,filteredOut:V.length-Y.length,initiativeId:h,runId:p,nextCursor:W.nextCursor??null}),A(Ie=>{const De=Ho(Ie,Y);return xi("PAGE_MERGE",{prevCount:Ie.length,pageCount:Y.length,nextCount:De.length,added:De.length-Ie.length}),De}),se(W.nextCursor??null),P(W.storeUpdatedAt??null),be(null)}catch(Ne){const E=Ne instanceof Error?Ne.message:"";be(E?Xt(E):"Activity paging failed"),se(W=>W===""?null:W)}finally{L(!1),xe.current=null}})();return xe.current=me,me},[O,u,h,d,y,p,N,k]);return o.useEffect(()=>{O===""&&(ne.current||(ne.current=!0,Le()))},[O,Le]),{items:H,hasMore:O!==null,isLoadingMore:M,error:ae,storeUpdatedAt:ie,loadMore:Le,cutoffEpoch:T,sinceIso:N,untilIso:k}}const vu="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",wu="".trim().toLowerCase()==="true"||"".trim()==="1",ku="".trim().toLowerCase()==="true"||"".trim()==="1",Iu={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Aa=null,Ko=!1,Vo=!1,lo=!1;function Nu(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ra(){return lo||!wu?!1:ku?!0:!Nu()}function ju(){return ra()?(Aa||(Aa=sn(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(lo=!0,null))),Aa):Promise.resolve(null)}function Au(e){if(Ko)return!0;try{return e.init(vu,Iu),Ko=!0,!0}catch{return lo=!0,!1}}async function co(){const e=await ju();return!e||!Au(e)?null:e}function _u(e){if(typeof window>"u")return;const t=window;if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(()=>e(),{timeout:1500});return}window.setTimeout(e,1)}function Su(){!ra()||typeof window>"u"||Vo||(Vo=!0,_u(()=>{co()}))}function Cu(e){if(!ra())return;const t=e.trim();t&&co().then(s=>{if(s)try{s.identify(t)}catch{}})}function js(e,t){ra()&&e.trim()&&co().then(s=>{if(s)try{s.capture(e,t)}catch{}})}function oi(e,t){const s=e.hasApiKey&&e.connectionVerified,i={...e,...t};return s&&(t.status==="pairing"||t.status==="awaiting_browser_auth")?(i.hasApiKey=!0,i.connectionVerified=!0,i.workspaceName=e.workspaceName??t.workspaceName??null):!t.workspaceName&&e.workspaceName&&(i.workspaceName=e.workspaceName),(!t.installationId||t.installationId.trim().length===0)&&e.installationId&&(i.installationId=e.installationId),(t.keySource==="none"||!t.keySource)&&e.keySource&&e.keySource!=="none"&&(i.keySource=e.keySource),i}const Us="https://orgx.mintlify.site/guides/openclaw-plugin-setup",Tu=1500,Mu=680,Eu=`<!doctype html>
|
|
3
|
+
<html lang="en">
|
|
4
|
+
<head>
|
|
5
|
+
<meta charset="utf-8" />
|
|
6
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
7
|
+
<title>Connecting to OrgX</title>
|
|
8
|
+
<style>
|
|
9
|
+
:root {
|
|
10
|
+
--bg: #02040a;
|
|
11
|
+
--surface: #0c0e14;
|
|
12
|
+
--surface-soft: #0f121a;
|
|
13
|
+
--line: rgba(255, 255, 255, 0.1);
|
|
14
|
+
--text: #f2f7ff;
|
|
15
|
+
--muted: rgba(242, 247, 255, 0.62);
|
|
16
|
+
--lime: #bfff00;
|
|
17
|
+
--teal: #14b8a6;
|
|
18
|
+
--iris: #7c7cff;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
* { box-sizing: border-box; }
|
|
22
|
+
|
|
23
|
+
body {
|
|
24
|
+
margin: 0;
|
|
25
|
+
min-height: 100vh;
|
|
26
|
+
background:
|
|
27
|
+
radial-gradient(920px 460px at 14% 14%, rgba(124, 124, 255, 0.12), transparent 68%),
|
|
28
|
+
radial-gradient(840px 420px at 84% 88%, rgba(20, 184, 166, 0.12), transparent 72%),
|
|
29
|
+
var(--bg);
|
|
30
|
+
color: var(--text);
|
|
31
|
+
font-family: "SF Pro Text", "SF Pro Display", Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
32
|
+
display: grid;
|
|
33
|
+
place-items: center;
|
|
34
|
+
padding: 24px;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
.shell {
|
|
38
|
+
width: min(640px, 100%);
|
|
39
|
+
border-radius: 22px;
|
|
40
|
+
border: 1px solid var(--line);
|
|
41
|
+
background:
|
|
42
|
+
linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.015)),
|
|
43
|
+
var(--surface);
|
|
44
|
+
box-shadow:
|
|
45
|
+
0 28px 80px rgba(0, 0, 0, 0.58),
|
|
46
|
+
inset 0 1px 0 rgba(255, 255, 255, 0.05);
|
|
47
|
+
overflow: hidden;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
.header {
|
|
51
|
+
display: flex;
|
|
52
|
+
align-items: center;
|
|
53
|
+
justify-content: space-between;
|
|
54
|
+
gap: 12px;
|
|
55
|
+
padding: 16px 18px;
|
|
56
|
+
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
|
57
|
+
background: rgba(0, 0, 0, 0.16);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
.brand {
|
|
61
|
+
display: inline-flex;
|
|
62
|
+
align-items: center;
|
|
63
|
+
gap: 10px;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
.brand-mark {
|
|
67
|
+
width: 22px;
|
|
68
|
+
height: 22px;
|
|
69
|
+
color: var(--lime);
|
|
70
|
+
opacity: 0.95;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
.brand-name {
|
|
74
|
+
font-size: 14px;
|
|
75
|
+
font-weight: 700;
|
|
76
|
+
letter-spacing: 0.01em;
|
|
77
|
+
color: rgba(242, 247, 255, 0.92);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
.chip {
|
|
81
|
+
display: inline-flex;
|
|
82
|
+
align-items: center;
|
|
83
|
+
gap: 6px;
|
|
84
|
+
border: 1px solid rgba(191, 255, 0, 0.3);
|
|
85
|
+
background: rgba(191, 255, 0, 0.12);
|
|
86
|
+
color: #d8ffa1;
|
|
87
|
+
border-radius: 999px;
|
|
88
|
+
padding: 4px 10px;
|
|
89
|
+
font-size: 11px;
|
|
90
|
+
font-weight: 600;
|
|
91
|
+
letter-spacing: 0.06em;
|
|
92
|
+
text-transform: uppercase;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
.dot {
|
|
96
|
+
width: 7px;
|
|
97
|
+
height: 7px;
|
|
98
|
+
border-radius: 50%;
|
|
99
|
+
background: var(--lime);
|
|
100
|
+
box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56);
|
|
101
|
+
animation: pulse 1.6s infinite ease-out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
.content {
|
|
105
|
+
padding: 20px 20px 18px;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
h1 {
|
|
109
|
+
margin: 0;
|
|
110
|
+
font-size: 24px;
|
|
111
|
+
line-height: 1.18;
|
|
112
|
+
letter-spacing: -0.02em;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
.subtitle {
|
|
116
|
+
margin: 8px 0 0;
|
|
117
|
+
color: var(--muted);
|
|
118
|
+
font-size: 14px;
|
|
119
|
+
line-height: 1.5;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
.steps {
|
|
123
|
+
margin-top: 16px;
|
|
124
|
+
display: grid;
|
|
125
|
+
gap: 8px;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
.step {
|
|
129
|
+
display: flex;
|
|
130
|
+
align-items: center;
|
|
131
|
+
gap: 9px;
|
|
132
|
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
|
133
|
+
background: var(--surface-soft);
|
|
134
|
+
border-radius: 12px;
|
|
135
|
+
padding: 10px 12px;
|
|
136
|
+
font-size: 12px;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
.step svg {
|
|
140
|
+
flex-shrink: 0;
|
|
141
|
+
width: 14px;
|
|
142
|
+
height: 14px;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
.meta {
|
|
146
|
+
margin-top: 12px;
|
|
147
|
+
padding-top: 12px;
|
|
148
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
149
|
+
color: rgba(242, 247, 255, 0.42);
|
|
150
|
+
font-size: 11px;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
@keyframes pulse {
|
|
154
|
+
0% { box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56); }
|
|
155
|
+
100% { box-shadow: 0 0 0 12px rgba(191, 255, 0, 0); }
|
|
156
|
+
}
|
|
157
|
+
</style>
|
|
158
|
+
</head>
|
|
159
|
+
<body>
|
|
160
|
+
<main class="shell">
|
|
161
|
+
<header class="header">
|
|
162
|
+
<div class="brand">
|
|
163
|
+
<svg class="brand-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
164
|
+
<path d="M5.5 7h5.8l6.7 6"></path>
|
|
165
|
+
<path d="M5.5 17h5.8l6.7-6"></path>
|
|
166
|
+
<path d="M5.5 12h12.5"></path>
|
|
167
|
+
<path d="m15.3 9.3 2.7 2.7-2.7 2.7"></path>
|
|
168
|
+
</svg>
|
|
169
|
+
<span class="brand-name">OrgX</span>
|
|
170
|
+
</div>
|
|
171
|
+
<div class="chip"><span class="dot"></span>Pairing</div>
|
|
172
|
+
</header>
|
|
173
|
+
<section class="content">
|
|
174
|
+
<h1>Connecting to OrgX</h1>
|
|
175
|
+
<p class="subtitle">Preparing a secure workspace session. This window will continue automatically.</p>
|
|
176
|
+
<div class="steps">
|
|
177
|
+
<div class="step">
|
|
178
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="#7C7CFF" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
179
|
+
<circle cx="12" cy="12" r="9"></circle>
|
|
180
|
+
<circle cx="12" cy="12" r="4.5"></circle>
|
|
181
|
+
</svg>
|
|
182
|
+
<span>Initializing plugin handshake</span>
|
|
183
|
+
</div>
|
|
184
|
+
<div class="step">
|
|
185
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="#14B8A6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
186
|
+
<path d="M5 3v18"></path>
|
|
187
|
+
<path d="m5 4 12 1-2 4 2 4-12-1z"></path>
|
|
188
|
+
</svg>
|
|
189
|
+
<span>Opening browser approval for this workspace</span>
|
|
190
|
+
</div>
|
|
191
|
+
<div class="step">
|
|
192
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="#BFFF00" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
193
|
+
<rect x="4" y="4" width="16" height="16" rx="4"></rect>
|
|
194
|
+
<path d="M9 12.2 11 14.2 15.2 10"></path>
|
|
195
|
+
</svg>
|
|
196
|
+
<span>Syncing initiatives, tasks, and decisions</span>
|
|
197
|
+
</div>
|
|
198
|
+
</div>
|
|
199
|
+
<div class="meta">If redirect does not start, return to OpenClaw and click “Approve in browser”.</div>
|
|
200
|
+
</section>
|
|
201
|
+
</main>
|
|
202
|
+
</body>
|
|
203
|
+
</html>`,Xa={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Us,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Ru(e,t){return e.hasApiKey||e.connectionVerified||e.workspaceName?{...e,lastError:t,nextAction:e.nextAction??"connect"}:{...Xa,status:"error",lastError:t,nextAction:"retry"}}function _a(e){if(typeof e=="string")return Xt(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Xt(t.error);if(typeof t.message=="string")return Xt(t.message)}}async function li(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:_a(s==null?void 0:s.error)??_a(s==null?void 0:s.message)??_a(s)??Xt(`Request failed (${t.status})`)}}function Ri(e){if(e)try{Cu(e)}catch{}}function Lu(){const[e,t]=o.useState(Xa),s=o.useRef(e),[i,r]=o.useState(!0),[a,l]=o.useState(!1),[c,d]=o.useState(!1),u=o.useRef(null),[p,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(hr)==="1");o.useEffect(()=>{s.current=e},[e]),o.useEffect(()=>{!zi()&&p&&h(!1)},[p]);const y=o.useCallback(async()=>{const _=await li(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!_.ok||!_.data){const A=_.error??"Failed to load onboarding state",O=Ru(s.current,A);return t(O),O}const H={...oi(s.current,_.data),docsUrl:_.data.docsUrl??s.current.docsUrl??Us};return Ri(H.installationId??null),t(H),H},[]);o.useEffect(()=>{let _=!1;return(async()=>{r(!0);const H=await y();_||(t(H),r(!1))})(),()=>{_=!0}},[y]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"||e.status==="connected"&&typeof e.pairingId=="string"&&e.pairingId.trim().length>0&&typeof e.connectUrl=="string"&&e.connectUrl.trim().length>0))return;const H=Math.max(900,e.pollIntervalMs??Tu),A=window.setInterval(async()=>{const O=await li(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(O.ok&&O.data){const se={...oi(s.current,O.data),docsUrl:O.data.docsUrl??s.current.docsUrl??Us};Ri(se.installationId??null),t(se)}},H);return()=>{window.clearInterval(A)}},[e.connectUrl,e.connectionVerified,e.pairingId,e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(!zi()){window.localStorage.removeItem(hr);return}if(p){window.localStorage.setItem(hr,"1");return}window.localStorage.removeItem(hr)}},[p]);const g=o.useCallback(()=>{if(typeof window>"u")return null;try{const _=window.open("","_blank");return _?(_.opener=null,_.document.title="Connecting to OrgX…",_.document.open(),_.document.write(Eu),_.document.close(),_):null}catch{return null}},[]),w=o.useCallback(async()=>{const _=g();u.current=_,l(!0);try{const H=await li(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),A=H.data;if(!H.ok||!(A!=null&&A.state)){_&&!_.closed&&_.close();const se=H.error??"Could not start pairing";t(M=>({...M,status:"error",lastError:se,nextAction:"enter_manual_key"}));return}t({...oi(s.current,A.state),docsUrl:A.state.docsUrl??s.current.docsUrl??Us});const O=A.connectUrl;if(O){const se=u.current;let M=!1;if(se&&!se.closed)try{window.setTimeout(()=>{if(!se.closed)try{se.location.href=O}catch{}},Mu),M=!0}catch{M=!1}M||(M=!!window.open(O,"_blank","noopener,noreferrer")),M||t(L=>({...L,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{u.current=null,l(!1)}},[g]),N=o.useCallback(async _=>{d(!0);try{const H=_.trim(),A=H.replace(/^[a-z]+_/i,""),O=Array.from(new Set([H,A?`oxk_${A}`:"",A?`orgx_${A}`:""].map(M=>M.trim()).filter(M=>M.length>0)));let se="Manual key validation failed";for(const M of O){const L={"Content-Type":"application/json","X-OrgX-Api-Key":M,Authorization:`Bearer ${M}`},ae=await li(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:L,body:JSON.stringify({apiKey:M})}));if(ae.ok&&ae.data){const be={...oi(s.current,ae.data),docsUrl:ae.data.docsUrl??s.current.docsUrl??Us};return Ri(be.installationId??null),t(be),be}se=ae.error??se}throw t(M=>({...M,status:"manual_key",lastError:se,nextAction:"enter_manual_key"})),new Error(se)}finally{d(!1)}},[]),k=o.useCallback(async()=>{const _=await li(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(_.ok&&_.data){const A={...oi(s.current,_.data),docsUrl:_.data.docsUrl??s.current.docsUrl??Us};return Ri(A.installationId??null),t(A),A}const H={...Xa,status:"idle"};return t(H),H},[]),T=o.useCallback(async()=>{const _=await li(fetch("/orgx/api/onboarding/cancel",{method:"POST"}));if(_.ok&&_.data){const A={...oi(s.current,_.data),docsUrl:_.data.docsUrl??s.current.docsUrl??Us};return Ri(A.installationId??null),t(A),A}const H=await y();return t(H),H},[y]),D=o.useCallback(()=>{t(_=>({..._,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),b=o.useMemo(()=>e.hasApiKey&&e.connectionVerified&&(e.status==="connected"||e.status==="pairing"||e.status==="awaiting_browser_auth")?!1:!(p&&zi()),[p,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:b,isLoading:i,isStarting:a,isSubmittingManual:c,refreshStatus:y,startPairing:w,submitManualKey:N,cancelPairing:T,disconnect:k,skipGate:()=>h(!0),resumeGate:()=>h(!1),backToPairing:D,setManualMode:()=>t(_=>({..._,status:"manual_key",nextAction:"enter_manual_key"}))}}const rs={liveData:e=>["live-data",{authToken:e.authToken??null,embedMode:e.embedMode??!1,useMock:e.useMock??!1,projectId:e.projectId??null}],sessions:e=>["sessions",{activeMinutes:e.activeMinutes??null,limit:e.limit??null,authToken:e.authToken??null,embedMode:e.embedMode??!1}],initiativeDetails:e=>["initiative-details",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],entities:e=>["entities",{type:e.type,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null}],missionControlGraph:e=>["mission-control-graph",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],missionControlSlices:e=>{var t;return["mission-control-slices",{workspaceId:e.workspaceId??null,initiativeId:e.initiativeId??null,level:e.level,orderMode:e.orderMode??null,includeCompleted:e.includeCompleted??!1,search:((t=e.search)==null?void 0:t.trim().toLowerCase())??"",offset:Math.max(0,e.offset??0),limit:Math.max(1,e.limit??24),authToken:e.authToken??null,embedMode:e.embedMode??!1}]},nextUpQueue:e=>["mission-control-next-up",{initiativeId:e.initiativeId??null,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null,offset:Math.max(0,e.offset??0),limit:Math.max(1,Math.min(300,e.limit??24))}],autoContinueStatus:e=>["auto-continue-status",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],liveInitiatives:e=>["live-initiatives",{limit:(e==null?void 0:e.limit)??300,projectId:(e==null?void 0:e.projectId)??null}],initiativeSearch:e=>["initiative-search",{query:e.query.trim().toLowerCase(),projectId:e.projectId??null}],artifactsByEntity:e=>["artifacts-by-entity",{entityType:e.entityType,entityId:e.entityId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],artifactDetail:e=>["artifact-detail",{artifactId:e.artifactId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],triageQueue:e=>["triage-queue",{workspaceId:e.workspaceId??null,status:e.status??"open",authToken:e.authToken??null,embedMode:e.embedMode??!1}]};class Du extends Error{constructor(s,i){super(s);ss(this,"code","upgrade_required");ss(this,"currentPlan");ss(this,"requiredPlan");ss(this,"actions");this.name="UpgradeRequiredError",this.currentPlan=(i==null?void 0:i.currentPlan)??null,this.requiredPlan=((i==null?void 0:i.requiredPlan)??"starter").trim()||"starter",this.actions=(i==null?void 0:i.actions)??null}}function $u(e){if(!e||typeof e!="object")return null;const t=e;if(t.code!=="upgrade_required")return null;const s=typeof t.error=="string"&&t.error.trim()?t.error.trim():"Upgrade required.";return new Du(s,{currentPlan:typeof t.currentPlan=="string"&&t.currentPlan.trim()?t.currentPlan.trim():null,requiredPlan:typeof t.requiredPlan=="string"&&t.requiredPlan.trim()?t.requiredPlan.trim():null,actions:t.actions??null})}function qx(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}class hc extends Error{constructor(s){super(s.message);ss(this,"status");ss(this,"code");ss(this,"errorLocation");ss(this,"retryable");ss(this,"details");this.name="MissionControlApiError",this.status=s.status,this.code=s.code??null,this.errorLocation=s.errorLocation??null,this.retryable=s.retryable??!1,this.details=s.details??null}}function Pu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Gi(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function Ou(e,t){if(e.status!==404)return!1;const s=Gi(t,["error"])??"",i=Gi(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${i}`)}function qu(e,t,s){if(Ou(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const i=Gi(t,["error","message"])??`${s} (${e.status})`;return Xt(i)}function Sa(e,t,s){const i=Pu(t),r=qu(e,i,s),a=Gi(i,["code"]),l=Gi(i,["error_location","errorLocation"]),c=i==null?void 0:i.retryable,d=typeof c=="boolean"?c:!1;return new hc({message:r,status:e.status,code:a,errorLocation:l,retryable:d,details:i})}function Fx(e){return e instanceof hc}const gc=750;async function Qa(e,t){const{initiativeId:s=null,projectId:i=null,authToken:r=null,embedMode:a=!1,queueQueryKey:l,includeQueue:c=!0,includeGraph:d=!0,includeSlices:u=!0,includeAutoContinue:p=!0,includeLiveData:h=!0}=t,y=[];c&&(l?y.push(e.invalidateQueries({queryKey:l})):y.push(e.invalidateQueries({queryKey:["mission-control-next-up"]}))),d&&y.push(e.invalidateQueries({queryKey:rs.missionControlGraph({initiativeId:s,authToken:r,embedMode:a})})),u&&y.push(e.invalidateQueries({queryKey:["mission-control-slices"]})),p&&y.push(e.invalidateQueries({queryKey:rs.autoContinueStatus({initiativeId:s,authToken:r,embedMode:a})})),h&&(y.push(e.invalidateQueries({queryKey:rs.liveData({authToken:r,embedMode:a,projectId:i})})),y.push(e.invalidateQueries({queryKey:["live-data"]}))),await Promise.all(y)}function Fu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Bu(e){const t=Fu(e.run),s=Array.isArray(t==null?void 0:t.activeSliceRunIds)?t.activeSliceRunIds.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[],i=typeof(t==null?void 0:t.activeRunId)=="string"&&t.activeRunId.trim()||s[0]||typeof e.sessionId=="string"&&e.sessionId.trim()||null,r=typeof(t==null?void 0:t.activeTaskId)=="string"&&t.activeTaskId.trim()||null,a=typeof(t==null?void 0:t.stopReason)=="string"&&t.stopReason.trim()||null;return{status:typeof(t==null?void 0:t.status)=="string"&&t.status.trim()||null,stopReason:a,activeRunId:i,activeTaskId:r,activeRunIds:s}}function gr(e,t){return e&&{...e,pages:e.pages.map(s=>({...s,items:s.items.map(i=>t(i))}))}}async function xr(e){return await e.json().catch(()=>null)}function Uu(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",i=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${i}`)}function zu(e,t,s){if(Uu(e,t))return`${s}. This queue route is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const i=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||s;return Xt(i)}function Wu(e,t){const s=e instanceof Error?e.message:"",i=s.trim().toLowerCase();return i.includes("timed out")||i.includes("timeout")||i.includes("request cancelled")||i.includes("signal is aborted")?`${t}. Request timed out while waiting for queue data.`:i.includes("failed to fetch")||i.includes("network")?`${t}. Unable to reach the queue service right now.`:s?Xt(s):t}function Hu(e){const t=new Date().toISOString(),s=l=>new Date(Date.now()-l*6e4).toISOString(),i=(l,c,d)=>({status:l,activeTaskId:(d==null?void 0:d.activeTaskId)??null,activeRunId:(d==null?void 0:d.activeRunId)??null,stopReason:(d==null?void 0:d.stopReason)??null,maxParallelSlices:(d==null?void 0:d.maxParallelSlices)??3,parallelMode:(d==null?void 0:d.parallelMode)??"iwmt",updatedAt:c}),r=[{initiativeId:"init-1",initiativeTitle:"Content Engine: Dogfood the Larry Playbook",initiativeStatus:"active",initiativePriority:"critical",initiativePriorityNum:11,workstreamId:"ws-content-1",workstreamTitle:"Long-form article generation",workstreamStatus:"in_progress",nextTaskId:"task-content-13",nextTaskTitle:"Apply editorial revisions for sections 3-4",nextTaskPriority:1,nextTaskDueAt:s(-35),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-content-12","task-content-13"],sliceTaskCount:2,executionPolicy:{domain:"content",requiredSkills:["editorial-review","voice-consistency"],profile:"quality-first",sliceScopePreference:"task",maxSliceTasks:2,maxParallelAgents:2,dependencyMode:"strict"},autoContinue:i("running",s(4),{activeTaskId:"task-content-13",activeRunId:"run-101",maxParallelSlices:2})},{initiativeId:"init-1",initiativeTitle:"Content Engine: Dogfood the Larry Playbook",initiativeStatus:"active",initiativePriority:"critical",initiativePriorityNum:12,workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",workstreamStatus:"blocked",nextTaskId:"task-legal-2",nextTaskTitle:"Approve legal-safe copy variant",nextTaskPriority:1,nextTaskDueAt:s(-20),runnerAgentId:"holt",runnerAgentName:"Holt",runnerAgents:[{id:"holt",name:"Holt"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Waiting on legal-safe variant decision from you",queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-legal-2"],sliceTaskCount:1,autoContinue:i("stopped",s(7),{stopReason:"blocked",maxParallelSlices:2})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:24,workstreamId:"ws-ux-devmode",workstreamTitle:"Developer-mode feature gating",workstreamStatus:"in_progress",nextTaskId:"task-ux-33",nextTaskTitle:"Capture final mobile + desktop verification",nextTaskPriority:1,nextTaskDueAt:s(-15),runnerAgentId:"holt",runnerAgentName:"Holt",runnerAgents:[{id:"holt",name:"Holt"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"workstream",sliceTaskIds:["task-ux-31","task-ux-32","task-ux-33"],sliceTaskCount:3,autoContinue:i("running",s(2),{activeTaskId:"task-ux-33",activeRunId:"run-202"})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:26,workstreamId:"ws-ux-activity",workstreamTitle:"Activity feed readability pass",workstreamStatus:"in_progress",nextTaskId:"task-ux-19",nextTaskTitle:"Finalize hierarchy labels and evidence chips",nextTaskPriority:2,nextTaskDueAt:s(-28),runnerAgentId:"dana",runnerAgentName:"Dana",runnerAgents:[{id:"dana",name:"Dana"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-ux-18","task-ux-19"],sliceTaskCount:2,autoContinue:i("running",s(6),{activeTaskId:"task-ux-19",activeRunId:"run-201"})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:27,workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",workstreamStatus:"blocked",nextTaskId:"task-ux-41",nextTaskTitle:"Apply approved collapsed spacing token",nextTaskPriority:1,nextTaskDueAt:s(-12),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Decision required: choose 8px or 0px collapsed spacing",queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-ux-41"],sliceTaskCount:1,autoContinue:i("stopped",s(2),{stopReason:"blocked"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:41,workstreamId:"ws-directory-import",workstreamTitle:"Enrichment import pipeline",workstreamStatus:"in_progress",nextTaskId:"task-dir-12",nextTaskTitle:"Finish vendor retry batch after cooldown",nextTaskPriority:2,nextTaskDueAt:s(-45),runnerAgentId:"pace",runnerAgentName:"Pace",runnerAgents:[{id:"pace",name:"Pace"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-11","task-dir-12"],sliceTaskCount:2,autoContinue:i("running",s(3),{activeTaskId:"task-dir-12",activeRunId:"run-301"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:43,workstreamId:"ws-directory-qa",workstreamTitle:"Reference verification QA lane",workstreamStatus:"in_progress",nextTaskId:"task-dir-qa-2",nextTaskTitle:"Reconcile citation mismatches and publish QA memo",nextTaskPriority:2,nextTaskDueAt:s(-38),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-qa-1","task-dir-qa-2"],sliceTaskCount:2,autoContinue:i("running",s(5),{activeTaskId:"task-dir-qa-2",activeRunId:"run-302"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:45,workstreamId:"ws-directory-outreach",workstreamTitle:"External partner outreach copy",workstreamStatus:"in_progress",nextTaskId:"task-dir-outreach-2",nextTaskTitle:"Finalize outreach sequence copy",nextTaskPriority:3,nextTaskDueAt:s(-52),runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-outreach-1","task-dir-outreach-2"],sliceTaskCount:2,autoContinue:i("running",s(8),{activeTaskId:"task-dir-outreach-2",activeRunId:"run-303"})},{initiativeId:"init-5",initiativeTitle:"Incident Replay & Reliability",initiativeStatus:"blocked",initiativePriority:"critical",initiativePriorityNum:8,workstreamId:"ws-reliability-replay",workstreamTitle:"Incident replay reconstruction",workstreamStatus:"blocked",nextTaskId:"task-rel-44",nextTaskTitle:"Approve snapshot restore and rerun replay",nextTaskPriority:1,nextTaskDueAt:s(-10),runnerAgentId:"ops",runnerAgentName:"Ops",runnerAgents:[{id:"ops",name:"Ops"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Archive restore approval needed to continue replay",queueOrigin:"system",sliceScope:"milestone",sliceTaskIds:["task-rel-44"],sliceTaskCount:1,sliceMilestoneId:"mile-rel-9",autoContinue:i("stopped",s(25),{stopReason:"blocked",maxParallelSlices:1})},{initiativeId:"init-4",initiativeTitle:"Revenue Expansion Q2",initiativeStatus:"completed",initiativePriority:"low",initiativePriorityNum:74,workstreamId:"ws-revenue-closeout",workstreamTitle:"Revenue Expansion Q2 closeout",workstreamStatus:"completed",nextTaskId:null,nextTaskTitle:"Completed",nextTaskPriority:null,nextTaskDueAt:null,runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"completed",blockReason:null,queueOrigin:"system",sliceScope:"milestone",sliceTaskIds:["task-revenue-19"],sliceTaskCount:1,sliceMilestoneId:"mile-revenue-4",autoContinue:i("stopped",s(40),{stopReason:"completed",maxParallelSlices:1})}],a=typeof e=="string"&&e.trim().length>0?r.filter(l=>l.initiativeId===e.trim()):r;return Ya({ok:!0,generatedAt:t,total:a.length,items:a,pagination:{offset:0,limit:a.length||1,total:a.length,nextCursor:null,hasMore:!1},degraded:[]})}function Ku(e){var s,i;const t=((s=e.autoContinue)==null?void 0:s.status)??"stopped";return t==="running"?"running":t==="stopping"?"stopping":((i=e.autoContinue)==null?void 0:i.stopReason)==="error"?"error":"idle"}function Vu(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function xc(e){const t=typeof e=="string"?e.trim():"";if(!t)return"unassigned";const s=t.toLowerCase();return s==="undefined"||s==="null"||s==="main"?"unassigned":t}function yc(e,t){const s=typeof e=="string"?e.trim():"";if(!s)return t==="unassigned"?"Unassigned":t;const i=s.toLowerCase();return i==="undefined"||i==="null"||i==="main"&&t==="unassigned"?t==="unassigned"?"Unassigned":t:s}function Gu(e,t,s){if(!Array.isArray(e))return t==="unassigned"?[]:[{id:t,name:s}];const i=[],r=new Set;for(const a of e){if(!a||typeof a!="object"||Array.isArray(a))continue;const l=a,c=xc(typeof l.id=="string"?l.id:null),d=yc(typeof l.name=="string"?l.name:null,c);if(c==="unassigned"&&d==="Unassigned")continue;const u=c.toLowerCase();r.has(u)||(r.add(u),i.push({id:c,name:d}))}return i.length===0&&t!=="unassigned"?[{id:t,name:s}]:i}function Xu(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Qu(e){const t=xc(e.runnerAgentId),s=yc(e.runnerAgentName,t),i=Gu(e.runnerAgents,t,s),r=i[0]??null,a=(r==null?void 0:r.id)??t,l=(r==null?void 0:r.name)??s,c=Xu(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(p=>typeof p=="string"&&p.trim().length>0):e.nextTaskId?[e.nextTaskId]:[],u=e.sliceScope==="workstream"||e.sliceScope==="milestone"||e.sliceScope==="task"?e.sliceScope:null;return{...e,runnerAgentId:a,runnerAgentName:l,runnerAgents:i,runnerSource:c,playbackState:e.queueState,autoIntentEnabled:Vu(e),autoRuntimeState:Ku(e),queueOrigin:e.queueOrigin??"system",sliceScope:u,sliceTaskIds:d,sliceTaskCount:typeof e.sliceTaskCount=="number"&&Number.isFinite(e.sliceTaskCount)?Math.max(0,Math.floor(e.sliceTaskCount)):d.length,executionPolicy:e.executionPolicy??null}}function Ya(e){var u,p,h,y,g;const t=e.items.map(w=>Qu(w)),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(e.total,t.length):t.length,i=e.pagination&&typeof e.pagination=="object"?e.pagination:null,r=i&&Number.isFinite(i.offset)?Math.max(0,Math.floor(i.offset)):0,a=i&&Number.isFinite(i.limit)?Math.max(1,Math.floor(i.limit)):Math.max(1,t.length),l=r+a<s,c=i&&typeof i.hasMore=="boolean"?i.hasMore:l,d=i&&typeof i.nextCursor=="string"?i.nextCursor:c?String(r+a):null;return{...e,items:t,total:s,summary:e.summary?{visibleTotal:typeof e.summary.visibleTotal=="number"&&Number.isFinite(e.summary.visibleTotal)?Math.max(0,Math.floor(e.summary.visibleTotal)):t.filter(w=>w.queueState!=="running"&&w.queueState!=="completed").length,stateCounts:{queued:Math.max(0,Math.floor(((u=e.summary.stateCounts)==null?void 0:u.queued)??0)),running:Math.max(0,Math.floor(((p=e.summary.stateCounts)==null?void 0:p.running)??0)),blocked:Math.max(0,Math.floor(((h=e.summary.stateCounts)==null?void 0:h.blocked)??0)),idle:Math.max(0,Math.floor(((y=e.summary.stateCounts)==null?void 0:y.idle)??0)),completed:Math.max(0,Math.floor(((g=e.summary.stateCounts)==null?void 0:g.completed)??0))}}:void 0,pagination:{offset:r,limit:a,total:s,nextCursor:d,hasMore:c}}}function Yu(e){const t=new Map;for(const s of e){const i=t.get(s.initiativeId);if(i){i.workstreamCount+=1,i.workstreamIds.push(s.workstreamId),i.items.push(s);for(const a of s.runnerAgents??[])i.runnerAgents.some(l=>l.id===a.id)||i.runnerAgents.push(a);const r=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;r(s.queueState)>r(i.queueState)&&(i.queueState=s.queueState)}else t.set(s.initiativeId,{initiativeId:s.initiativeId,initiativeTitle:s.initiativeTitle??s.initiativeId,initiativeStatus:s.initiativeStatus??"active",initiativePriority:typeof s.initiativePriority=="string"?s.initiativePriority:null,initiativePriorityNum:typeof s.initiativePriorityNum=="number"?s.initiativePriorityNum:null,workstreamCount:1,workstreamIds:[s.workstreamId],runnerAgents:[...s.runnerAgents??[]],queueState:s.queueState,items:[s]})}return Array.from(t.values())}function Ju(e){return e.map(t=>({milestoneId:t.sliceMilestoneId??null,milestoneTitle:t.sliceMilestoneId?`Milestone ${t.sliceMilestoneId.slice(0,8)}`:t.workstreamTitle??"Workstream",workstreamId:t.workstreamId,workstreamTitle:t.workstreamTitle??t.workstreamId,initiativeId:t.initiativeId,initiativeTitle:t.initiativeTitle??t.initiativeId,taskCount:t.sliceTaskCount??0,queueState:t.queueState,item:t}))}function Zu({initiativeId:e=null,projectId:t=null,offset:s=0,limit:i=20,authToken:r=null,embedMode:a=!1,enabled:l=!0,snapshotVersion:c=null,zoomLevel:d="workstream"}){var ne,K,G,le,Le,Me,me,Ne;const u=ao(),p=Hn(),h=Math.max(0,s),y=Math.max(1,Math.min(300,i)),g=o.useRef(null);o.useEffect(()=>()=>{g.current&&(clearTimeout(g.current),g.current=null)},[]);const w=o.useMemo(()=>rs.nextUpQueue({initiativeId:e,projectId:t,offset:h,limit:y,authToken:r,embedMode:a}),[e,t,h,y,r,a]),N=o.useCallback((E,W)=>{const V=rs.autoContinueStatus({initiativeId:E,authToken:r,embedMode:a});u.setQueryData(V,Y=>{const Ie=Y&&typeof Y=="object"?Y:null;return{ok:!0,initiativeId:E,run:W,defaults:(Ie==null?void 0:Ie.defaults)??{tokenBudget:null,tickMs:0}}})},[r,a,u]),k=o.useRef(c);o.useEffect(()=>{c!==null&&k.current!==null&&c!==k.current&&u.invalidateQueries({queryKey:w}),k.current=c},[c,u,w]);const T=()=>{g.current&&(clearTimeout(g.current),g.current=null),g.current=setTimeout(()=>{g.current=null,u.invalidateQueries({queryKey:rs.liveData({authToken:r,embedMode:a,projectId:t})})},gc)},D=async({includeGraph:E=!0,includeLiveData:W=!0}={})=>{await Qa(u,{initiativeId:e,projectId:t,authToken:r,embedMode:a,queueQueryKey:w,includeGraph:E,includeSlices:!1,includeLiveData:!1}),W&&T()},b=async(E,W)=>{if(p)return Hu(e);const V=new URLSearchParams;e&&V.set("initiative_id",e),gs(V,t,{allTokenWhenMissing:!0}),V.set("offset",String(E)),V.set("limit",String(W));let Y;try{Y=await fetch(`/orgx/api/mission-control/next-up?${V.toString()}`,{headers:Ot({authToken:r,embedMode:a})})}catch(R){throw new Error(Wu(R,"Failed to load next up queue"))}const Ie=await xr(Y);if(!Y.ok){const R=zu(Y,Ie,"Failed to load next up queue");throw new Error(R)}const De=Ie??null;if(!De||De.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:E,limit:W,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(pu())return Ya(De);const he=De.items.filter(R=>!ki(R.initiativeId));return Ya({...De,items:he})},_=pd({queryKey:w,enabled:l,initialPageParam:h,queryFn:async({pageParam:E})=>{const W=typeof E=="number"&&Number.isFinite(E)?Math.max(0,Math.floor(E)):h;return await b(W,y)},getNextPageParam:E=>{const W=E.pagination;if(!(W!=null&&W.hasMore)||!W.nextCursor)return;const V=Number.parseInt(W.nextCursor,10);if(Number.isFinite(V))return Math.max(0,Math.floor(V))},refetchInterval:E=>{var Y;const W=(Y=E.state.data)==null?void 0:Y.pages;return!W||W.length===0?1e4:W.some(Ie=>Array.isArray(Ie.items)&&Ie.items.some(De=>De.queueState==="running"))?2500:8e3}}),H=Dn({mutationFn:async E=>{if(p)return{ok:!0,initiativeId:E.initiativeId,workstreamId:E.workstreamId,dispatchMode:"slice",sessionId:null};const W=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:E.initiativeId,workstreamId:E.workstreamId,workspaceId:t??void 0,agentId:E.agentId??void 0,scope:E.scope??void 0,maxParallelSlices:typeof E.maxParallelSlices=="number"&&Number.isFinite(E.maxParallelSlices)?Math.max(1,Math.floor(E.maxParallelSlices)):void 0,parallelMode:E.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),V=await xr(W);if(!W.ok)throw Sa(W,V,"Failed to dispatch queued workstream");return V??{ok:!0,initiativeId:E.initiativeId,workstreamId:E.workstreamId,agentId:E.agentId??void 0,dispatchMode:"none",sessionId:null}},onMutate:async()=>(await u.cancelQueries({queryKey:w}),{previous:u.getQueryData(w)}),onError:(E,W,V)=>{V!=null&&V.previous&&u.setQueryData(w,V.previous)},onSuccess:(E,W)=>{const V=Bu(E),Y=E.outcome==="started"||E.outcome==="fallback_started"||E.outcome==="dispatch_pending";W.initiativeId&&N(W.initiativeId,Y?{id:V.activeRunId??`${W.initiativeId}:${W.workstreamId}:play`,initiativeId:W.initiativeId,agentId:W.agentId??"auto",agentName:null,tokenBudget:null,tokensUsed:0,status:V.status==="stopping"?"stopping":"running",stopRequested:!1,updatedAt:new Date().toISOString(),startedAt:new Date().toISOString(),stoppedAt:null,lastError:null,lastTaskId:V.activeTaskId,lastRunId:V.activeRunId??null,activeTaskId:V.activeTaskId,activeRunId:V.activeRunId??null,stopReason:V.stopReason,activeSliceRunIds:V.activeRunIds,activeTaskIds:[],maxParallelSlices:W.maxParallelSlices??1,parallelMode:W.parallelMode??"iwmt"}:null),u.setQueryData(w,Ie=>gr(Ie,De=>De.initiativeId!==W.initiativeId||De.workstreamId!==W.workstreamId?De:{...De,queueState:E.outcome==="started"||E.outcome==="fallback_started"?"running":E.outcome==="slice_completed"?"completed":E.outcome==="slice_blocked"?"blocked":De.queueState,playbackState:E.outcome==="started"||E.outcome==="fallback_started"?"running":E.outcome==="slice_completed"?"completed":E.outcome==="slice_blocked"?"blocked":De.playbackState})),D({includeGraph:!1})}}),A=Dn({mutationFn:async E=>{if(p)return{ok:!0,initiativeId:E.initiativeId,workstreamIds:[E.workstreamId],run:null};const W={initiativeId:E.initiativeId,workspaceId:t??void 0,agentId:E.agentId??void 0,tokenBudgetTokens:E.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};E.scope==="workstream"&&E.workstreamId&&(W.workstreamIds=[E.workstreamId]),typeof E.maxParallelSlices=="number"&&Number.isFinite(E.maxParallelSlices)&&(W.maxParallelSlices=E.maxParallelSlices),E.parallelMode==="iwmt"&&(W.parallelMode=E.parallelMode);const V=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(W)}),Y=await xr(V);if(!V.ok){const Ie=$u(Y);throw Ie||Sa(V,Y,"Failed to start auto-continue")}return Y??{ok:!0,initiativeId:E.initiativeId,workstreamIds:[E.workstreamId],run:null}},onMutate:async()=>(await u.cancelQueries({queryKey:w}),{previous:u.getQueryData(w)}),onError:(E,W,V)=>{V!=null&&V.previous&&u.setQueryData(w,V.previous)},onSuccess:(E,W)=>{N(W.initiativeId,E.run??null),u.setQueryData(w,V=>gr(V,Y=>{var De;return Y.initiativeId!==W.initiativeId||!(Y.workstreamId===W.workstreamId||W.scope!=="workstream")?Y:{...Y,autoContinue:E.run?{status:E.run.status,activeTaskId:E.run.activeTaskId??null,activeRunId:E.run.activeRunId??((De=E.run.activeSliceRunIds)==null?void 0:De[0])??E.run.lastRunId??null,stopReason:E.run.stopReason,maxParallelSlices:E.run.maxParallelSlices,parallelMode:E.run.parallelMode,updatedAt:E.run.updatedAt}:Y.autoContinue}})),D({includeGraph:!1})}}),O=Dn({mutationFn:async E=>{if(p)return{ok:!0,initiativeId:E.initiativeId,run:null};const W=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:E.initiativeId})}),V=await xr(W);if(!W.ok)throw Sa(W,V,"Failed to stop auto-continue");return V??{ok:!0,initiativeId:E.initiativeId,run:null}},onMutate:async E=>{await u.cancelQueries({queryKey:w});const W=u.getQueryData(w);return u.setQueryData(w,gr(W,V=>V.initiativeId!==E.initiativeId||!V.autoContinue?V:{...V,autoContinue:{...V.autoContinue,status:"stopping",updatedAt:new Date().toISOString()}})),{previous:W}},onError:(E,W,V)=>{V!=null&&V.previous&&u.setQueryData(w,V.previous)},onSuccess:(E,W)=>{N(W.initiativeId,E.run??null),u.setQueryData(w,V=>gr(V,Y=>{var Ie;return Y.initiativeId!==W.initiativeId||!Y.autoContinue?Y:{...Y,autoContinue:E.run?{status:E.run.status,activeTaskId:E.run.activeTaskId??null,activeRunId:E.run.activeRunId??((Ie=E.run.activeSliceRunIds)==null?void 0:Ie[0])??E.run.lastRunId??null,stopReason:E.run.stopReason,maxParallelSlices:E.run.maxParallelSlices,parallelMode:E.run.parallelMode,updatedAt:E.run.updatedAt}:null}})),D({includeGraph:!1})}}),se=o.useMemo(()=>{var Y;const E=((Y=_.data)==null?void 0:Y.pages)??[];if(E.length===0)return[];const W=new Set,V=[];for(const Ie of E)for(const De of Ie.items){const he=`${De.initiativeId}:${De.workstreamId}`;W.has(he)||(W.add(he),V.push(De))}return V},[(ne=_.data)==null?void 0:ne.pages]),M=o.useMemo(()=>{var V;const E=((V=_.data)==null?void 0:V.pages)??[];let W=0;for(const Y of E)typeof Y.total=="number"&&Number.isFinite(Y.total)&&(W=Math.max(W,Y.total));return Math.max(W,se.length)},[se.length,(K=_.data)==null?void 0:K.pages]),L=o.useMemo(()=>{var he;const E=((he=_.data)==null?void 0:he.pages)??[];if(E.length===0)return null;const W=E[0],V=E[E.length-1],Y=W.pagination,Ie=V.pagination,De=!!_.hasNextPage;return{offset:Y&&Number.isFinite(Y.offset)?Math.max(0,Math.floor(Y.offset)):h,limit:Y&&Number.isFinite(Y.limit)?Math.max(1,Math.floor(Y.limit)):y,total:M,nextCursor:De?(Ie==null?void 0:Ie.nextCursor)??String(((Ie==null?void 0:Ie.offset)??h)+((Ie==null?void 0:Ie.limit)??y)):null,hasMore:De}},[M,y,h,(G=_.data)==null?void 0:G.pages,_.hasNextPage]),ae=((Le=(le=_.data)==null?void 0:le.pages[0])==null?void 0:Le.generatedAt)??null,be=o.useMemo(()=>{var Ie,De,he,je,R,Ae;const E=((Ie=_.data)==null?void 0:Ie.pages)??[];if(E.length===0)return null;let W=0;const V={queued:0,running:0,blocked:0,idle:0,completed:0};let Y=!1;for(const Se of E)Se.summary&&(Y=!0,W=Math.max(W,Se.summary.visibleTotal??0),V.queued=Math.max(V.queued,((De=Se.summary.stateCounts)==null?void 0:De.queued)??0),V.running=Math.max(V.running,((he=Se.summary.stateCounts)==null?void 0:he.running)??0),V.blocked=Math.max(V.blocked,((je=Se.summary.stateCounts)==null?void 0:je.blocked)??0),V.idle=Math.max(V.idle,((R=Se.summary.stateCounts)==null?void 0:R.idle)??0),V.completed=Math.max(V.completed,((Ae=Se.summary.stateCounts)==null?void 0:Ae.completed)??0));return Y?{visibleTotal:W,stateCounts:V}:null},[(Me=_.data)==null?void 0:Me.pages]),ie=o.useMemo(()=>{var V;const E=((V=_.data)==null?void 0:V.pages)??[],W=new Set;for(const Y of E)for(const Ie of Y.degraded??[])typeof Ie=="string"&&Ie.trim().length>0&&W.add(Ie);return Array.from(W)},[(me=_.data)==null?void 0:me.pages]),P=o.useMemo(()=>d==="initiative"?Yu(se):[],[se,d]),xe=o.useMemo(()=>d==="milestone"?Ju(se):[],[se,d]);return{items:se,total:M,summary:be,pagination:L,generatedAt:ae,degraded:ie,isLoading:_.isLoading,isFetching:_.isFetching,isFetchingNextPage:_.isFetchingNextPage,hasNextPage:!!_.hasNextPage,error:((Ne=_.error)==null?void 0:Ne.message)??null,refetch:_.refetch,fetchNextPage:_.fetchNextPage,playWorkstream:H.mutateAsync,startWorkstreamAutoContinue:A.mutateAsync,stopInitiativeAutoContinue:O.mutateAsync,isPlaying:H.isPending,isStartingAutoContinue:A.isPending,isStoppingAutoContinue:O.isPending,zoomLevel:d,initiativeGroups:P,milestoneGroups:xe}}async function Nn(e){return await e.json().catch(()=>null)}function hi(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",i=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${i}`)}function jn(e,t,s){if(hi(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable. Try again in a moment.`;const i=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||`${s}.`;return Xt(i)}function em(e){const t=e.authToken??null,s=e.embedMode??!1,i=e.projectId??null,r=Hn(),a=ao(),l=o.useRef(null);o.useEffect(()=>()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]);const c=()=>{l.current&&(clearTimeout(l.current),l.current=null),l.current=setTimeout(()=>{l.current=null,Qa(a,{projectId:i,authToken:t,embedMode:s,includeQueue:!1,includeGraph:!1,includeSlices:!1,includeAutoContinue:!1})},gc)},d=async()=>{await Qa(a,{projectId:i,authToken:t,embedMode:s}),c()},u=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId,placement:b.placement??"top"};const _=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(_.ok)return H;if(!hi(_,H))throw new Error(jn(_,H,"Failed to move Next Up item"));const A=new URLSearchParams;gs(A,i,{allTokenWhenMissing:!0});const O=await fetch(`/orgx/api/mission-control/next-up?${A.toString()}`,{headers:Ot({authToken:t,embedMode:s})}),se=await Nn(O);if(!O.ok)throw new Error(jn(O,se,"Failed to read queue for move fallback"));const L=(Array.isArray(se==null?void 0:se.items)?se.items:[]).map(xe=>{const ne=typeof(xe==null?void 0:xe.initiativeId)=="string"?xe.initiativeId:null,K=typeof(xe==null?void 0:xe.workstreamId)=="string"?xe.workstreamId:null;return!ne||!K?null:{initiativeId:ne,workstreamId:K}}).filter(xe=>!!xe);if(L.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const ae=L.findIndex(xe=>xe.initiativeId===b.initiativeId&&xe.workstreamId===b.workstreamId);if(ae===-1)return{ok:!0,fallback:"reorder-move-skip"};const[be]=L.splice(ae,1);(b.placement??"top")==="bottom"?L.push(be):L.unshift(be);const ie=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:L})}),P=await Nn(ie);if(!ie.ok)throw new Error(jn(ie,P,"Failed to move Next Up item with reorder fallback"));return P??{ok:!0,fallback:"reorder-move"}},p=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const _=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(_.ok)return H;if(hi(_,H)){const A=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),O=await Nn(A);if(!A.ok)throw new Error(jn(A,O,"Failed to remove item from queue with legacy fallback"));return O??{ok:!0,fallback:"next-up-unpin"}}throw new Error(jn(_,H,"Failed to remove item from queue"))},h=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const _=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok)throw new Error(jn(_,H,"Failed to pin Next Up item"))},onSuccess:()=>{d()}}),y=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const _=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok)throw new Error(jn(_,H,"Failed to unpin Next Up item"))},onSuccess:()=>{d()}}),g=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.order.length};const _=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok)throw new Error(jn(_,H,"Failed to reorder Next Up queue"))},onSuccess:()=>{d()}}),w=Dn({mutationFn:u,onSuccess:()=>{d()}}),N=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const _=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok){if(hi(_,H)){const A=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),O=await Nn(A);if(!A.ok)throw new Error(jn(A,O,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(jn(_,H,"Failed to stop triage"))}return H},onSuccess:()=>{d()}}),k=Dn({mutationFn:p,onSuccess:()=>{d()}}),T=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,cleared:!0};const _=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok){if(hi(_,H)&&b.initiativeId){const A=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),O=await Nn(A);if(!A.ok)throw new Error(jn(A,O,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(jn(_,H,"Failed to clear Next Up lifecycle state"))}return H},onSuccess:()=>{d()}}),D=Dn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.items.length,failed:0,errors:[],fallback:"demo"};const _=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await Nn(_);if(!_.ok){if(!hi(_,H))throw new Error(jn(_,H,"Failed to apply bulk queue action"));const A=await Promise.all(b.items.map(async L=>{try{return b.action==="remove"?await p(L):await u({initiativeId:L.initiativeId,workstreamId:L.workstreamId,placement:b.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ae){return{ok:!1,error:ae instanceof Error?ae.message:"Queue action failed"}}})),O=A.filter(L=>L.ok).length,se=A.length-O,M=A.filter(L=>!L.ok&&L.error).map(L=>L.error);return{ok:se===0,updated:O,failed:se,errors:M,fallback:"sequential"}}return H},onSuccess:()=>{d()}});return{pin:h.mutateAsync,unpin:y.mutateAsync,reorder:g.mutateAsync,move:w.mutateAsync,remove:k.mutateAsync,stopTriage:N.mutateAsync,clear:T.mutateAsync,bulk:D.mutateAsync,isPinning:h.isPending,isUnpinning:y.isPending,isReordering:g.isPending,isMoving:w.isPending,isRemoving:k.isPending,isStoppingTriage:N.isPending,isClearing:T.isPending,isBulking:D.isPending}}function bc(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function tm(e,t,s,i){const r=new URLSearchParams;e&&r.set("workspace_id",e),t&&r.set("status",t),r.set("limit","100");const a=`/orgx/api/live/triage?${r.toString()}`,l=await fetch(a,{headers:bc(s,i)});if(!l.ok){const c=await l.json().catch(()=>null),d=(c&&typeof c=="object"&&"error"in c&&typeof c.error=="string"?c.error:null)??(c&&typeof c=="object"&&"message"in c&&typeof c.message=="string"?c.message:null)??`Triage fetch failed (${l.status})`;throw new Error(Xt(String(d)))}return l.json()}async function nm(e,t,s,i){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:bc(s,i),body:JSON.stringify(t)});if(!l.ok){const c=await l.json().catch(()=>({})),d=c.error??c.message??`Action failed (${l.status})`;throw new Error(Xt(String(d)))}return l.json()}function sm(e={}){const{enabled:t=!0,workspaceId:s=null,status:i="open",authToken:r=null,embedMode:a=!1}=e,l=ao(),c=rs.triageQueue({workspaceId:s,status:i,authToken:r,embedMode:a}),d=ei({queryKey:c,queryFn:()=>tm(s,i,r,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=Dn({mutationFn:async({itemId:g,payload:w})=>nm(g,w,r,a),onSuccess:()=>{l.invalidateQueries({queryKey:c})}}),p=o.useCallback(async(g,w,N)=>u.mutateAsync({itemId:g,payload:{action:w,note:N==null?void 0:N.note,optionId:N==null?void 0:N.optionId,snoozeDurationMinutes:N==null?void 0:N.snoozeDurationMinutes}}),[u]),h=o.useMemo(()=>{var g,w,N;return{items:((g=d.data)==null?void 0:g.items)??[],total:((w=d.data)==null?void 0:w.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((N=d.data)==null?void 0:N.degraded)??[],refetch:d.refetch}},[d]),y=o.useMemo(()=>({performAction:p,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[p,u.isPending,u.error]);return{model:h,actions:y}}function fe(...e){return e.filter(Boolean).join(" ")}const q={lime:"#BFFF00",teal:"#14B8A6",cyan:"#0AD4C4",iris:"#7C7CFF",amber:"#F5B700",red:"#FF6B88",background:"#02040A",cardBg:"#08090D",cardBgElevated:"#0C0E14",cardBorderStrong:"rgba(255, 255, 255, 0.12)",textMuted:"#8F9AB7"},Fi={active:{border:"rgba(191, 255, 0, 0.28)",background:"rgba(191, 255, 0, 0.11)",text:"rgba(223, 255, 156, 0.9)"},done:{border:"rgba(20, 184, 166, 0.26)",background:"rgba(20, 184, 166, 0.11)",text:"rgba(135, 255, 233, 0.9)"},blocked:{border:"rgba(255, 107, 136, 0.28)",background:"rgba(255, 107, 136, 0.12)",text:"rgba(255, 195, 208, 0.9)"},planned:{border:"rgba(255, 255, 255, 0.16)",background:"rgba(255, 255, 255, 0.06)",text:"rgba(236, 241, 255, 0.74)"}},vc={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ja={Pace:"Product",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Go={engineering:{domain:"Engineering",color:"#BFFF00"},product:{domain:"Product",color:"#A78BFA"},design:{domain:"Design",color:"#FF00D4"},marketing:{domain:"Marketing",color:"#F5B700"},sales:{domain:"Sales",color:"#0AD4C4"},operations:{domain:"Operations",color:"#14B8A6"},orchestration:{domain:"Orchestrator",color:"#FF6B88"},orchestrator:{domain:"Orchestrator",color:"#FF6B88"}};function wc(e){if(Ja[e])return{domain:Ja[e],color:vc[e]??"rgba(255,255,255,0.4)"};const t=e.toLowerCase().replace(/[_\s-]+/g,"-");for(const[s,i]of Object.entries(Go))if(t===s||t===`${s}-agent`||t===`orgx-${s}`||t===`orgx-${s}-agent`)return i;for(const[s,i]of Object.entries(Go))if(t.includes(s))return i;return null}function uo(e){var t;return vc[e]??((t=wc(e))==null?void 0:t.color)??"rgba(255, 255, 255, 0.4)"}function Xi(e){var t;return Ja[e]??((t=wc(e))==null?void 0:t.domain)??null}function im(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function Lt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Wt={durationFast:150,durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},Bx={surfaceSwitch:{duration:Wt.durationStandard/1e3,ease:Wt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Wt.durationFast/1e3,ease:Wt.easingStandard}},railMorphSpring:{type:"spring",stiffness:340,damping:38,mass:.72},listStaggerStep:.016,listStaggerMaxItems:6,segmentedTap:{whileTap:{scale:.985},transition:{duration:.09}}},yr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:Wt.durationStandard/1e3,ease:Wt.easingStandard}})},Ux={initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:Wt.easingStandard}},aa="/orgx/live/assets/Fm0FhtnV.png";function kc({size:e=14,className:t="",stroke:s="currentColor",strokeWidth:i=1.8,withBackground:r=!1,backgroundColor:a="transparent"}){return n.jsxs("svg",{className:t,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:s,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i,children:[r?n.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"6",fill:a,stroke:"none"}):null,n.jsx("path",{d:"M6 6c3 0 5 6 8 6"}),n.jsx("path",{d:"M6 18c3 0 5-6 8-6"}),n.jsx("path",{d:"M6 12h12"}),n.jsx("path",{d:"m14 8 4 4-4 4"}),n.jsx("circle",{cx:"6",cy:"6",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"12",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1.5",fill:s,stroke:"none"})]})}function en({type:e,className:t="",size:s=14,accent:i}){const r={className:t,width:s,height:s,viewBox:"0 0 24 24",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8};if(e==="initiative"){const l=i??q.iris;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:l,stroke:"none"})]})}if(e==="workstream"){const l=i??q.lime;return n.jsx(kc,{size:s,className:t,stroke:l,strokeWidth:r.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}if(e==="milestone"){const l=i??q.teal;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${l}1A`})]})}if(e==="task")return n.jsxs("svg",{...r,stroke:"rgba(255,255,255,0.76)",children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4",fill:"rgba(255,255,255,0.12)"}),n.jsx("path",{d:"M9 12.2 11 14.2 15.2 10"})]});if(e==="decision"){const l=i??q.amber;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M12 3 5.2 6.1v5.7c0 4.8 3.2 7.5 6.8 9 3.6-1.5 6.8-4.2 6.8-9V6.1z",fill:`${l}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}if(e==="session"){const l=i??q.teal;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${l}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}if(e==="active"){const l=i??q.lime;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}if(e==="blocked"){const l=i??q.red;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("rect",{x:"7.5",y:"11",width:"9",height:"7",rx:"2",fill:"rgba(255,255,255,0.03)"}),n.jsx("path",{d:"M9 11V9.2a3 3 0 0 1 6 0V11"})]})}if(e==="failed"){const l=i??q.red;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}if(e==="handoff"){const l=i??q.iris;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"m13 8 4 4-4 4"}),n.jsx("path",{d:"M7 8v8",opacity:"0.55"})]})}if(e==="outbox"){const l=i??q.amber;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M4 12h16"}),n.jsx("path",{d:"M6 7h12l2 5v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7z",fill:`${l}12`}),n.jsx("path",{d:"M9 14h6"})]})}const a=i??q.cyan;return n.jsxs("svg",{...r,stroke:a,children:[n.jsx("path",{d:"M12 3a6 6 0 0 0-6 6v2.9c0 .7-.3 1.4-.8 1.9L4 15.2h16l-1.2-1.4a2.8 2.8 0 0 1-.8-1.9V9a6 6 0 0 0-6-6z",fill:`${a}1A`}),n.jsx("path",{d:"M9.2 18a2.8 2.8 0 0 0 5.6 0"})]})}const rm=[{label:"Model Routing",desc:"Right model, right cost, every prompt",iconType:"initiative"},{label:"Live Operations",desc:"Decisions, handoffs, sessions in real time",iconType:"workstream"},{label:"Quality Gates",desc:"Automated checkpoints before shipping",iconType:"milestone"}],Fr=[{id:"hierarchy",kicker:"Mission Control",title:"Map the full execution ladder in one place",description:"Trace initiatives through workstreams, milestones, and tasks with sticky context, dependency mapping, and inline edits.",highlights:[{type:"initiative",label:"Initiative",detail:"Top-level outcomes with owner and status."},{type:"workstream",label:"Workstream",detail:"Operational lanes and runner context."},{type:"milestone",label:"Milestone",detail:"Checkpoints that gate readiness."},{type:"task",label:"Task",detail:"Priority, ETA, budget, and dependencies."}],footnote:"Use the hierarchy filters to isolate open, blocked, or done work instantly."},{id:"activity",kicker:"Activity + Decisions",title:"Stay in flow while execution evolves",description:"Track agent output as it happens, review decision payloads, and keep operational context attached from plan to completion.",highlights:[{type:"notification",label:"Live feed",detail:"Messages, failures, and progress in one stream."},{type:"decision",label:"Decision queue",detail:"Approve or reject with full execution context."},{type:"workstream",label:"Handoffs",detail:"Runner transitions across domains and tasks."},{type:"task",label:"Artifacts",detail:"Completion evidence attached where it belongs."}],footnote:"Focus a session to pin a run while the rest of the org remains visible."},{id:"dispatch",kicker:"Autopilot + Next Up",title:"Dispatch work confidently with clear guardrails",description:"Queue the next workstream, open the owning initiative instantly, and escalate from manual play to controlled auto-continue.",highlights:[{type:"workstream",label:"Next Up",detail:"Queued workstreams with resolved runner and next task."},{type:"initiative",label:"Open target",detail:"Jump to the owning initiative and sticky hierarchy."},{type:"milestone",label:"Guardrails",detail:"Blocked states are surfaced before dispatch."},{type:"notification",label:"System notices",detail:"Inline success and failure feedback loops."}],footnote:"Start with Play, then enable auto-continue when queue health is stable."}],am=[{type:"initiative",label:"Live Initiative Sync",detail:"Initiatives and ownership stay aligned with OpenClaw execution."},{type:"decision",label:"Decision Control",detail:"Review approvals in-app without losing mission context."},{type:"workstream",label:"Queue Visibility",detail:"Understand what runs next, who runs it, and why."}],Xo="openclaw plugins install @useorgx/openclaw-plugin",om=6500;function lm(e){switch(e){case"config":return"Plugin config";case"environment":return"Environment variable";case"persisted":return"Saved local credential";case"openclaw-config-file":return"OpenClaw config file";case"legacy-dev":return"Local development key";default:return"Not detected"}}const cm={hidden:{},visible:{transition:{staggerChildren:.07}}},As={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},dm={initiative:"text-[#A8A0FF]",workstream:"text-lime",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-lime",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function Ca(e){const t=Fr.length;return(e+t)%t}function um({state:e,isStarting:t,onConnect:s,onUseManualKey:i,onContinueWithoutOrgX:r}){const a=!!e.lastError,l=e.lastError?Xt(e.lastError):null,[c,d]=o.useState("idle"),[u,p]=o.useState("idle"),[h,y]=o.useState(0),[g,w]=o.useState(!1),N=e.hasApiKey&&e.keySource&&e.keySource!=="none",k=Fr[h];o.useEffect(()=>{if(c==="idle")return;const b=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(b)},[c]),o.useEffect(()=>{if(u==="idle")return;const b=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(b)},[u]),o.useEffect(()=>{if(g)return;const b=window.setInterval(()=>{y(_=>Ca(_+1))},om);return()=>window.clearInterval(b)},[g]);const T=async()=>{try{await navigator.clipboard.writeText(Xo),d("ok")}catch{d("error")}},D=async()=>{try{const b={at:new Date().toISOString(),onboarding:{status:e.status,nextAction:e.nextAction,hasApiKey:e.hasApiKey,keySource:e.keySource,installationId:e.installationId,lastError:e.lastError},page:typeof window<"u"?window.location.href:null,userAgent:typeof navigator<"u"?navigator.userAgent:null};await navigator.clipboard.writeText(JSON.stringify(b,null,2)),p("ok")}catch{p("error")}};return n.jsxs(ue.section,{variants:cm,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-4 sm:px-8 sm:pt-5",children:[n.jsxs(ue.div,{variants:As,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:aa,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsxs(ue.h2,{variants:As,className:"mt-3 flex items-center gap-2.5 text-[24px] font-semibold leading-[1.2] tracking-[-0.02em] text-white sm:text-[28px]",children:[n.jsx(en,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ue.p,{variants:As,className:"mt-2 max-w-2xl text-heading leading-relaxed text-secondary",children:"Orchestrate agents, approve decisions, and track progress from a single live dashboard."})]}),n.jsxs("div",{className:"mt-3 grid gap-3 px-6 sm:px-8 lg:grid-cols-[1.24fr_0.86fr]",children:[n.jsxs(ue.div,{variants:As,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(en,{type:"workstream",size:14,className:"text-lime"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[h+1,"/",Fr.length]})]}),n.jsx(bt,{initial:!1,mode:"wait",children:n.jsxs(ue.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.24,ease:[.22,1,.36,1]},className:"mt-2.5 min-h-[214px] space-y-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.09em] text-muted",children:k.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:k.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:k.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:k.highlights.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(en,{type:b.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},`${k.id}-${b.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:k.footnote})]},k.id)}),n.jsxs("div",{className:"mt-1.5 flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:Fr.map((b,_)=>{const H=_===h;return n.jsx("button",{type:"button",onClick:()=>y(_),"aria-label":`View slide ${_+1}`,className:`h-1.5 rounded-full transition-all ${H?"w-6 bg-lime":"w-2 bg-white/24 hover:bg-white/38"}`},b.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(b=>Ca(b-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>y(b=>Ca(b+1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Next"})]})]})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:rm.map(b=>n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.025] px-3 py-2.5",children:[n.jsx("div",{className:`mb-1.5 ${dm[b.iconType]}`,children:n.jsx(en,{type:b.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:b.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:b.desc})]},b.label))}),n.jsxs(ue.div,{variants:As,className:"flex flex-wrap items-center gap-2.5",children:[n.jsx("button",{type:"button",onClick:s,disabled:t,className:"inline-flex items-center gap-2 rounded-full bg-lime px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:t?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Connecting..."]}):"Connect OrgX"}),n.jsx("button",{type:"button",onClick:i,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Use API key"})]})]}),n.jsxs(ue.div,{variants:As,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/20 bg-[#14B8A6]/[0.06] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(en,{type:"workstream",size:12,className:"text-[#7EEDE1]"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#7EEDE1]",children:"OpenClaw Integration"})]}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-[#CFF8F3]",children:"OrgX syncs with OpenClaw so initiatives, workstreams, milestones, and tasks stay aligned with live execution."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(en,{type:"task",size:12,className:"opacity-90"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"Quick Setup"})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsx("code",{className:"rounded-md border border-white/[0.08] bg-black/30 px-2 py-1 font-mono text-caption text-primary",children:Xo}),n.jsx("button",{type:"button",onClick:()=>{T()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:c==="ok"?"Copied":c==="error"?"Copy failed":"Copy command"})]}),N&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",lm(e.keySource)]})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"What Unlocks After Connect"}),n.jsx("div",{className:"mt-2 space-y-1.5",children:am.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(en,{type:b.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},b.label))})]})]})]}),n.jsx(ue.div,{variants:As,className:"mx-6 mt-2 sm:mx-8",children:a?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-500/15 bg-red-500/[0.04] px-4 py-3",children:[n.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/15",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:n.jsx("path",{d:"M5 2.5v3M5 7.5h.004",stroke:"#FF6B88",strokeWidth:"1.4",strokeLinecap:"round"})})}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"text-body text-red-300/80",children:l})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void D(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:u==="ok"?"Copied":u==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:i,className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Use API key"}),n.jsx("button",{type:"button",onClick:s,disabled:t,className:"rounded-full border border-red-500/20 bg-red-500/[0.06] px-3 py-1 text-caption font-semibold text-red-200/85 transition hover:bg-red-500/[0.09] hover:text-red-100 disabled:opacity-50",children:"Retry"})]})]}):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-subtle bg-white/[0.02] px-3.5 py-2",children:[n.jsx("span",{className:"relative flex h-1.5 w-1.5",children:n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-white/40"})}),n.jsx("span",{className:"text-body text-muted",children:"Ready to connect"})]})}),n.jsxs(ue.div,{variants:As,className:"mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-subtle px-6 py-2 sm:px-8",children:[n.jsx("div",{className:"flex flex-wrap items-center gap-3",children:n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.setItem(Xr,"1"),window.localStorage.removeItem(Qr)}catch{}r()},className:"text-left text-caption text-muted transition hover:text-secondary",children:"Open guided sandbox"})}),n.jsxs("a",{href:e.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1 text-caption text-muted transition hover:text-secondary",children:["Setup guide",n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:"transition-transform group-hover:translate-x-0.5",children:n.jsx("path",{d:"M3.5 2.5l3 2.5-3 2.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]})}const mm={hidden:{},visible:{transition:{staggerChildren:.06}}},Bs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function pm({isSubmitting:e,onSubmit:t,onBack:s}){const[i,r]=o.useState(""),[a,l]=o.useState(null),c="https://www.useorgx.com/settings#security",d=async()=>{l(null);const p=i.trim();if(!p){l("API key is required.");return}const h=/^[a-z]+_/i.test(p)?p:`oxk_${p}`;try{await t(h),r("")}catch(y){const g=y instanceof Error?y.message:"Failed to validate API key.";l(Xt(g))}},u=a!==null;return n.jsxs(ue.section,{variants:mm,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-6 sm:px-8 sm:pt-8",children:[n.jsxs(ue.div,{variants:Bs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:aa,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsx(ue.h3,{variants:Bs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ue.p,{variants:Bs,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(ue.p,{variants:Bs,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(ue.div,{variants:Bs,className:"mt-3",children:n.jsxs("a",{href:c,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-full border border-white/[0.10] bg-white/[0.03] px-3 py-1.5 text-body font-semibold text-secondary transition hover:bg-white/[0.06] hover:text-primary",title:"Open OrgX settings to generate an API key",children:["Generate an API key",n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h5v5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M9.5 2.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M2.75 3.5H2.5c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]})]})})]}),n.jsxs(ue.div,{variants:Bs,className:"mt-6 space-y-4 px-6 sm:px-8",children:[n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1.5 block text-caption font-medium uppercase tracking-[0.14em] text-muted",children:"API key"}),n.jsxs("div",{className:`flex items-stretch overflow-hidden rounded-xl border transition-colors focus-within:border-lime/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:i,onChange:p=>{r(p.target.value),a&&l(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(ue.p,{initial:{opacity:0,y:-3},animate:{opacity:1,y:0},className:"mt-1.5 text-body text-red-400/70",children:a})]}),n.jsxs("p",{className:"text-body text-muted",children:["User-scoped keys (",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_..."}),") do not require a separate user ID header."]})]}),n.jsxs(ue.div,{variants:Bs,className:"mt-6 flex flex-wrap items-center gap-3 px-6 sm:px-8",children:[n.jsx("button",{type:"button",onClick:()=>{d()},disabled:e,className:"inline-flex items-center gap-2 rounded-full bg-lime px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:e?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Validating..."]}):"Validate & Connect"}),n.jsx("button",{type:"button",onClick:s,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Back to pairing"})]}),n.jsx("div",{className:"mt-6 border-t border-subtle px-6 py-4 sm:px-8",children:n.jsx("p",{className:"text-body text-faint",children:"Keys are stored locally and never leave your device."})})]})}const Qo="orgx.user.display-name",Yo="orgx.user.avatar-seed-suffix";function Jo(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Zo(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function fm(){const[e,t]=o.useState(()=>Jo(Qo)),[s,i]=o.useState(()=>Jo(Yo)),r=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();Zo(Qo,d),t(d)},[]),l=o.useCallback(()=>{const c=String(Date.now());Zo(Yo,c),i(c)},[]);return{displayName:e,avatarSeed:r,updateName:a,regenerateAvatar:l}}function hm(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function gm(e){let t=e|0;return()=>{t=t+1831565813|0;let s=Math.imul(t^t>>>15,1|t);return s=s+Math.imul(s^s>>>7,61|s)^s,((s^s>>>14)>>>0)/4294967296}}const el=[q.lime,q.teal,q.iris,q.cyan];function xm(e,t,s,i,r,a){const l=_=>_*Math.PI/180,c=Math.cos,d=Math.sin,u=l(r),p=l(a),h=a-r>180?1:0,y=e+i*c(u),g=t+i*d(u),w=e+i*c(p),N=t+i*d(p),k=e+s*c(p),T=t+s*d(p),D=e+s*c(u),b=t+s*d(u);return[`M ${y} ${g}`,`A ${i} ${i} 0 ${h} 1 ${w} ${N}`,`L ${k} ${T}`,`A ${s} ${s} 0 ${h} 0 ${D} ${b}`,"Z"].join(" ")}function ym(e){const t=gm(hm(e)),s=3+Math.floor(t()*2),i=[],r=50,a=50;for(let l=0;l<s;l++){const c=8+l*10,d=c+9,u=6+Math.floor(t()*6),p=360/u,h=1.5+t()*2;for(let y=0;y<u;y++){if(t()<.15)continue;const g=y*p+h/2,w=(y+1)*p-h/2,N=el[Math.floor(t()*el.length)],k=.25+t()*.55;i.push({d:xm(r,a,c,d,g,w),fill:N,opacity:k})}}return i}function Ic({seed:e,size:t,className:s,animate:i=!0}){const r=o.useMemo(()=>ym(e),[e]);return n.jsxs(ue.svg,{viewBox:"0 0 100 100",width:t,height:t,className:fe("flex-shrink-0",s),initial:i?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Wt.easingEntrance},children:[n.jsxs("defs",{children:[n.jsx("clipPath",{id:`avatar-clip-${e}`,children:n.jsx("circle",{cx:"50",cy:"50",r:"48"})}),n.jsxs("radialGradient",{id:`avatar-glow-${e}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:q.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:q.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:q.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:r.map((a,l)=>n.jsx(ue.path,{d:a.d,fill:a.fill,initial:i?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:l*.012,duration:.35,ease:Wt.easingEntrance},style:{transformOrigin:"50px 50px"}},l))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function bm({onComplete:e}){const{displayName:t,updateName:s}=fm(),[i,r]=o.useState(t),a=o.useCallback(()=>{s(i),e()},[i,s,e]),l=o.useCallback(()=>{e()},[e]),c=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(i.trim()||"orgx-user")+"";return n.jsx(ue.div,{initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:Wt.easingEntrance},className:"flex items-center justify-center",children:n.jsx("div",{className:"w-full max-w-md rounded-2xl border border-white/[0.08] bg-[--orgx-surface-elevated] p-6 sm:p-8",children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx(Ic,{seed:d,size:96}),n.jsx("h2",{className:"mt-5 text-title font-medium text-white",children:"Welcome to OrgX"}),n.jsx("p",{className:"mt-2 text-body leading-relaxed text-secondary",children:"What should we call you? This appears in your settings and is stored locally."}),n.jsx("input",{type:"text",value:i,onChange:u=>r(u.target.value),onKeyDown:c,maxLength:64,autoFocus:!0,placeholder:"Your name",className:"mt-5 h-10 w-full max-w-xs rounded-xl border border-white/[0.12] bg-white/[0.04] px-4 text-center text-body text-white placeholder:text-muted focus:border-lime/30 focus:outline-none"}),n.jsx("button",{type:"button",onClick:a,className:"mt-5 rounded-full bg-lime px-6 py-2.5 text-body font-medium text-black transition hover:brightness-110",children:i.trim()?"Continue":"Continue without name"}),i.trim()&&n.jsx("button",{type:"button",onClick:l,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const vm=[{label:"Terms",href:"https://www.useorgx.com/terms"},{label:"Privacy",href:"https://www.useorgx.com/privacy"},{label:"IP notice",href:"https://www.useorgx.com/legal"}];function wm({className:e,compact:t=!1}){return n.jsxs("div",{className:fe("flex flex-wrap items-center gap-x-3 gap-y-1 text-muted",t?"text-micro":"text-caption",e),children:[n.jsxs("span",{className:"text-faint",children:["© ",new Date().getFullYear()," OrgX"]}),vm.map(s=>n.jsx("a",{href:s.href,target:"_blank",rel:"noopener noreferrer nofollow",className:"transition-colors hover:text-secondary",children:s.label},s.label))]})}const tl="orgx.user.name-asked";function km(e){switch(e){case"starting":return"Starting secure session...";case"awaiting_browser_auth":return"Waiting for browser approval...";case"pairing":return"Confirming connection...";case"manual_key":return"Manual key entry";case"connected":return"Connected";case"error":return"Connection issue";default:return"Ready to connect"}}function Im(e){switch(e){case"config":return"Config key";case"environment":return"Env key";case"persisted":return"Saved key";case"openclaw-config-file":return"OpenClaw key";case"legacy-dev":return"Local dev key";default:return"No key"}}function Nm(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const nl={idle:"bg-white/40",active:"bg-lime",error:"bg-red-400"},Ta="orgx.onboarding.mc_hint.dismissed",Ma={initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:[.16,1,.3,1]}};function jm({state:e,isLoading:t,isStarting:s,isSubmittingManual:i,onRefresh:r,onStartPairing:a,onSubmitManualKey:l,onBackToPairing:c,onUseManualKey:d,onSkip:u}){const[p,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ta)==="1"),[y,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(tl)!=="1"),w=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(tl,"1"),g(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(Ta,"1"):window.localStorage.removeItem(Ta))},[p]);const N=e.status==="manual_key",k=e.status==="awaiting_browser_auth"||e.status==="pairing",T=Nm(e.status),D=T==="active"&&e.status!=="connected",b=e.status==="connected"&&!p;return n.jsx("div",{className:"relative flex min-h-screen items-start justify-center px-4 pb-6 pt-0 sm:pt-2",style:{backgroundColor:"#02040A"},children:n.jsxs(ue.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${N?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(bt,{mode:"wait",children:e.status==="connected"&&y?n.jsx(ue.div,{...Ma,children:n.jsx(bm,{onComplete:w})},"welcome-name"):N?n.jsx(ue.div,{...Ma,children:n.jsx(pm,{isSubmitting:i,onSubmit:l,onBack:c})},"manual"):n.jsx(ue.div,{...Ma,children:n.jsx(um,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(k||e.status==="connected")&&n.jsxs(ue.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{delay:.15,duration:.35,ease:[.16,1,.3,1]},className:"mt-4 flex items-center justify-between rounded-xl border border-subtle bg-white/[0.025] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsxs("span",{className:"relative flex h-2 w-2",children:[D&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${nl[T]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${nl[T]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:km(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Im(e.keySource)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[e.expiresAt&&n.jsx("span",{className:"text-caption text-muted",children:new Date(e.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.connectUrl&&k&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-lime/25 bg-lime/[0.05] px-3 py-1 text-caption font-medium text-lime transition hover:bg-lime/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{r()},className:"rounded-full border border-white/[0.08] px-2.5 py-1 text-caption text-muted transition hover:bg-white/[0.04] hover:text-secondary",children:"Refresh"})]})]}),b&&n.jsxs(ue.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.2,duration:.3},className:"mt-3 rounded-xl border border-[#7C7CFF]/25 bg-[#7C7CFF]/10 px-4 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#CFCBFF]",children:"Mission Control Tip"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-[#E6E4FF]",children:"Open Mission Control to see initiative → workstream → milestone → task flow with dependencies and recent todos in one expandable view."}),n.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[n.jsx("a",{href:"/orgx/live?view=mission-control",className:"rounded-full border border-lime/30 bg-lime/15 px-3 py-1 text-caption font-medium text-lime",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>h(!0),className:"text-caption text-secondary underline underline-offset-2",children:"Dismiss"})]})]}),!t&&n.jsx("div",{className:"mt-3 flex justify-center",children:n.jsx(wm,{compact:!0})})]})})}function Am({children:e,color:t,pulse:s,title:i}){const r=t??q.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title:i,style:{backgroundColor:`${r}22`,border:`1px solid ${r}5a`,color:r},children:[n.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s&&n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",style:{backgroundColor:r}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:r}})]}),e]})}function oa({open:e,onClose:t,children:s,maxWidth:i="max-w-2xl",fitContent:r=!1,closeOnBackdropClick:a=!0,closeOnEscape:l=!0,closeOnEscapeWhenTyping:c=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const w=d.current;if(!w)return;const N=w.querySelector('[data-modal-autofocus="true"]');if(N){N.focus();return}const k=w.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');k.length>0?k[0].focus():w.focus()})();const y=w=>{if(w.key==="Escape"){if(!l)return;if(!c){const _=w.target;if(_&&(_.tagName==="INPUT"||_.tagName==="TEXTAREA"||_.tagName==="SELECT"||_.isContentEditable))return}w.preventDefault(),t();return}if(w.key!=="Tab")return;const N=d.current;if(!N)return;const k=N.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(k.length===0){w.preventDefault(),N.focus();return}const T=k[0],D=k[k.length-1],b=document.activeElement;!w.shiftKey&&b===D?(w.preventDefault(),T.focus()):w.shiftKey&&b===T&&(w.preventDefault(),D.focus())},g=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",y),()=>{var w;document.body.style.overflow=g,document.removeEventListener("keydown",y),(w=u.current)==null||w.focus()}},[e,t,l,c]);const p=n.jsx(bt,{children:e&&n.jsxs(ue.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.22,ease:[.22,1,.36,1]},className:"fixed inset-0 z-[420] flex items-stretch justify-center p-0 sm:items-center sm:p-6",onClick:()=>{a&&t()},"aria-hidden":!e,children:[n.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-md"}),n.jsxs(ue.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.24,ease:[.16,1,.3,1]},className:`glass-panel soft-shadow relative flex flex-col w-full ${i} overflow-hidden ${r?"h-auto max-h-[100dvh] rounded-none sm:max-h-[88vh] sm:rounded-2xl":"h-[100dvh] max-h-[100dvh] rounded-none sm:h-[88vh] sm:max-h-[88vh] sm:rounded-2xl"}`,style:{backgroundColor:q.cardBgElevated,borderColor:q.cardBorderStrong},onClick:h=>h.stopPropagation(),role:"dialog","aria-modal":"true",tabIndex:-1,ref:d,children:[n.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"}),s]})]})});return typeof document>"u"?p:ud.createPortal(p,document.body)}const _m=[{id:"agents",label:"Agents",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})},{id:"activity",label:"Activity",icon:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})},{id:"decisions",label:"Decisions",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),n.jsx("path",{d:"m9 12 2 2 4-4"})]})},{id:"initiatives",label:"Next Up",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),n.jsx("line",{x1:"4",x2:"4",y1:"22",y2:"15"})]})}];function Sm({activeTab:e,onTabChange:t,pendingDecisionCount:s=0}){return n.jsx("nav",{className:"pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3 lg:hidden",style:{bottom:"max(10px, env(safe-area-inset-bottom))"},"aria-label":"Mobile sections",children:n.jsx("div",{className:"pointer-events-auto relative flex items-stretch gap-1 rounded-[24px] border border-strong bg-[#090d16]/90 p-1.5 shadow-[0_20px_50px_rgba(0,0,0,0.52)] backdrop-blur-xl",children:_m.map(i=>{const r=e===i.id;return n.jsxs("button",{type:"button",onClick:()=>t(i.id),"aria-current":r?"page":void 0,className:fe("relative flex min-w-[76px] flex-1 flex-col items-center gap-1 overflow-hidden rounded-[18px] px-2 pb-1.5 pt-2.5 transition-colors",r?"text-lime":"text-secondary hover:text-white/72"),children:[r&&n.jsxs(n.Fragment,{children:[n.jsx(ue.span,{layoutId:"mobile-tab-active-pill",className:"absolute inset-0 rounded-[18px] border border-lime/28 bg-lime/[0.1]",transition:{type:"spring",stiffness:420,damping:34,mass:.8}}),n.jsx(ue.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:q.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:fe("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",r?"border-lime/35 bg-lime/[0.12] text-lime":"border-white/[0.1] bg-white/[0.03]"),children:[n.jsx("span",{className:"relative z-[1]",children:i.icon}),i.id==="decisions"&&s>0&&n.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3.5 min-w-[14px] items-center justify-center rounded-full border border-black/35 px-1 text-[8px] font-bold text-black shadow-[0_2px_8px_rgba(0,0,0,0.35)]",style:{backgroundColor:q.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:fe("relative z-[1] text-micro font-medium",r?"text-lime":"text-secondary"),children:i.label})]},i.id)})})})}function Ts({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:fe("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Cm={xs:"w-6 h-6 text-micro",sm:"w-8 h-8 text-micro",md:"w-10 h-10 text-body",lg:"w-16 h-16 text-title"},Tm={xs:24,sm:32,md:40,lg:64},Mm="orgx.user.display-name",Em="orgx.user.avatar-seed-suffix",Rm="/orgx/live/",An=e=>`${Rm.replace(/\/+$/,"/")}${e}`,Lm={pace:An("brand/product-orchestrator.png"),eli:An("brand/engineering-autopilot.png"),mark:An("brand/launch-captain.png"),sage:An("brand/pipeline-intelligence.png"),orion:An("brand/control-tower.png"),dana:An("brand/design-codex.png"),xandy:An("brand/xandy-orchestrator.png"),nova:An("brand/xandy-orchestrator.png"),openclaw:An("brand/openclaw-mark.svg"),codex:An("brand/openai-mark.svg"),openai:An("brand/openai-mark.svg"),anthropic:An("brand/anthropic-mark.svg"),orgx:An("brand/orgx-logo.png")},Dm=[{test:/\bpace\b|product|nova|strategist/i,key:"pace"},{test:/\beli\b|engineering|dev-delivery|executor/i,key:"eli"},{test:/\bmark\b|marketing|launch-captain/i,key:"mark"},{test:/\bsage\b|sales|pipeline-intelligence|sales-sage/i,key:"sage"},{test:/\borion\b|operations|ops-orbit|control-tower/i,key:"orion"},{test:/\bdana\b|design/i,key:"dana"},{test:/\bxandy\b|orchestrator|router-all-agents/i,key:"xandy"},{test:/\bholt\b|openclaw/i,key:"openclaw"},{test:/openai|gpt|o[1345]-|codex/i,key:"codex"},{test:/anthropic|claude/i,key:"anthropic"},{test:/\borgx\b/i,key:"orgx"}];function $m(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of Dm)if(s.test.test(t))return Lm[s.key];return null}function Pm(e){return typeof e=="string"?e.trim().toLowerCase():""}function sl(e){const t=Pm(e);return t?!!(t==="you"||t==="main"||t==="me"||t==="user"||t==="usr"||t.startsWith("user_")||t.startsWith("usr_")):!1}function Om(){if(typeof window>"u")return"orgx-user";try{const e=(window.localStorage.getItem(Mm)??"").trim(),t=window.localStorage.getItem(Em)??"";return`${e||"orgx-user"}${t}`}catch{return"orgx-user"}}function Gt({name:e,size:t="xs",hint:s,src:i}){const r=uo(e),[a,l]=o.useState(!1),c=o.useMemo(()=>sl(e)||sl(s),[s,e]),d=o.useMemo(()=>c?Om():null,[c]),u=o.useMemo(()=>i&&i.trim()?i:$m(e,s),[s,e,i]),p=!!(!c&&u&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Cm[t]} overflow-hidden rounded-full flex items-center justify-center font-semibold flex-shrink-0`,style:{backgroundColor:`${r}20`,color:r,border:`1px solid ${r}30`},children:c&&d?n.jsx(Ic,{seed:d,size:Tm[t],animate:!1,className:"h-full w-full"}):p?n.jsx("img",{src:u??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>l(!0),loading:"lazy"}):im(e)})}Gt.displayName="AgentAvatar";const qm={neutral:"border-strong bg-white/[0.04] text-primary",muted:"border-strong bg-white/[0.03] text-secondary",lime:"border-lime/28 bg-lime/[0.12] text-[#D8FFA1]",cyan:"border-cyan-300/28 bg-cyan-500/[0.12] text-cyan-100",red:"border-red-300/28 bg-red-500/[0.12] text-red-100"};function Ln({children:e,tone:t="muted",className:s,...i}){const r=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const l=a.type;return l.displayName==="AgentAvatar"||l.name==="AgentAvatar"});return n.jsx("span",{className:fe("inline-flex h-7 items-center rounded-full border text-caption font-medium leading-none whitespace-nowrap",r?"gap-1.5 pl-[3px] pr-2.5 [&>[data-agent-avatar]]:h-5 [&>[data-agent-avatar]]:w-5":"gap-1.5 px-2.5",qm[t],s),...i,children:e})}function Fm(e){var s,i;const t=[];if(e.initiativeId){const r={id:e.initiativeId,label:e.initiativeTitle||Qs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=Nc(e.status),l={id:e.workstreamId,label:e.workstreamTitle||Qs(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const c of e.scopeProgress.milestones){const d=c.done>=c.total?"done":c.done>0?"active":"pending",u={id:c.id,label:c.title||Qs(c.id,"Milestone"),type:"milestone",status:d,progress:{done:c.done,total:c.total}};c.total>0&&(u.children=Array.from({length:c.total},(p,h)=>({id:`${c.id}-task-${h}`,label:`Task ${h+1}`,type:"task",status:h<c.done?"done":"pending"}))),l.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const c=((i=e.scopeProgress)==null?void 0:i.completedTasks)??0;l.children=e.taskIds.map((d,u)=>({id:d,label:Qs(d,"Task"),type:"task",status:u<c?"done":"pending"}))}r.children.push(l)}t.push(r)}return t}function zx(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Qs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,i=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Qs(e.workstreamId,"Workstream"),type:"workstream",status:Nc(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,r=e.taskId?{id:e.taskId,label:e.taskTitle||Qs(e.taskId,"Task"),type:"task",highlight:!0}:null;return i&&r&&(i.children=[r]),s&&i?(s.children=[i],t.push(s)):i?t.push(i):s&&t.push(s),t}function Qs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function Nc(e){return e?e==="completed"||e==="done"?"done":e==="running"||e==="in_progress"||e==="needs_review"?"active":e==="failed"?"failed":e==="blocked"||e==="awaiting_input"?"blocked":"pending":"pending"}function Bm(e){return e==="done"||e==="completed"?"done":e==="active"||e==="running"||e==="in_progress"?"active":e==="blocked"?"blocked":e==="failed"?"failed":"pending"}function Um(e){return e.map(t=>({id:t.id,label:t.title,type:"milestone",status:t.doneTasks===t.totalTasks&&t.totalTasks>0?"done":t.tasks.some(s=>s.status==="active"||s.status==="running"||s.status==="in_progress")?"active":"pending",progress:{done:t.doneTasks,total:t.totalTasks},children:t.tasks.map(s=>({id:s.id,label:s.title,type:"task",status:Bm(s.status)}))}))}function zm(e){const t=[],s=[],i=[],r=[];for(const a of e)a.status==="done"?s.push(a):a.status==="active"?t.push(a):a.status==="blocked"||a.status==="failed"?r.push(a):i.push(a);return{inProgress:t,completed:s,upcoming:i,blocked:r}}const Wx=o.memo(function({milestones:t,height:s=3}){const i=t.reduce((r,a)=>r+a.totalTasks,0);return i===0?null:n.jsx("div",{className:"flex w-full gap-px overflow-hidden rounded-full",style:{height:s},children:t.map(r=>{const a=r.totalTasks/i*100,l=r.totalTasks>0?r.doneTasks/r.totalTasks*100:0,c=r.doneTasks===r.totalTasks&&r.totalTasks>0;return n.jsx("div",{className:"relative overflow-hidden rounded-full bg-white/[0.06]",style:{width:`${a}%`},children:n.jsx("div",{className:"absolute inset-y-0 left-0 rounded-full transition-[width] duration-500",style:{width:`${l}%`,backgroundColor:c?q.teal:`${q.lime}99`}})},r.id)})})}),Wm={active:Fi.active,done:Fi.done,blocked:Fi.blocked,planned:Fi.planned};function br({label:e,count:t,tone:s,nodes:i,defaultOpen:r,compact:a}){const[l,c]=o.useState(r);o.useEffect(()=>{c(r)},[r]);const d=Wm[s]??Fi.planned;return n.jsxs("div",{className:"overflow-hidden rounded-lg border",style:{borderColor:d.border,backgroundColor:d.background},children:[n.jsxs("button",{type:"button",onClick:()=>c(u=>!u),className:"flex w-full items-center justify-between px-2.5 py-1.5",children:[n.jsxs("span",{className:"text-micro font-semibold uppercase tracking-[0.08em]",style:{color:d.text},children:[e," ",n.jsx("span",{className:"ml-1 font-normal opacity-70",children:t})]}),n.jsx(ue.svg,{viewBox:"0 0 12 12",fill:"none",className:"h-3 w-3",style:{color:d.text},animate:{rotate:l?180:0},transition:{duration:.15},children:n.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n.jsx(bt,{initial:!1,children:l&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:n.jsx("div",{className:"px-1 pb-1.5",children:n.jsx(_c,{nodes:i,compact:a})})})})]})}const Hm=o.memo(function({nodes:t,compact:s=!1,defaultOpenSections:i}){const r=zm(t);return n.jsxs("div",{className:"space-y-2",children:[r.blocked.length>0&&n.jsx(br,{label:"BLOCKED",count:r.blocked.length,tone:"blocked",nodes:r.blocked,defaultOpen:(i==null?void 0:i.blocked)??!0,compact:s}),r.inProgress.length>0&&n.jsx(br,{label:"IN PROGRESS",count:r.inProgress.length,tone:"active",nodes:r.inProgress,defaultOpen:(i==null?void 0:i.inProgress)??!0,compact:s}),r.completed.length>0&&n.jsx(br,{label:"COMPLETED",count:r.completed.length,tone:"done",nodes:r.completed,defaultOpen:(i==null?void 0:i.completed)??!1,compact:s}),r.upcoming.length>0&&n.jsx(br,{label:"UPCOMING",count:r.upcoming.length,tone:"planned",nodes:r.upcoming,defaultOpen:(i==null?void 0:i.upcoming)??!1,compact:s})]})});function jc(e){switch(e){case"done":return q.lime;case"active":return q.teal;case"blocked":return q.amber;case"failed":return q.red;default:return"rgba(255,255,255,0.15)"}}function Km(e){const t=jc(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Vm=o.memo(function({done:t,total:s,color:i}){const r=s>0?Math.max(2,Math.round(t/s*100)):0;return n.jsx("div",{className:"h-[3px] w-full overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx(ue.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${r}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Gm=16,Xm=14,il=8,Qm=8,Ym=28,Jm=24,Zm=24,ep=20,Ea="rgba(255,255,255,0.07)";function tp(e){const t=e?Xm:Gm,s=t+Qm+4;return{iconSz:t,colW:s,rowH:e?Zm:Ym,rowHTask:e?ep:Jm}}function Ac({node:e,depth:t,isLast:s,activeId:i,compact:r,index:a,taskLimit:l,expanded:c,onToggleExpand:d}){const u=i===e.id||e.highlight,p=e.progress&&e.progress.total>0,h=e.type==="task",{iconSz:y,colW:g,rowH:w,rowHTask:N}=tp(r),k=h?N:w,T=e.children??[],D=T.filter(M=>M.type==="task"),b=T.filter(M=>M.type!=="task"),_=D.length>l&&!c,H=_?D.slice(0,l):D,A=D.length-H.length,O=[...b,...H],se=O.length>0||_;return n.jsxs("div",{className:"relative",style:{minHeight:k},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Ea,left:(t-1)*g+g/2,top:0,bottom:s?void 0:0,height:s?k/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:Ea,left:(t-1)*g+g/2,top:k/2,width:g}})]}),n.jsxs(ue.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${u?"rounded-md bg-white/[0.03]":""}`,style:{height:k,paddingLeft:t*g},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:g,height:k},children:h?n.jsx("span",{className:"inline-block rounded-full",style:{...Km(e.status),width:il,height:il}}):n.jsx(en,{type:e.type,size:y,accent:u?q.lime:void 0})}),n.jsxs("div",{className:"min-w-0 flex-1 pr-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`min-w-0 truncate ${h?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),p&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] tabular-nums leading-none text-white/20",children:[e.progress.done,"/",e.progress.total]}),e.agent&&n.jsx("span",{className:"ml-auto flex-shrink-0 rounded-full bg-white/[0.05] px-1.5 py-px text-[9px] font-medium leading-none text-white/25",children:e.agent.name})]}),p&&!h&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Vm,{done:e.progress.done,total:e.progress.total,color:jc(e.status)})})]})]}),se&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Ea,left:t*g+g/2,top:k/2,height:k/2}}),se&&n.jsxs("div",{children:[O.map((M,L)=>n.jsx(Ac,{node:M,depth:t+1,isLast:L===O.length-1&&!_,activeId:i,compact:r,index:a+L+1,taskLimit:l,expanded:c,onToggleExpand:d},M.id)),_&&n.jsxs(ue.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+O.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:N,paddingLeft:(t+1)*g+g},children:["+",A," more · see all"]}),n.jsx(bt,{children:c&&D.length>l&&n.jsx(ue.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:N},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*g+g},children:"show less"})})]})]})}const _c=o.memo(function({nodes:t,className:s,activeId:i,compact:r,taskLimit:a=4}){const[l,c]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(Ac,{node:d,depth:0,isLast:u===t.length-1,activeId:i,compact:r,index:u,taskLimit:a,expanded:l,onToggleExpand:()=>c(p=>!p)},d.id))})}),Za={engineering:{domain:"engineering",displayName:"Engineering",gradient:["#22c55e","#14b8a6"],accentColor:"#22c55e",glowColor:"#22c55e33",icon:"hammer",progressStyle:"linear",verb:"Building"},design:{domain:"design",displayName:"Design",gradient:["#a78bfa","#ec4899"],accentColor:"#a78bfa",glowColor:"#a78bfa33",icon:"palette",progressStyle:"wave",verb:"Designing"},product:{domain:"product",displayName:"Product",gradient:["#3b82f6","#6366f1"],accentColor:"#3b82f6",glowColor:"#3b82f633",icon:"compass",progressStyle:"stepped",verb:"Specifying"},marketing:{domain:"marketing",displayName:"Marketing",gradient:["#f59e0b","#ef4444"],accentColor:"#f59e0b",glowColor:"#f59e0b33",icon:"megaphone",progressStyle:"wave",verb:"Crafting"},sales:{domain:"sales",displayName:"Sales",gradient:["#06b6d4","#3b82f6"],accentColor:"#06b6d4",glowColor:"#06b6d433",icon:"handshake",progressStyle:"linear",verb:"Preparing"},operations:{domain:"operations",displayName:"Operations",gradient:["#64748b","#475569"],accentColor:"#64748b",glowColor:"#64748b33",icon:"shield",progressStyle:"stepped",verb:"Securing"},orchestrator:{domain:"orchestrator",displayName:"Orchestrator",gradient:["#8b5cf6","#6366f1"],accentColor:"#8b5cf6",glowColor:"#8b5cf633",icon:"workflow",progressStyle:"linear",verb:"Coordinating"}},np=Object.keys(Za);function rl(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of np)if(t.includes(s))return s;return"engineering"}function al(e){return Za[e]??Za.engineering}const ci={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Li={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},ol={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},ll={eli:"Eli",pace:"Pace",dana:"Dana",mark:"Mark",sage:"Sage",orion:"Orion",xandy:"Xandy",nova:"Nova","engineering-agent":"Eli","product-agent":"Pace","design-agent":"Dana","marketing-agent":"Mark","strategy-agent":"Sage","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","dev-delivery":"Eli","launch-captain":"Mark","pipeline-intelligence":"Sage","control-tower":"Orion","design-codex":"Dana","router-all-agents":"Xandy","ops-orbit":"Orion","sales-sage":"Sage"};function sp(e,t){const s={name:(t==null?void 0:t.trim())||"OrgX",domain:"",color:"rgba(255,255,255,0.4)",displayLabel:(t==null?void 0:t.trim())||"OrgX"};if(e){const i=e.trim().toLowerCase(),r=ll[i];if(r){const a=Li[r]??"";return{name:r,domain:a,color:ci[r]??s.color,displayLabel:a?`${r} (${a})`:r}}for(const[a,l]of Object.entries(ol))if(i.includes(a)){const c=Li[l]??"";return{name:l,domain:c,color:ci[l]??s.color,displayLabel:c?`${l} (${c})`:l}}}if(t){const i=t.trim();if(ci[i]){const l=Li[i]??"";return{name:i,domain:l,color:ci[i],displayLabel:l?`${i} (${l})`:i}}const r=i.toLowerCase(),a=ll[r];if(a){const l=Li[a]??"";return{name:a,domain:l,color:ci[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(ol))if(r.includes(l)){const d=Li[c]??"";return{name:c,domain:d,color:ci[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function Hx({agents:e,max:t=4}){if(!e.length)return null;const s=e.slice(0,t),i=e.length-t;return n.jsxs("div",{className:"inline-flex min-w-0 items-center justify-end -space-x-1.5 pl-1",children:[s.map(r=>n.jsx("div",{className:"relative flex-shrink-0",title:`${r.name} (${r.confidence} confidence)`,style:{borderRadius:"9999px",border:r.confidence==="high"?"1.5px solid rgba(255,255,255,0.25)":r.confidence==="medium"?"1.5px dashed rgba(255,255,255,0.15)":"1.5px dotted rgba(255,255,255,0.10)"},children:n.jsx(Gt,{name:r.name,size:"xs"})},r.id)),i>0&&n.jsxs("span",{className:"ml-1 flex-shrink-0 text-micro text-muted",children:["+",i]})]})}const ip=new Set(["running","in_progress","working","dispatching"]),rp=new Set(["running","dispatching"]),ap=3*6e4;function cl(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=ap:!1}function op(e){const t=Lt(e.status??""),s=Lt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:ip.has(t)?!0:t==="active"||s==="active"?cl(e.lastHeartbeatAt):t==="queued"||t==="pending"||t==="planning"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?cl(e.lastHeartbeatAt):!1}function Sc(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function lp(e){const t=Lt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"border-teal-300/28 bg-teal-400/[0.10] text-teal-100":t==="blocked"||t==="failed"||t==="error"?"border-red-400/26 bg-red-500/[0.10] text-red-100":t==="paused"||t==="pending"||t==="queued"?"border-amber-300/28 bg-amber-300/[0.10] text-amber-100":"border-lime/24 bg-lime/[0.10] text-lime"}function cp(e){const t=Lt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":t==="blocked"||t==="failed"||t==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":t==="paused"||t==="pending"||t==="queued"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-lime/0 via-lime/70 to-lime/0"}function dp(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function di(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Hs(e,t){const s=[],i=r=>{if(typeof r!="string")return;const a=r.trim();a&&(s.some(l=>l.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const r of e)i(r);return i(t??null),s}function eo(e,t){if(!e)return t;const s=e.trim();return s?Wn(s)?`${t} ${Ss(s)}`:s:t}const up=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),mp=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function pp(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?up.has(t)||t.startsWith("telegram:"):!1}function fp(e){if(!e)return!1;const t=e.trim();return t?mp.some(s=>s.test(t)):!1}function Cc({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var k,T,D,b,_,H;const i=new Map;for(const A of s)A.id&&i.set(A.id,A.name??A.id);const r=new Map;for(const A of e){const O=(k=A.runId)==null?void 0:k.trim();!O||r.has(O)||r.set(O,A)}const a=new Map;for(const A of e){const O=((T=A.initiativeId)==null?void 0:T.trim())??"",se=((D=A.workstreamId)==null?void 0:D.trim())??"";if(!O||!se)continue;const M=`${O}:${se}`;a.has(M)||a.set(M,A)}const l=new Set;for(const A of e){const O=(b=A.runId)==null?void 0:b.trim();O&&l.add(O)}const c=[];for(const A of t){const O=(A.sliceKind??"").trim().toLowerCase();if(O&&O!=="work_slice"||!rp.has(A.status))continue;const se=(A.runId??A.sliceRunId??"").trim();if(!se)continue;const M=Hs(A.initiativeIds,A.initiativeId),L=Hs(A.workstreamIds,A.workstreamId),ae=M[0]??null,be=L[0]??null;if(!ae||!be)continue;const ie=[];for(const G of M)for(const le of L)!G||!le||ie.push(`${G}:${le}`);if(!(l.has(se)||ie.some(G=>a.has(G))))continue;const xe=r.get(se)??(ie.length>0?ie.map(G=>a.get(G)??null).find(G=>!!G)??null:null),ne=ae?i.get(ae)??ae:null,K=A.scopeProgress&&typeof A.scopeProgress.totalTasks=="number"&&A.scopeProgress.totalTasks>0?Math.round(A.scopeProgress.completedTasks/A.scopeProgress.totalTasks*100):null;c.push({key:`slice:${A.sliceRunId}`,source:"slice",session:xe??null,runId:se,status:Lt(A.status),title:A.workstreamTitle??(xe==null?void 0:xe.title)??`Work slice ${A.sliceRunId.slice(0,8)}`,subtitle:A.statusExplainer??A.lastEventSummary??(xe==null?void 0:xe.lastEventSummary)??null,progress:K??(xe==null?void 0:xe.progress)??null,initiativeId:ae,initiativeIds:M,initiativeTitle:ne,workstreamId:be,workstreamIds:L,iwmtId:A.iwmtId??null,iwmtIds:Hs(A.iwmtIds,A.iwmtId),workstreamTitle:A.workstreamTitle??(xe==null?void 0:xe.title)??null,taskIds:Array.isArray(A.taskIds)?A.taskIds:[],milestoneIds:Array.isArray(A.milestoneIds)?A.milestoneIds:[],artifactCount:A.artifactCount??0,decisionCount:A.blockingDecisionCount??A.decisionCount??0,updatedAt:A.updatedAt??A.lastEventAt??(xe==null?void 0:xe.updatedAt)??null,scope:A.scope,milestoneProgress:(_=A.scopeProgress)==null?void 0:_.milestones})}c.sort((A,O)=>di(O.updatedAt)-di(A.updatedAt));const d=[],u=new Set,p=new Set,h=new Set;for(const A of c){const O=A.initiativeId??((H=A.initiativeIds)==null?void 0:H[0])??"none",se=A.workstreamId?`scope:${O}:${A.workstreamId}`:null,M=se??(A.runId?`run:${A.runId}`:A.key);u.has(M)||(u.add(M),A.runId&&p.add(A.runId),se&&h.add(se),d.push(A))}const y=e.filter(A=>{if(!op(A))return!1;const O=(A.initiativeId??"").trim(),se=(A.workstreamId??"").trim();if(O.length===0||se.length===0)return!1;const M=(A.runId??"").trim();return M&&p.has(M)?!1:!h.has(`scope:${O}:${se}`)});y.sort((A,O)=>{const se=di(A.updatedAt??A.lastEventAt??A.startedAt);return di(O.updatedAt??O.lastEventAt??O.startedAt)-se});const g=[],w=new Set;for(const A of y){const O=A.workstreamId&&A.workstreamId.trim().length>0?`${A.initiativeId??"none"}:${A.workstreamId}`:A.runId;w.has(O)||(w.add(O),g.push(A))}const N=g.map(A=>{var O;return{key:`session:${A.id}`,source:"session",session:A,runId:A.runId,status:Lt(A.status??""),title:A.title,subtitle:(O=A.lastEventSummary)!=null&&O.trim()?A.lastEventSummary.trim():null,progress:A.progress,initiativeId:A.initiativeId,initiativeIds:Hs(void 0,A.initiativeId),initiativeTitle:A.initiativeId?i.get(A.initiativeId)??A.groupLabel??null:A.groupLabel??null,workstreamId:A.workstreamId,workstreamIds:Hs(void 0,A.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:A.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:A.updatedAt??A.lastEventAt??A.startedAt??null}});return[...d,...N].sort((A,O)=>di(O.updatedAt)-di(A.updatedAt))}const hp=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:i=[],title:r="In Progress",className:a,showHeader:l=!0,panelStyle:c="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:p,onFocusRunId:h,onPlayWorkstream:y,onPauseWorkstream:g,onResumeWorkstream:w,onRestartSession:N,onIntervene:k,onOpenSliceDetail:T}){const[D,b]=o.useState(null),[_,H]=o.useState(null),[A,O]=o.useState(null),[se,M]=o.useState(null),L=o.useMemo(()=>{const G=new Map;if(!Array.isArray(s))return G;for(const le of s){const Le=Hs(le.initiativeIds,le.initiativeId),Me=Hs(le.workstreamIds,le.workstreamId);for(const Ne of Le)for(const E of Me){if(!Ne||!E)continue;const W=`${Ne}:${E}`;G.has(W)||G.set(W,le)}const me=(le.runId??le.sliceRunId??"").trim();me&&!G.has(`run:${me}`)&&G.set(`run:${me}`,le)}return G},[s]),ae=o.useMemo(()=>Cc({sessions:t,sliceRuns:s,initiatives:i}),[i,t,s]),be=o.useMemo(()=>{const G=new Map;for(const le of ae){const Le=Lt(le.status);G.set(Le,(G.get(Le)??0)+1)}return Array.from(G.entries()).sort((le,Le)=>Le[1]-le[1]).map(([le,Le])=>({status:le,count:Le}))},[ae]),ie=o.useMemo(()=>D?ae.filter(G=>Lt(G.status)===D):ae,[D,ae]),P=o.useMemo(()=>{var Me,me;const G=new Map,le=[];for(const Ne of ie){const E=(((Me=Ne.initiativeIds)==null?void 0:Me[0])??Ne.initiativeId??"").trim(),W=(((me=Ne.workstreamIds)==null?void 0:me[0])??Ne.workstreamId??"").trim();if(!E){le.push(Ne);continue}let V=G.get(E);V||(V={title:Ne.initiativeTitle??E,wsMap:new Map},G.set(E,V));const Y=W||"__none__";let Ie=V.wsMap.get(Y);Ie||(Ie={title:Ne.workstreamTitle??(W||"Unassigned"),rows:[],completedCount:0,lastActivity:null},V.wsMap.set(Y,Ie));const De=Lt(Ne.status);if(De==="completed"||De==="done"?Ie.completedCount+=1:Ie.rows.push(Ne),Ne.updatedAt){const he=Date.parse(Ne.updatedAt),je=Ie.lastActivity?Date.parse(Ie.lastActivity):0;Number.isFinite(he)&&he>je&&(Ie.lastActivity=Ne.updatedAt)}}const Le=[];for(const[Ne,E]of G){const W=[];for(const[V,Y]of E.wsMap)W.push({workstreamId:V,workstreamTitle:Y.title,rows:Y.rows,completedCount:Y.completedCount,lastActivityAt:Y.lastActivity});W.sort((V,Y)=>{const Ie=V.lastActivityAt?Date.parse(V.lastActivityAt):0;return(Y.lastActivityAt?Date.parse(Y.lastActivityAt):0)-Ie}),Le.push({initiativeId:Ne,initiativeTitle:E.title,workstreams:W})}return Le.sort((Ne,E)=>{const W=Math.max(0,...Ne.workstreams.map(Y=>Y.lastActivityAt?Date.parse(Y.lastActivityAt):0));return Math.max(0,...E.workstreams.map(Y=>Y.lastActivityAt?Date.parse(Y.lastActivityAt):0))-W}),{groups:Le,ungrouped:le}},[ie]),[xe,ne]=o.useState(new Set),K=async(G,le,Le)=>{if(G.session){M(null),H(G.session.id);try{await le(G.session),M(Le)}catch(Me){const me=Me instanceof Error?Me.message:"";M(me?Xt(me):"Workstream action failed")}finally{H(null)}}};return n.jsxs(Ts,{surface:c==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${c==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${a??""}`,children:[l?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:r}),n.jsx("span",{className:"chip text-micro",children:ae.length})]})}):null,be.length>1&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-subtle px-3 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>b(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${D===null?"border-lime/30 bg-lime/12 text-lime":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:ae.length})]}),be.map(({status:G,count:le})=>n.jsxs("button",{type:"button",onClick:()=>b(Le=>Le===G?null:G),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${D===G?"border-lime/30 bg-lime/12 text-lime":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[Sc(G),n.jsx("span",{className:"tabular-nums opacity-70",children:le})]},G))]}),se&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:se}),ie.length===0?ae.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"Execution paused"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active execution is moving in this scope right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"intervention is":"interventions are"," preventing the next slice from starting."]})]}),n.jsxs("button",{type:"button",onClick:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:ae.length===0?"No runs in progress.":"No runs match this filter."})}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-2",children:n.jsxs(ue.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[P.groups.map(G=>n.jsxs("div",{children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[n.jsx(en,{type:"initiative",size:13,className:"opacity-90"}),n.jsx("h3",{className:"text-[15px] font-semibold text-white/90",children:It(G.initiativeTitle&&!Wn(G.initiativeTitle)?G.initiativeTitle:eo(G.initiativeId,"Initiative"))})]}),G.workstreams.map(le=>{const Le=`${G.initiativeId}:${le.workstreamId}`,Me=xe.has(Le);return n.jsxs("div",{className:"pl-4 border-l border-white/[0.08] mb-3",children:[n.jsx("div",{className:"space-y-2",children:le.rows.map((me,Ne)=>n.jsx(dl,{row:me,index:Ne,sliceRunByScope:L,busySessionId:_,expandedRowKey:A,setExpandedRowKey:O,onOpenSession:p,onFocusRunId:h,onPauseWorkstream:g,onResumeWorkstream:w,onRestartSession:N,onPlayWorkstream:y,onIntervene:k,onOpenSliceDetail:T,runWorkstreamAction:K,showInitiativeLabel:!1},me.key))}),le.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>ne(me=>{const Ne=new Set(me);return Ne.has(Le)?Ne.delete(Le):Ne.add(Le),Ne}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:Me?`Hide ${le.completedCount} completed`:`${le.completedCount} completed`})})]},le.workstreamId)})]},G.initiativeId)),P.ungrouped.length>0&&n.jsxs("div",{children:[P.groups.length>0&&n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:"Ungrouped"}),n.jsx("div",{className:"space-y-2",children:P.ungrouped.map((G,le)=>n.jsx(dl,{row:G,index:le,sliceRunByScope:L,busySessionId:_,expandedRowKey:A,setExpandedRowKey:O,onOpenSession:p,onFocusRunId:h,onPauseWorkstream:g,onResumeWorkstream:w,onRestartSession:N,onPlayWorkstream:y,onIntervene:k,onOpenSliceDetail:T,runWorkstreamAction:K,showInitiativeLabel:!0},G.key))})]})]})})]})});function dl({row:e,index:t,sliceRunByScope:s,busySessionId:i,expandedRowKey:r,setExpandedRowKey:a,onOpenSession:l,onFocusRunId:c,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:p,onPlayWorkstream:h,onIntervene:y,onOpenSliceDetail:g,runWorkstreamAction:w,showInitiativeLabel:N=!0}){var Le,Me,me,Ne,E,W,V,Y,Ie,De;const k=Lt(e.status??""),T=e.updatedAt,D=e.subtitle?e.subtitle:T?`Updated ${Rt(T)}`:null,b=N&&(e.initiativeTitle||e.initiativeId)?It(e.initiativeTitle&&!Wn(e.initiativeTitle)?e.initiativeTitle:eo(e.initiativeId,"Initiative")):null,_=(Le=e.title)!=null&&Le.trim()?e.title:"",H=pp(_)&&((Me=e.workstreamTitle)!=null&&Me.trim())?e.workstreamTitle:_||e.workstreamTitle||"",A=eo(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),O=It(H&&!Wn(H)?H:A),se=D&&!fp(D)?It(D):null,M=dp(e.progress),L=["running","active","in_progress","working","planning","dispatching"].includes(k),ae=["paused","blocked","queued","pending"].includes(k),be=p??h,ie=M===null&&["running","active","in_progress","working","planning","dispatching"].includes(k),P=e.session?i===e.session.id:!1,xe=r===e.key,ne=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),K=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),G=e.scope==="task"?"task":e.scope==="milestone"?"milestone":e.scope==="workstream"||e.source==="slice"?"workstream":"session",le=sp((me=e.session)==null?void 0:me.agentId,(Ne=e.session)==null?void 0:Ne.agentName);return n.jsxs(ue.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.97,y:-6},layout:!0,transition:{duration:.24,delay:Math.min(t,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-visible rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 cursor-pointer transition-colors hover:border-white/[0.14]",onClick:()=>g==null?void 0:g(e,K),role:"button",tabIndex:0,onKeyDown:he=>{(he.key==="Enter"||he.key===" ")&&(he.preventDefault(),g==null||g(e,K))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${cp(k)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[n.jsx("div",{className:e.status==="running"?"agent-glow-ring rounded-full":"",style:e.status==="running"?{"--agent-glow-color":le.color}:void 0,children:n.jsx(Gt,{name:((E=e.session)==null?void 0:E.agentName)??"OrgX",hint:((W=e.session)==null?void 0:W.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[b?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:b}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(en,{type:G,size:12,className:"mt-[3px] flex-shrink-0 opacity-80"}),n.jsx("p",{className:"min-w-0 line-clamp-2 text-body font-semibold leading-snug text-white",title:O,children:O})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Ln,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] ${lp(k)}`,children:Sc(k)}),T&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:gd(new Date(T),{addSuffix:!0})})]}),se?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:se,children:se}):null,null,(M!==null||ie)&&n.jsxs("div",{className:"mt-2",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro",children:[n.jsx("span",{className:"text-secondary",children:"Progress"}),n.jsx("span",{className:"font-semibold text-primary tabular-nums",children:M===null?"Live":`${M}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${M===100?" shimmer-on-complete":""}`,children:M===null?n.jsx("div",{className:"h-full w-1/3 animate-pulse rounded-full bg-[#7dd3c0]/70"}):n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,M)}%`,background:`linear-gradient(90deg, ${al(rl((V=e.session)==null?void 0:V.agentId)).gradient[0]}, ${al(rl((Y=e.session)==null?void 0:Y.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(_c,{nodes:Fm({initiativeId:e.initiativeId,initiativeTitle:e.initiativeTitle,workstreamId:e.workstreamId,workstreamTitle:e.workstreamTitle,taskIds:e.taskIds,milestoneIds:e.milestoneIds,scopeProgress:e.milestoneProgress?{totalTasks:e.milestoneProgress.reduce((he,je)=>he+je.total,0),completedTasks:e.milestoneProgress.reduce((he,je)=>he+je.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((Ie=e.session)==null?void 0:Ie.agentName)??null,agentId:((De=e.session)==null?void 0:De.agentId)??null}),activeId:e.workstreamId,compact:!0})}),ne?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:he=>{he.stopPropagation(),a(je=>je===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-md px-1 text-micro font-semibold text-secondary transition-colors hover:text-white",children:xe?"Hide details":"Slice details"}),xe?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:he=>he.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){l==null||l(e.session.id);return}c==null||c(e.runId)},className:"control-pill h-7 px-2.5 text-micro font-semibold",title:e.session?"Open session detail":"Focus in Activity",children:e.session?"Open":"Focus"}),e.session&&L&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:P,onClick:()=>void w(e,d,`Paused ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Pause and return this workstream to queue",children:"Pause"}),e.session&&ae&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:P,onClick:()=>void w(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&be&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:P,onClick:()=>void w(e,be,`Restarted ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Restart this workstream",children:"Restart"}),e.session&&y&&n.jsx("button",{type:"button",disabled:P,onClick:()=>void w(e,y,`Opened intervention for ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Intervene with context and guidance",children:"Intervene"})]})]})]})]},e.key)}const gp={inbox:n.jsx("path",{d:"M22 12h-6l-2 3H10l-2-3H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),search:n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"m21 21-4.3-4.3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),activity:n.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),agents:n.jsx(n.Fragment,{children:n.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",stroke:"currentColor",strokeWidth:"1.5",fill:"none"})}),initiative:n.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),queue:n.jsxs(n.Fragment,{children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M8 12h8M12 8v8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),error:n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M12 9v4M12 17h.01",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};function la({icon:e="inbox",headline:t,description:s,primaryAction:i,secondaryAction:r,className:a}){return n.jsxs(ue.div,{className:fe("flex flex-col items-center justify-center py-12 px-6 text-center max-w-md mx-auto",a),initial:"hidden",animate:"visible",variants:{visible:{transition:{staggerChildren:.04}}},children:[n.jsx(ue.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:yr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:gp[e]})}),n.jsx(ue.h4,{className:"mt-5 text-heading font-semibold text-white",variants:yr,custom:1,children:t}),n.jsx(ue.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:yr,custom:2,children:s}),(i||r)&&n.jsxs(ue.div,{className:"mt-5 flex items-center gap-2",variants:yr,custom:3,children:[i&&n.jsx("button",{type:"button",onClick:i.onClick,className:"control-pill px-4 text-[12px] font-medium",style:{borderColor:"rgba(191, 255, 0, 0.24)",background:"rgba(191, 255, 0, 0.09)",color:"#d8ffa1"},children:i.label}),r&&n.jsx("button",{type:"button",onClick:r.onClick,className:"control-pill px-4 text-[12px] font-medium",children:r.label})]})]})}const xp=new Set(["awaiting_input","needs_review","failed"]),yp=[/credential/i,/api key/i,/provider/i,/auth/i,/token/i,/anthropic/i,/openai/i,/gateway/i,/secret/i,/permission/i];function ui(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Yr(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Wn(s)?`${t} ${Ss(s)}`:s}function Jr(e){if(!e)return null;const t=It(e);return t.length<10?null:t.length>88?`${t.slice(0,85)}…`:t}function bp(e){return It(e??"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()||"unknown"}function vp(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function wp(e){return e==="failed"?"border-red-400/30 bg-red-500/[0.10] text-red-100":e==="needs_review"?"border-amber-300/30 bg-amber-300/[0.10] text-amber-100":"border-lime/30 bg-lime/12 text-lime"}function kp(e){return e==="failed"?"from-red-300/0 via-red-300/65 to-red-300/0":e==="needs_review"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-lime/0 via-lime/70 to-lime/0"}function Ip(e){return e.primaryAction==="resolve_decision"?"Review decision":e.primaryAction==="open_artifact"?"Review output":e.primaryAction==="retry_slice"?"Review blocker":e.primaryAction==="review_output"?"Review output":"Open details"}function Np(e){const t=[];e.statusExplainer&&t.push(e.statusExplainer),e.lastEventSummary&&t.push(e.lastEventSummary);for(const s of e.blockers??[])s.reason&&t.push(s.reason),s.requiredAction&&t.push(s.requiredAction),s.waitingOn&&t.push(s.waitingOn);for(const s of e.pendingDecisions??[])s.title&&t.push(s.title),s.summary&&t.push(s.summary),s.recommendedAction&&t.push(s.recommendedAction);return t.some(s=>yp.some(i=>i.test(s)))}function ul(e){return Np(e)?"environment":e.primaryAction==="resolve_decision"||e.blockingDecisionCount>0||e.decisionCount>0?"decisions":e.status==="needs_review"||e.primaryAction==="review_output"||e.primaryAction==="open_artifact"||e.artifactCount>0?"review":"blockers"}function jp(e,t){const s=(e.pendingDecisions??[]).map(r=>r.id.trim()).filter(Boolean).sort();if(s.length>0)return`${t}:decision:${s.join("|")}`;const i=(e.blockers??[]).map(r=>r.id.trim()).filter(Boolean).sort();return i.length>0?`${t}:blocker:${i.join("|")}`:t==="environment"?`${t}:${bp(e.statusExplainer||e.lastEventSummary)}`:`${t}:${e.sliceRunId}`}function Ra(e,t,s){const i=(t==null?void 0:t.trim())??"";if(i&&!Wn(i)){const a=It(i);if(a&&a!=="Untitled session")return a}const r=Jr(e.statusExplainer);return r||(s?Yr(s,"Workstream"):Yr(e.sliceRunId,"Slice"))}function Ap(e,t,s,i){var c,d,u,p,h,y;const r=((u=(d=(c=t.pendingDecisions)==null?void 0:c[0])==null?void 0:d.title)==null?void 0:u.trim())??"",a=((y=(h=(p=t.blockers)==null?void 0:p[0])==null?void 0:h.reason)==null?void 0:y.trim())??"",l=Jr(t.statusExplainer);return e==="decisions"?It(r||a||l||Ra(t,s,t.workstreamId)):e==="environment"?It(a||r||l||"Environment setup required"):i>1&&(e==="blockers"||e==="review")?It(a||l||Ra(t,s,t.workstreamId)):It(Ra(t,s,t.workstreamId))}function _p(e){const{category:t,representative:s,duplicateCount:i,workstreamCount:r,decisionCount:a,artifactCount:l,blockingTaskCount:c}=e;if(t==="environment"){const d=Math.max(i,r);return`${d} slice${d===1?"":"s"} are waiting on the same environment or setup issue.`}return t==="decisions"?a>0?`${a} decision${a===1?"":"s"} need your judgment before dispatch can continue.`:"A blocking choice is preventing the next slice from starting.":t==="review"?l>0?`${l} artifact${l===1?"":"s"} are ready for review before the workflow continues.`:"Output is ready and needs a quick operator pass.":c>0?`This issue is blocking ${c} downstream task${c===1?"":"s"}.`:s.status==="failed"?"Execution stopped before the current slice could finish cleanly.":"This execution slice needs intervention to continue."}function Sp(e){switch(e){case"decisions":return{label:"Decisions",description:"Judgment calls that determine whether downstream work can proceed."};case"blockers":return{label:"Blockers",description:"Execution issues that require retry, intervention, or rerouting."};case"review":return{label:"Review-required",description:"Outputs or artifacts that need a quick human pass before continuation."};default:return{label:"Environment & setup",description:"Credentials, provider setup, or auth issues holding slices open."}}}function Br(e,t=[]){const s=e.filter(l=>xp.has(l.status)).sort((l,c)=>ui(c.updatedAt??c.lastEventAt??"")-ui(l.updatedAt??l.lastEventAt??"")),i=new Map,r=new Map;for(const l of t){l.id&&i.set(l.id,l.name??l.id);for(const c of l.workstreams??[])c.id&&!r.has(c.id)&&r.set(c.id,c.name??c.id)}const a=new Map;for(const l of s){const c=ul(l),d=jp(l,c),u=a.get(d);u?u.push(l):a.set(d,[l])}return Array.from(a.entries()).map(([l,c])=>{var O,se;const d=[...c].sort((M,L)=>ui(L.updatedAt??L.lastEventAt??"")-ui(M.updatedAt??M.lastEventAt??""))[0],u=ul(d);new Set(c.flatMap(M=>[...M.initiativeIds??[],M.initiativeId??""].filter(Boolean)));const p=new Set(c.flatMap(M=>[...M.workstreamIds??[],M.workstreamId??""].filter(Boolean))),h=d.initiativeIds&&d.initiativeIds[0]||d.initiativeId,y=d.workstreamTitle??(d.workstreamId?r.get(d.workstreamId)??null:null),g=h?i.get(h)??Yr(h,"Initiative"):p.size>1?`${p.size} workstreams`:Yr(d.workstreamId,"Workstream"),w=((se=(O=d.pendingDecisions)==null?void 0:O[0])==null?void 0:se.id)??null,N=c.reduce((M,L)=>M+Math.max(L.blockingDecisionCount,L.decisionCount),0),k=c.reduce((M,L)=>M+L.artifactCount,0),T=c.reduce((M,L)=>M+(L.blockingDecisionCount??0),0),D=c.length,b=p.size||D,_=Ap(u,d,y,D),H=_p({category:u,representative:d,duplicateCount:D,workstreamCount:b,decisionCount:N,artifactCount:k,blockingTaskCount:T}),A=D>1?`${b} workstream${b===1?"":"s"} · latest ${Rt(d.updatedAt??d.lastEventAt??"")}`:Jr(d.lastEventSummary)??Jr(d.statusExplainer);return{key:l,item:d,items:c,category:u,duplicateCount:D,workstreamCount:b,decisionCount:N,blockingTaskCount:T,artifactCount:k,title:_,summary:It(H),subtitle:A?It(A):null,initiativeText:It(g),actionLabel:Ip(d),scopeText:d.scope?d.scope.replace(/_/g," "):null,updatedAt:d.updatedAt??d.lastEventAt??null,pendingDecisionId:w}}).sort((l,c)=>{const d={decisions:0,blockers:1,review:2,environment:3},u=d[l.category]-d[c.category];return u!==0?u:ui(c.updatedAt)-ui(l.updatedAt)})}function Cp(e){return["decisions","blockers","review","environment"].map(s=>{const i=e.filter(a=>a.category===s);if(i.length===0)return null;const r=Sp(s);return{key:s,label:r.label,description:r.description,rows:i}}).filter(s=>!!s)}const Tp=o.memo(function({sliceRuns:t,initiatives:s=[],title:i="Needs Input",className:r,showHeader:a=!0,panelStyle:l="card",onOpenDecisions:c,onFocusRunId:d,onReviewActivity:u,onOpenSliceDetail:p}){const h=o.useMemo(()=>Br(t,s),[t,s]),y=o.useMemo(()=>Cp(h),[h]),[g,w]=o.useState(!1),[N,k]=o.useState(new Set),T=o.useMemo(()=>h.filter(ie=>N.has(ie.key)),[h,N]),D=o.useMemo(()=>T.reduce((ie,P)=>(ie[P.category]+=1,ie),{decisions:0,blockers:0,review:0,environment:0}),[T]),b=o.useMemo(()=>{var P;const ie=new Set;for(const xe of T)for(const ne of xe.items){const K=(P=ne.workstreamId)==null?void 0:P.trim();K&&ie.add(K);for(const G of ne.workstreamIds??[]){const le=G.trim();le&&ie.add(le)}}return ie.size||T.length},[T]),_=T.reduce((ie,P)=>ie+P.decisionCount,0),H=T.filter(ie=>ie.category==="review").length,A=o.useMemo(()=>[D.decisions>0?`${D.decisions} decision ${D.decisions===1?"group":"groups"}`:null,D.blockers>0?`${D.blockers} blocker${D.blockers===1?"":"s"}`:null,D.review>0?`${D.review} review item${D.review===1?"":"s"}`:null,D.environment>0?`${D.environment} setup issue${D.environment===1?"":"s"}`:null].filter(ie=>!!ie),[D]),O=h.length>0&&h.every(ie=>N.has(ie.key)),se=()=>{k(new Set),w(!1)},M=ie=>{k(P=>{const xe=new Set(P);return xe.has(ie)?xe.delete(ie):xe.add(ie),xe})},L=()=>{k(ie=>O?new Set:new Set(h.map(P=>P.key)))},ae=ie=>{var xe;const P=ie.item;if(P.primaryAction==="resolve_decision"){c==null||c(ie.pendingDecisionId);return}if(P.primaryAction==="review_output"||P.primaryAction==="retry_slice"){u==null||u(P);return}if(P.primaryAction==="open_artifact"){const ne=(xe=P.artifacts.find(K=>K.url))==null?void 0:xe.url;if(ne&&typeof window<"u"){window.open(ne,"_blank","noopener,noreferrer");return}u==null||u(P);return}if(P.runId){d==null||d(P.runId);return}p==null||p(P)},be=()=>{var ie;if(T.length!==0){if(T.length===1){ae(T[0]);return}if(_>0){const P=((ie=T.find(xe=>xe.pendingDecisionId))==null?void 0:ie.pendingDecisionId)??null;c==null||c(P);return}p==null||p(T[0].item)}};return n.jsxs(Ts,{surface:l==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${l==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${r??""}`,children:[a?n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:i}),n.jsx("span",{className:"chip text-micro",children:h.length})]}),h.length>0?n.jsx("div",{className:"flex items-center gap-2",children:g?n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:L,className:"control-pill h-8 px-3 text-caption font-semibold",children:O?"Clear all":"Select all"}),n.jsx("button",{type:"button",onClick:se,className:"control-pill h-8 px-3 text-caption font-semibold",children:"Cancel"})]}):n.jsx("button",{type:"button",onClick:()=>w(!0),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Select"})}):null]}):null,h.length===0?n.jsx(la,{icon:"inbox",headline:"No slices need attention",description:"All workstreams are running smoothly. Decisions will appear here when agents need your input."}):n.jsxs(n.Fragment,{children:[!a&&h.length>0?n.jsx("div",{className:"border-b border-subtle px-3 py-2.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-white/40",children:"Intervention controls"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Group similar issues, then review a focused decision or blocker basket."})]}),n.jsx("div",{className:"flex items-center gap-2",children:g?n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:L,className:"control-pill h-8 px-3 text-caption font-semibold",children:O?"Clear all":"Select all"}),n.jsx("button",{type:"button",onClick:se,className:"control-pill h-8 px-3 text-caption font-semibold",children:"Cancel"})]}):n.jsx("button",{type:"button",onClick:()=>w(!0),className:"control-pill h-8 px-3 text-caption font-semibold",children:"Select"})})]})}):null,n.jsx("div",{className:`min-h-0 flex-1 space-y-3 overflow-y-auto px-3 py-2 ${g?"pb-20":""}`,children:n.jsx(bt,{mode:"popLayout",children:y.map(ie=>n.jsxs(ue.section,{layout:!0,initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.22,ease:[.22,1,.36,1]},className:"rounded-2xl border border-white/[0.06] bg-white/[0.02]",children:[n.jsxs("div",{className:"border-b border-white/[0.06] px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:ie.label}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:ie.rows.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:ie.description})]}),n.jsx("div",{className:"space-y-2 p-2",children:ie.rows.map((P,xe)=>{const ne=N.has(P.key);return n.jsxs(ue.article,{layout:!0,initial:{opacity:0,y:8,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.97,y:-6},transition:{duration:.22,delay:Math.min(xe,6)*.018,ease:[.22,1,.36,1]},className:`group relative overflow-hidden rounded-2xl border bg-white/[0.02] px-3 py-2.5 transition-colors ${ne?"border-lime/30 shadow-[0_0_0_1px_rgba(191,255,0,0.12)]":P.item.status==="failed"?"border-red-400/16 hover:border-red-300/28":"border-white/[0.08] hover:border-white/[0.14]"}`,role:"button",tabIndex:0,onClick:()=>{if(g){M(P.key);return}p==null||p(P.item)},onKeyDown:K=>{if(!(K.key!=="Enter"&&K.key!==" ")){if(K.preventDefault(),g){M(P.key);return}p==null||p(P.item)}},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${kp(P.item.status)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex items-start gap-2.5",children:[g?n.jsx("input",{type:"checkbox",checked:ne,onChange:()=>M(P.key),onClick:K=>K.stopPropagation(),className:"mt-0.5 h-4 w-4 rounded border-white/20 bg-black/40 text-lime focus:ring-lime/40","aria-label":`Select ${P.title}`}):null,n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex min-w-0 items-center gap-1 text-micro uppercase tracking-[0.08em] text-muted",children:[n.jsx(en,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:P.initiativeText})]}),n.jsxs("p",{className:"mt-0.5 inline-flex min-w-0 items-start gap-1.5 text-body font-semibold leading-snug text-white",title:P.title,children:[n.jsx(en,{type:P.category==="decisions"?"decision":"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:P.title})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:P.summary,children:P.summary}),P.subtitle?n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:P.subtitle,children:P.subtitle}):null]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-1.5",children:[n.jsx("span",{className:`inline-flex h-6 items-center rounded-full border px-2 text-micro font-semibold uppercase tracking-[0.08em] ${wp(P.item.status)}`,children:vp(P.item.status)}),P.scopeText?n.jsx("span",{className:"chip text-micro capitalize",children:P.scopeText}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[P.duplicateCount>1?n.jsxs("span",{className:"chip text-micro",children:[P.workstreamCount," similar slices"]}):null,P.blockingTaskCount>0?n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",P.blockingTaskCount," task",P.blockingTaskCount===1?"":"s"]}):null,P.decisionCount>0?n.jsxs("span",{className:"chip text-micro",children:[P.decisionCount," decision",P.decisionCount===1?"":"s"]}):null,P.artifactCount>0?n.jsxs("span",{className:"chip text-micro",children:[P.artifactCount," artifact",P.artifactCount===1?"":"s"]}):null,P.updatedAt?n.jsxs("span",{children:["Updated ",Rt(P.updatedAt)]}):null]}),P.item.decisionOptions&&P.item.decisionOptions.length>0&&P.item.decisionOptions.length<=3?n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:K=>K.stopPropagation(),children:P.item.decisionOptions.slice(0,3).map(K=>n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(P.item),className:"chip text-micro font-medium hover:bg-white/[0.08] transition-colors cursor-pointer",title:K.description??K.label,"aria-label":`Review option ${K.label}`,children:K.label},K.id))}):null,g?null:n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:K=>K.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(P.item),className:"control-pill h-7 px-2.5 text-micro font-semibold","aria-label":`Open details for ${P.title}`,children:"Details"}),n.jsx("button",{type:"button",onClick:()=>ae(P),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":P.item.status==="failed"?"teal":void 0,"aria-label":`${P.actionLabel} for ${P.title}`,children:P.actionLabel})]})]})]})]},P.key)})})]},ie.key))})}),g?n.jsx("div",{className:"border-t border-subtle bg-black/40 px-3 py-2.5 backdrop-blur-xl",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"min-w-0 space-y-1",children:[n.jsxs("p",{className:"text-caption font-semibold text-white",children:[T.length," selected"]}),n.jsx("p",{className:"text-micro leading-relaxed text-secondary",children:"Review the selected intervention basket before routing the operator to a focused blocker or decision flow."})]}),n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[A.length>0?A.map(ie=>n.jsx("span",{className:"chip text-micro",children:ie},ie)):n.jsx("span",{className:"chip text-micro",children:"Review the selected intervention basket"}),n.jsxs("span",{className:"chip text-micro",children:[b," workstream",b===1?"":"s"]})]}),n.jsx("p",{className:"text-micro leading-relaxed text-white/45",children:_>0?`Routes ${_} pending decision${_===1?"":"s"} into the review flow.`:H>0?`Focuses the selected review work across ${b} workstream${b===1?"":"s"}.`:`Focuses the selected intervention basket across ${b} workstream${b===1?"":"s"}.`}),n.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[n.jsx("button",{type:"button",onClick:()=>k(new Set),disabled:T.length===0,className:"control-pill h-9 w-full justify-center px-3 text-caption font-semibold disabled:opacity-40",children:"Clear"}),n.jsx("button",{type:"button",onClick:be,disabled:T.length===0,className:"control-pill h-9 w-full justify-center px-3 text-caption font-semibold disabled:opacity-40","data-tone":T.length>0?"lime":void 0,children:T.length<=1?"Open selected":_>0&&D.decisions===T.length?"Review decision basket":H>0&&D.review===T.length?"Review output basket":"Open selected basket"})]})]})}):null]})]})});function Mp(e){if(!e)return"Unknown";const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toLocaleString():"Unknown"}function ml(e){return e?Rt(e):"unknown"}const Ep={run_completed:"text-lime",milestone_completed:"text-teal-200",artifact_created:"text-cyan-200",handoff_fulfilled:"text-violet-200",decision_resolved:"text-amber-200",run_started:"text-white/80",delegation:"text-white/80"};function Rp(e){var i;const t=wi(e);if(t.update)return t.update;const s=(i=e.title)==null?void 0:i.trim();return s||e.type.replace(/_/g," ")}const Lp=o.memo(function({className:t,rows:s,onFocusRunId:i,onOpenNextUp:r}){return s.length===0?n.jsx(Ts,{className:t??"",children:n.jsx("div",{className:"flex h-full min-h-[220px] items-center justify-center px-5 py-8 text-center",children:n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"No completed work in this scope yet."}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Completed slices will appear here with full scope, artifacts, and timeline."})]})})}):n.jsx("div",{className:`flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2 ${t??""}`,children:s.map((a,l)=>n.jsxs(ue.section,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.26,delay:Math.min(l,6)*.035,ease:[.22,1,.36,1]},className:"rounded-2xl border border-subtle bg-white/[0.02] px-3 py-2.5",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-body font-semibold text-primary",children:It(a.title)}),n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Completed ",ml(a.completedAt)," · ",Mp(a.completedAt)]}),a.statusExplainer?n.jsx("p",{className:"mt-0.5 truncate text-micro text-muted",children:It(a.statusExplainer)}):null]}),n.jsx(Ln,{tone:"lime",className:"whitespace-nowrap",children:"Completed"})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Hierarchy"}),n.jsx("p",{className:"mt-1 text-caption text-primary",children:It([a.initiativeTitle,a.workstreamTitle].filter(Boolean).join(" > ")||"Unscoped")}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[a.scope&&n.jsx("span",{className:"chip capitalize",children:a.scope}),n.jsxs("span",{className:"chip",children:[a.taskIds.length," tasks"]}),n.jsxs("span",{className:"chip",children:[a.milestoneIds.length," milestones"]})]})]}),(a.whatChanged||a.whatThisUnlocked||a.nextUp.length>0)&&n.jsxs("div",{className:"mt-2 grid gap-2 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[n.jsxs("div",{className:"rounded-lg border border-subtle bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"What changed"}),n.jsx("p",{className:"mt-1 text-caption text-primary",children:It(a.whatChanged??a.statusExplainer??"Completed work landed without a richer change summary.")}),a.whatThisUnlocked?n.jsxs("p",{className:"mt-2 text-micro text-secondary",children:["Unlocked: ",It(a.whatThisUnlocked)]}):null]}),n.jsxs("div",{className:"rounded-lg border border-lime/18 bg-lime/[0.05] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-lime/70",children:"Connects to next up"}),a.nextUp.length>0?n.jsx("ul",{className:"mt-1.5 space-y-1",children:a.nextUp.slice(0,4).map(c=>n.jsx("li",{className:"text-caption text-primary",children:It(c)},c))}):n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Open Next Up to continue from this completed scope."})]})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2.5",children:[n.jsxs("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:["Artifacts (",a.artifactCount,")"]}),a.artifacts.length>0?n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:a.artifacts.map(c=>n.jsxs("li",{className:"flex items-center justify-between gap-2 text-caption",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-primary",children:It(c.title)}),n.jsxs("p",{className:"text-micro text-secondary",children:[c.type??"artifact"," · ",ml(c.createdAt)]})]}),c.url?n.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-primary transition hover:bg-white/[0.08]",children:"Open"}):null]},`${a.key}:${c.id??c.title}`))}):n.jsx("p",{className:"mt-1.5 text-caption text-secondary",children:"No artifact metadata attached."})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2.5",children:[n.jsxs("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:["Timeline (",a.timelineEvents.length,")"]}),a.timelineEvents.length>0?n.jsx("ul",{className:"mt-1.5 space-y-1",children:a.timelineEvents.map((c,d)=>{const u=Ep[c.type]??"text-primary",p=wi(c);return n.jsxs(ue.li,{initial:{opacity:0,x:-4},animate:{opacity:1,x:0},transition:{duration:.2,delay:Math.min(d,8)*.025,ease:[.22,1,.36,1]},className:"flex items-start justify-between gap-2 text-caption",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:`truncate ${u}`,children:It(Rp(c))}),p.nextUp[0]?n.jsx("p",{className:"truncate text-micro text-secondary",children:It(p.nextUp[0])}):c.description?n.jsx("p",{className:"truncate text-micro text-secondary",children:It(c.description)}):null]}),n.jsx("span",{className:"whitespace-nowrap text-micro text-muted",children:Rt(c.timestamp)})]},`${a.key}:event:${c.id}`)})}):n.jsx("p",{className:"mt-1.5 text-caption text-secondary",children:"No related timeline events found."})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[i?n.jsx("button",{type:"button",onClick:()=>i(a.runId),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}):null,r?n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-lime/28 bg-lime/12 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/18",children:"Connect back to Next Up"}):null]})]},a.key))})});function Dp(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function $p(e){if(!e)return 0;const t=new Date(e),s=new Date;return Math.max(0,Math.ceil((t.getTime()-s.getTime())/864e5))}function Pp(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Op(e){return{id:e.id,name:e.title,status:Dp(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:$p(e.target_date),targetDate:e.target_date??null,createdAt:e.created_at??null,updatedAt:e.updated_at??e.created_at??null,activeAgents:0,totalAgents:0,description:e.summary??void 0}}const pl=150,qp=12;function fl(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Fp(){const e=new Date,t=864e5;return[{id:"init-1",name:"Content Engine: Dogfood the Larry Playbook",status:"active",rawStatus:"active",priority:"critical",health:56,daysRemaining:9,targetDate:new Date(e.getTime()+9*t).toISOString(),createdAt:new Date(e.getTime()-24*t).toISOString(),updatedAt:new Date(e.getTime()-4*6e4).toISOString(),activeAgents:3,totalAgents:4,description:"Drafting long-form content, clearing legal review, and preparing distribution schedule."},{id:"init-2",name:"Live View UX Redesign — The Conductor's Display",status:"active",rawStatus:"active",priority:"high",health:44,daysRemaining:6,targetDate:new Date(e.getTime()+6*t).toISOString(),createdAt:new Date(e.getTime()-17*t).toISOString(),updatedAt:new Date(e.getTime()-3*6e4).toISOString(),activeAgents:3,totalAgents:4,description:"Improving activity readability, developer-mode gating, and collapse-state spacing quality."},{id:"init-3",name:"Directory Submissions & External References",status:"active",rawStatus:"active",priority:"medium",health:49,daysRemaining:12,targetDate:new Date(e.getTime()+12*t).toISOString(),createdAt:new Date(e.getTime()-19*t).toISOString(),updatedAt:new Date(e.getTime()-1*6e4).toISOString(),activeAgents:4,totalAgents:5,description:"Parallel directory import, reference QA, and partner outreach with active artifact production."},{id:"init-4",name:"Revenue Expansion Q2",status:"completed",rawStatus:"completed",priority:"low",health:100,daysRemaining:0,targetDate:new Date(e.getTime()-1*t).toISOString(),createdAt:new Date(e.getTime()-45*t).toISOString(),updatedAt:new Date(e.getTime()-42*6e4).toISOString(),activeAgents:0,totalAgents:2,description:"Completed closeout package with reconciled variance sheet and executive sign-off trail."},{id:"init-5",name:"Incident Replay & Reliability",status:"blocked",rawStatus:"blocked",priority:"critical",health:24,daysRemaining:3,targetDate:new Date(e.getTime()+3*t).toISOString(),createdAt:new Date(e.getTime()-13*t).toISOString(),updatedAt:new Date(e.getTime()-25*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Replay pipeline is blocked on archive restore approval and backup snapshot decision."}]}function Tc(e,t=null){return ei({queryKey:rs.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Hn())return Fp();const s=[],i=(t==null?void 0:t.trim())??"";let r=0;for(let d=0;d<qp;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(pl),offset:String(r)});i&&gs(u,i);const p=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:Ot({workspaceId:i})});if(!p.ok)break;const h=await p.json(),y=h.data??[];if(s.push(...y),!!!((c=h.pagination)!=null&&c.has_more)||y.length===0)break;r+=pl}const a=i.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),l=new Map;for(const d of s){const u=l.get(d.id);if(!u){l.set(d.id,d);continue}fl(d.updated_at??d.created_at)>fl(u.updated_at??u.created_at)&&l.set(d.id,d)}return Array.from(l.values()).filter(d=>!i||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===i).filter(d=>Pp(d.status)).sort((d,u)=>{const p=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-p}).map(Op)},enabled:e,staleTime:6e4})}const vr=50,hl=8;function Bp(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Up(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function zp(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Wp(e){const t=zp(e.sequence);return{id:e.id,name:e.title,status:Bp(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,sequenceIndex:t,hierarchyLabel:typeof t=="number"?`I${t+1}`:void 0,activeAgents:e.activeAgents??0,totalAgents:e.totalAgents??0,description:void 0}}function Hp(e,t=null){return ei({queryKey:rs.liveInitiatives({limit:vr*hl,projectId:t}),queryFn:async()=>{var l;if(Hn())return[];const s=[];let i=0;for(let c=0;c<hl;c+=1){const d=new URLSearchParams({limit:String(vr),offset:String(i)});t&&t.trim().length>0&&gs(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:Ot({workspaceId:t})});if(!u.ok)break;const p=await u.json(),h=p.initiatives??[];s.push(...h);const y=typeof p.total=="number"?p.total:null,g=(l=p.pagination)==null?void 0:l.has_more;if(!(typeof g=="boolean"?g:y!==null?i+h.length<y:h.length===vr)||h.length===0)break;i+=vr}const r=(t==null?void 0:t.trim())??"",a=r.length>0&&s.some(c=>(c.command_center_id??c.commandCenterId??"").trim().length>0);return s.filter(c=>!r||!a?!0:(c.command_center_id??c.commandCenterId??"").trim()===r).filter(c=>Up(c.status)).map(Wp)},enabled:e,staleTime:3e4})}const Mc=o.createContext(null);function Kp({children:e}){const[t,s]=o.useState({artifactId:null}),i=o.useCallback((a,l)=>{s({artifactId:a,context:l})},[]),r=o.useCallback(()=>{s({artifactId:null})},[]);return n.jsx(Mc.Provider,{value:{state:t,open:i,close:r},children:e})}function Ec(){const e=o.useContext(Mc);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Vp(e){const{running:t,blocked:s,decisionsCount:i,completedToday:r,onNeedsAttentionClick:a,onDecisionsClick:l,onBlockedClick:c,onNewInitiative:d}=e,u=i+s,p=a??l??c;if(t===0&&u===0&&r===0)return{key:"idle-empty",segments:[{text:"All caught up. "},d?{text:"Start something new?",color:q.lime,clickable:!0,onClick:d}:{text:"Nothing running."}]};if(t===0&&u===0)return{key:"idle-done",segments:[{text:`${r} done today`,color:q.teal},{text:" · all caught up"}]};if(u>0){const h=s>0&&i>0?`${s} blocked · ${i} decisions need your input`:s>0?`${s} blocked`:`${i} decisions need your input`;return{key:`needs-attention-${u}-${s}-${i}-${t}`,segments:[...t>0?[{text:`${t} running`,color:q.lime},{text:" · "}]:[],{text:`${u} needs attention`,color:q.amber,clickable:!!p,onClick:p},{text:` · ${h}`}]}}return{key:`running-${t}`,segments:[{text:`${t} running`,color:q.lime},{text:" · all systems go"}]}}function gl(e){const{className:t}=e,{key:s,segments:i}=Vp(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(bt,{mode:"wait",children:n.jsx(ue.span,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.18,ease:[.22,1,.36,1]},className:"inline-flex flex-wrap items-baseline gap-0",children:i.map((r,a)=>r.clickable&&r.onClick?n.jsx("button",{onClick:r.onClick,className:"font-semibold underline decoration-dotted underline-offset-4 transition-opacity hover:opacity-80",style:{color:r.color},children:r.text},a):n.jsx("span",{className:r.color?"font-semibold":"text-secondary",style:r.color?{color:r.color}:void 0,children:r.text},a))},s)})})}const Kx={active:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",paused:"text-[#F5B700] bg-[#F5B700]/10 border-[#F5B700]/20",blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20"},Gp={done:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",in_progress:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",active:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",todo:"text-white/60 bg-white/5 border-white/10"},Vx=e=>Gp[Lt(e)]??"text-white/60 bg-white/5 border-white/10",Gx=e=>{const t=Lt(e);return t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":t==="blocked"?"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20":t==="completed"||t==="done"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":"text-white/60 bg-white/5 border-white/10"},Xx=e=>{const t=Lt(e);return t==="done"||t==="completed"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":"text-white/60 bg-white/5 border-white/10"},Qx=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Yx=e=>{const t=Lt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},Ks=e=>{const t=Lt(e);return t==="blocked"||t==="failed"||t==="cancelled"?q.red:t==="active"||t==="in_progress"||t==="running"?q.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?q.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?q.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Zr={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:q.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:q.teal,tint:"rgba(20, 184, 166, 0.18)"}},Xp=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Ur(e,t,s,i){if(!(e==null||s>2)){if(typeof e=="string"){const r=e.trim();r.length>0&&t.push(r);return}if(Array.isArray(e)){for(const r of e)Ur(r,t,s+1,i);return}if(typeof e=="object"){if(i.has(e))return;i.add(e);for(const[r,a]of Object.entries(e)){const l=r.toLowerCase();typeof a=="string"?(Xp.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&Ur(a,t,s+1,i):typeof a=="object"&&a!==null&&Ur(a,t,s+1,i)}}}}function Qp(e){const t=e.toLowerCase();return/\bcodex\b/.test(t)||/\bcursor\b/.test(t)||t.includes("openai/codex")?"codex":t.includes("openclaw")||t.includes("clawdbot")||t.includes("moltbot")?"openclaw":t.includes("anthropic")||t.includes("claude")||t.includes("sonnet")||t.includes("opus")?"anthropic":t.includes("openai")||t.includes("chatgpt")||/\bgpt[-\s]?\d/.test(t)||/\bo[134]/.test(t)?"openai":t.includes("orgx")?"orgx":null}function Cs(...e){const t=[],s=new Set;for(const i of e)Ur(i,t,0,s);for(const i of t){const r=Qp(i);if(r)return Zr[r]}return Zr.unknown}function Yp(e){return Zr[e]??Zr.unknown}const Jp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]),Zp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),ef=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff","review"]),tf=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping","stalled","awaiting_input","needs_review","needs_decision","review_required"]);function Jx(e){return Jp.has(Lt(e))}function nf(e){return Zp.has(Lt(e))}function mo(e){return ef.has(Lt(e))}function sf(e){return tf.has(Lt(e))}const rf={xs:18,sm:24,md:30};function af({provider:e}){switch(e){case"openai":case"codex":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"})});case"anthropic":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"})});case"openclaw":return n.jsxs("svg",{viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("path",{d:"M60 10C30 10 15 35 15 55C15 75 30 95 45 100V110H55V100C55 100 60 102 65 100V110H75V100C90 95 105 75 105 55C105 35 90 10 60 10Z",fill:"currentColor"}),n.jsx("path",{d:"M20 45C5 40 0 50 5 60C10 70 20 65 25 55C28 48 25 45 20 45Z",fill:"currentColor"}),n.jsx("path",{d:"M100 45C115 40 120 50 115 60C110 70 100 65 95 55C92 48 95 45 100 45Z",fill:"currentColor"}),n.jsx("circle",{cx:"45",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"}),n.jsx("circle",{cx:"75",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"})]});case"orgx":return n.jsx("img",{src:aa,alt:"","aria-hidden":"true",className:"h-full w-full rounded-[4px] object-contain"});default:return n.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor",strokeWidth:"1.8",fill:"none"}),n.jsx("path",{d:"m12 6-2 7h3l-1 5 4-8h-3l1-4Z",fill:"currentColor"})]})}}function yi({provider:e,size:t="sm",className:s,showRing:i=!0}){const r=Yp(e),a=rf[t];return n.jsx("span",{className:fe("inline-flex items-center justify-center rounded-md",s),style:{width:a,height:a,color:r.accent,backgroundColor:r.tint,border:i?`1px solid ${r.accent}55`:"none"},title:r.label,"aria-label":r.label,children:n.jsx("span",{style:{width:Math.round(a*.66),height:Math.round(a*.66),display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(af,{provider:e})})})}function Rc({running:e,blocked:t,paused:s,size:i=36,children:r}){const a=xs(),l=e+t+s,c=o.useMemo(()=>{if(l===0)return[];const g=[];return e>0&&g.push({color:q.lime,fraction:e/l}),t>0&&g.push({color:q.red,fraction:t/l}),s>0&&g.push({color:q.amber,fraction:s/l}),g},[e,t,s,l]),d=2.5,u=(i-d)/2,p=2*Math.PI*u,h=i/2;if(l===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:i,height:i},children:[n.jsx("svg",{width:i,height:i,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:h,cy:h,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:r})]});let y=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:i,height:i},children:[n.jsxs("svg",{width:i,height:i,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:h,cy:h,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),c.map((g,w)=>{const N=g.fraction*p,k=-y;return y+=N,n.jsx(ue.circle,{cx:h,cy:h,r:u,fill:"none",stroke:g.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${N} ${p-N}`,strokeDashoffset:k,initial:a?!1:{strokeDasharray:`0 ${p}`},animate:{strokeDasharray:`${N} ${p-N}`},transition:{duration:.5,delay:w*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},w)})]}),n.jsx("div",{className:"relative z-10",children:r})]})}const wr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function po(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function fo(e,t){if(typeof t=="number")return`${e}${t+1}`}const of=(e,t)=>{const s=po(e.sequence??e.order);return{id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fo("W",s)}},lf=(e,t)=>{const s=po(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fo("M",s)}},cf=(e,t)=>{const s=po(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fo("T",s)}};function La(e){return[...e].sort((t,s)=>{const i=typeof t.sequenceIndex=="number"?t.sequenceIndex:Number.POSITIVE_INFINITY,r=typeof s.sequenceIndex=="number"?s.sequenceIndex:Number.POSITIVE_INFINITY;if(i!==r)return i-r;const a=t.createdAt?Date.parse(t.createdAt):0,l=s.createdAt?Date.parse(s.createdAt):0;return a!==l?a-l:0})}function df(e){const t=new Date().toISOString();return e==="init-1"?{initiativeId:e,workstreams:[{id:"ws-4",name:"Dashboard UI pass",summary:"Polish interaction details and close accessibility feedback.",status:"active",progress:70,initiativeId:e,createdAt:t},{id:"ws-5",name:"Usage tracking instrumentation",summary:"Waiting on events table access.",status:"blocked",progress:25,initiativeId:e,createdAt:t}],milestones:[{id:"ms-1",title:"UX polish complete",description:"All blocking review comments resolved.",status:"active",dueDate:null,initiativeId:e,workstreamId:"ws-4",createdAt:t}],tasks:[{id:"task-1",title:"Polish timeline controls",description:null,status:"in_progress",priority:"high",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-2",title:"Validate mobile overlays",description:null,status:"todo",priority:"medium",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-3",title:"Grant data pipeline access",description:null,status:"blocked",priority:"high",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-5",createdAt:t}]}:{initiativeId:e,workstreams:[{id:"ws-9",name:"Email campaign generation",summary:"Final review of subject line variants.",status:"active",progress:55,initiativeId:e,createdAt:t}],milestones:[],tasks:[{id:"task-9",title:"Prepare launch variants",description:null,status:"in_progress",priority:"medium",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-9",createdAt:t}]}}function uf({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:i=!0}){var c;const r=fu(e),a=o.useMemo(()=>rs.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),l=ei({queryKey:a,enabled:i&&!!e&&r,queryFn:async()=>{if(!e)return wr;if(Hn())return df(e);if(!r)return{...wr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,p=async T=>{try{const D=new URLSearchParams({type:T,initiative_id:e,limit:"100"}),b=await fetch(`/orgx/api/entities?${D.toString()}`,{headers:u});return b.ok?await b.json():{data:[]}}catch{return{data:[]}}},[h,y,g]=await Promise.all([p("workstream"),p("milestone"),p("task")]),w=Array.isArray(h.data)?La(h.data.map(T=>of(T,e))):[],N=Array.isArray(y.data)?La(y.data.map(T=>lf(T,e))):[],k=Array.isArray(g.data)?La(g.data.map(T=>cf(T,e))):[];return{initiativeId:e,workstreams:w,milestones:N,tasks:k}}});return{details:(r?l.data:null)??(e?{...wr,initiativeId:e}:wr),isLoading:r?l.isLoading:!1,error:r?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function mf(){const e=new Date().toISOString();return{generatedAt:e,agents:[{id:"eli",name:"Eli",workspace:"Q4 Feature Ship",model:"gpt-5",isDefault:!0,status:"running",currentTask:"Planning",runId:"run-1",startedAt:e,blockers:[],context:null},{id:"dana",name:"Dana",workspace:"Q4 Feature Ship",model:"claude-sonnet-4.5",isDefault:!1,status:"running",currentTask:"Dashboard UI pass",runId:"run-2",startedAt:e,blockers:["Approval pending"],context:null},{id:"mark",name:"Mark",workspace:"Black Friday Email",model:"gpt-5-mini",isDefault:!1,status:"running",currentTask:"Campaign variants",runId:"run-4",startedAt:e,blockers:[],context:null}]}}function ho({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return ei({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Hn())return mf();const i=await fetch("/orgx/api/agents/catalog");if(!i.ok){const r=await i.text().catch(()=>"");throw new Error(r||`Agent catalog failed (${i.status})`)}return await i.json()},enabled:e,staleTime:t,refetchInterval:s??(e?8e3:!1)})}function Di(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:q.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:q.iris,bg:"rgba(124,124,255,0.10)"}}function pf(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function ff(e,t){return[...t?e.tasks.filter(i=>i.workstreamId===t):e.tasks].sort((i,r)=>i.title.localeCompare(r.title))}function hf({open:e,onClose:t,onLaunched:s}){var V,Y,Ie,De,he,je;const i=ho({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:r}=Tc(e),[a,l]=o.useState(""),[c,d]=o.useState(""),[u,p]=o.useState(""),[h,y]=o.useState(""),[g,w]=o.useState("auto"),[N,k]=o.useState(""),[T,D]=o.useState(null),[b,_]=o.useState(null),[H,A]=o.useState("starter"),[O,se]=o.useState(!1),[M,L]=o.useState(1),ae=Hn(),be=o.useMemo(()=>{const R=c.trim();return R?(r==null?void 0:r.find(Ae=>Ae.id===R))??null:null},[r,c]),{details:ie}=uf({initiativeId:be?be.id:null,enabled:e&&!!be}),P=o.useMemo(()=>pf(ie),[ie]),xe=o.useMemo(()=>ff(ie,u||null),[ie,u]),ne=((V=i.data)==null?void 0:V.agents)??[],K=o.useMemo(()=>{const R=a.trim();return R?ne.find(Ae=>Ae.id===R)??null:null},[ne,a]);o.useEffect(()=>{var Ae,Se;if(!e)return;const R=((Ae=ne.find(Ee=>Ee.isDefault))==null?void 0:Ae.id)??((Se=ne[0])==null?void 0:Se.id)??"";!a&&R&&l(R)},[ne,e,a]),o.useEffect(()=>{if(!e||c.trim())return;const R=r??[],Ae=R.length===1?R[0]:null;Ae&&d(Ae.id)},[r,e,c]),o.useEffect(()=>{if(!e)return;const R=(K==null?void 0:K.model)??"",Ae=R.includes("openrouter")?"openrouter":R.includes("anthropic")?"anthropic":R.includes("openai")?"openai":"auto";w(Ae)},[e,K==null?void 0:K.model,a]),o.useEffect(()=>{e&&(D(null),_(null),A("starter"),L(1))},[e]),o.useEffect(()=>{p(""),y("")},[c]),o.useEffect(()=>{y("")},[u]),o.useEffect(()=>{e&&(N.trim().length>0||be&&k(`Kick off: ${be.name}`))},[N,e,be]);const G=!!a.trim()&&!!c.trim(),le=M===1?!!a.trim():M===2?!!c.trim():G,Le=async()=>{var ye;const R=(b==null?void 0:b.checkout)??"/orgx/api/billing/checkout",Ae=H&&H.trim().length>0?H.trim():"starter",Ee=await(await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:Ae,billingCycle:"monthly"})})).json().catch(()=>null),$e=((ye=Ee==null?void 0:Ee.data)==null?void 0:ye.url)??(Ee==null?void 0:Ee.url)??null;if(!$e)throw new Error((Ee==null?void 0:Ee.error)??"Checkout unavailable");window.open($e,"_blank","noopener,noreferrer")},Me=async()=>{var $e;const R=(b==null?void 0:b.portal)??"/orgx/api/billing/portal",Se=await(await fetch(R,{method:"POST"})).json().catch(()=>null),Ee=(($e=Se==null?void 0:Se.data)==null?void 0:$e.url)??(Se==null?void 0:Se.url)??null;if(!Ee)throw new Error((Se==null?void 0:Se.error)??"Billing portal unavailable");window.open(Ee,"_blank","noopener,noreferrer")},me=async()=>{if(!(!G||O)){if(ae){t(),s==null||s();return}D(null),_(null),se(!0);try{const R={agentId:a.trim(),message:N.trim()?N.trim():void 0,initiativeId:c.trim(),initiativeTitle:(be==null?void 0:be.name)??null,workstreamId:u.trim()?u.trim():null,taskId:h.trim()?h.trim():null,provider:g!=="auto"?g:null},Ae=new URLSearchParams;Ae.set("agentId",R.agentId),Ae.set("initiativeId",R.initiativeId),R.initiativeTitle&&Ae.set("initiativeTitle",R.initiativeTitle),R.workstreamId&&Ae.set("workstreamId",R.workstreamId),R.taskId&&Ae.set("taskId",R.taskId),R.message&&Ae.set("message",R.message),R.provider&&Ae.set("provider",R.provider);const Se=await fetch(`/orgx/api/agents/launch?${Ae.toString()}`,{method:"POST"}),Ee=await Se.json().catch(()=>null);if(!Se.ok||!(Ee!=null&&Ee.ok))throw(Ee==null?void 0:Ee.code)==="upgrade_required"&&(_(Ee.actions??null),A(Ee.requiredPlan??"starter")),new Error((Ee==null?void 0:Ee.error)??`Launch failed (${Se.status})`);t(),s==null||s()}catch(R){D(R instanceof Error?R.message:"Launch failed")}finally{se(!1)}}},Ne=!!((Y=K==null?void 0:K.run)!=null&&Y.runId)&&!!((Ie=K==null?void 0:K.run)!=null&&Ie.pid),E=async()=>{var R;if(!(!((R=K==null?void 0:K.run)!=null&&R.runId)||!Ne||O)&&!ae){D(null),se(!0);try{const Ae=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(K.run.runId)}`,{method:"POST"}),Se=await Ae.json().catch(()=>null);if(!Ae.ok||!(Se!=null&&Se.ok))throw new Error((Se==null?void 0:Se.error)??`Stop failed (${Ae.status})`);await i.refetch()}catch(Ae){D(Ae instanceof Error?Ae.message:"Stop failed")}finally{se(!1)}}},W=async()=>{var R;if(!(!((R=K==null?void 0:K.run)!=null&&R.runId)||O)){if(ae){t(),s==null||s();return}D(null),se(!0);try{const Ae=new URLSearchParams;Ae.set("runId",K.run.runId),N.trim()&&Ae.set("message",N.trim()),g&&g!=="auto"&&Ae.set("provider",g);const Se=await fetch(`/orgx/api/agents/restart?${Ae.toString()}`,{method:"POST"}),Ee=await Se.json().catch(()=>null);if(!Se.ok||!(Ee!=null&&Ee.ok))throw new Error((Ee==null?void 0:Ee.error)??`Restart failed (${Se.status})`);t(),s==null||s()}catch(Ae){D(Ae instanceof Error?Ae.message:"Restart failed")}finally{se(!1)}}};return e?n.jsx(oa,{open:e,onClose:t,maxWidth:"max-w-2xl",children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"border-b border-subtle px-5 py-4 sm:px-6",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:"Launch OpenClaw Agent"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:"Starts a background agent turn and scopes the resulting sessions/activity to the selected OrgX initiative."}),n.jsx("div",{className:"mt-3 inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.03] p-1 text-micro uppercase tracking-[0.12em] text-secondary",children:[[1,"Agent"],[2,"Scope"],[3,"Message"]].map(([R,Ae])=>n.jsxs("button",{type:"button",onClick:()=>L(R),className:fe("rounded-full px-3 py-1 transition-colors",M===R?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[R,". ",Ae]},R))})]}),n.jsx("button",{type:"button",onClick:t,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-1.5 text-body text-secondary hover:bg-white/[0.08] hover:text-white",children:"Close"})]})}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4 sm:px-6",children:[i.isLoading&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading agent catalog…"}),i.error&&n.jsx("div",{className:"rounded-xl border border-rose-300/20 bg-rose-400/10 p-4 text-body text-rose-100",children:i.error.message}),n.jsx(bt,{mode:"wait",children:n.jsxs(ue.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.22,ease:[.16,1,.3,1]},className:"mt-3 space-y-4",children:[M===1&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Agent"}),n.jsx("select",{value:a,onChange:R=>l(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",children:ne.map(R=>{const Ae=Di(R.status);return n.jsxs("option",{value:R.id,children:[R.name," (",R.id,") · ",Ae.label]},R.id)})})]}),K&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-primary",children:K.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${Di(K.status).color}55`,color:Di(K.status).color,backgroundColor:Di(K.status).bg},children:Di(K.status).label})]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Model:"})," ",K.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",K.workspace??"unknown"]}),((De=K.context)==null?void 0:De.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",K.context.initiativeTitle??K.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:g,onChange:R=>w(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",children:[n.jsx("option",{value:"auto",children:"Auto (keep agent model)"}),n.jsx("option",{value:"anthropic",children:"Anthropic"}),n.jsx("option",{value:"openrouter",children:"OpenRouter"}),n.jsx("option",{value:"openai",children:"OpenAI"})]}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Selecting a provider updates the agent's default model before launch."})]}),K.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",K.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",K.run.status,")"]})]}),K.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:E,disabled:!Ne||O,className:"rounded-lg border border-rose-300/25 bg-rose-400/10 px-3 py-2 text-caption font-semibold text-rose-100 transition-colors hover:bg-rose-400/20 disabled:opacity-45",children:"Stop Run"}),n.jsx("button",{type:"button",onClick:W,disabled:O,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-2 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Restart"})]})]})]})]}),M===2&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Initiative Scope"}),n.jsxs("select",{value:c,onChange:R=>d(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",children:[n.jsx("option",{value:"",children:"Select an initiative…"}),(r??[]).map(R=>n.jsx("option",{value:R.id,children:R.name},R.id))]})]}),n.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream (optional)"}),n.jsxs("select",{value:u,onChange:R=>p(R.target.value),disabled:!be,className:fe("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",!be&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),P.map(R=>n.jsx("option",{value:R.id,children:R.name},R.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:h,onChange:R=>y(R.target.value),disabled:!be,className:fe("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",!be&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),xe.slice(0,80).map(R=>n.jsx("option",{value:R.id,children:R.title},R.id))]}),xe.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),M===3&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Kickoff Message"}),n.jsx("textarea",{value:N,onChange:R=>k(R.target.value),rows:4,className:"mt-1 w-full resize-none rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-lime/30",placeholder:"Optional. If left blank, a default kickoff message is used."})]}),n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Review"}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Agent"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((K==null?void 0:K.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((be==null?void 0:be.name)??c.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((he=P.find(R=>R.id===u))==null?void 0:he.name)??u:"Any"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:h.trim()?((je=xe.find(R=>R.id===h))==null?void 0:je.title)??h:"Any"})]})]})]})]})]},M)}),T&&n.jsx("div",{className:"mt-3 rounded-xl border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-body text-rose-100",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{children:T}),b&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Le().catch(R=>D(R instanceof Error?R.message:"Checkout failed")),className:"rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15",children:"Upgrade"}),n.jsx("button",{type:"button",onClick:()=>void Me().catch(R=>D(R instanceof Error?R.message:"Portal failed")),className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08]",children:"Billing portal"}),b.pricing&&n.jsx("a",{href:b.pricing,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary underline decoration-white/20 hover:text-primary",children:"View pricing"})]})]})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-subtle px-5 py-3.5 sm:px-6",children:[n.jsx("div",{className:"text-caption text-secondary",children:M===1?"Pick an agent to configure.":M===2?"Select an initiative scope (required).":G?"Launch will update sessions/activity under the selected initiative.":"Select an agent and initiative to launch."}),n.jsxs("div",{className:"flex items-center gap-2",children:[M>1&&n.jsx("button",{type:"button",onClick:()=>L(R=>R>1?R-1:R),disabled:O,className:"rounded-xl border border-strong bg-white/[0.03] px-4 py-2 text-body font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Back"}),M<3?n.jsx("button",{type:"button",onClick:()=>L(R=>R<3?R+1:R),disabled:!le||O,className:fe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",le&&!O?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:le&&!O?{backgroundColor:q.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:me,disabled:!G||O,className:fe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",G&&!O?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:G&&!O?{backgroundColor:q.lime}:void 0,children:O?"Launching…":"Launch"})]})]})]})}):null}function gf({breadcrumbs:e,typeBadge:t,onClose:s,footer:i,children:r}){return n.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-body text-secondary",children:[e.map((a,l)=>n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[l>0&&n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"flex-shrink-0 text-faint",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),a.onClick?n.jsx("button",{type:"button",onClick:a.onClick,className:`truncate transition-colors hover:text-primary ${l===e.length-1?"text-primary font-medium":""}`,children:a.label}):n.jsx("span",{className:`truncate ${l===e.length-1?"text-primary font-medium":""}`,children:a.label})]},l)),t&&n.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.06em] text-secondary",children:[t.icon&&n.jsx(en,{type:t.icon,size:11,className:"opacity-90"}),t.label]})]}),n.jsx(ue.button,{type:"button",onClick:s,"aria-label":"Close detail",whileHover:{scale:1.06},whileTap:{scale:.92},transition:{duration:.12},className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:r}),i&&n.jsx("div",{className:"flex-shrink-0 border-t border-subtle px-5 py-3 sm:px-6",children:i})]})}const Da=10,xf=20;function yf(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:q.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:q.iris,bg:"rgba(124,124,255,0.10)"}}function bf(e){return e?e.includes("error")||e.includes("fail")?q.red:e.includes("decision")||e.includes("block")?q.amber:e.includes("complete")||e.includes("success")?q.teal:e.includes("start")||e.includes("launch")?q.lime:q.iris:q.iris}const vf={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},kr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function wf(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function kf({open:e,onClose:t,agentName:s,catalogAgent:i,sessions:r,activity:a,onSelectSession:l,onRefresh:c}){var L,ae,be,ie,P,xe;const[d,u]=o.useState(!1),[p,h]=o.useState(!1),[y,g]=o.useState(null),w=Xi(s),N=yf((i==null?void 0:i.status)??null),k=uo(s),T=o.useMemo(()=>{let ne=0,K=0,G=0,le=0;for(const Le of r)Le.status==="running"||Le.status==="queued"||Le.status==="pending"?ne++:Le.status==="blocked"?K++:Le.status==="failed"||Le.status==="cancelled"?G++:(Le.status==="completed"||Le.status==="archived")&&le++;return{running:ne,blocked:K,failed:G,completed:le}},[r]),D=o.useMemo(()=>[...r].sort((ne,K)=>Date.parse(K.updatedAt??K.lastEventAt??K.startedAt??"")-Date.parse(ne.updatedAt??ne.lastEventAt??ne.startedAt??"")),[r]),b=d?D:D.slice(0,Da),_=D.length>Da,H=o.useMemo(()=>[...a].sort((ne,K)=>Date.parse(K.timestamp)-Date.parse(ne.timestamp)).slice(0,xf),[a]),A=!!((L=i==null?void 0:i.run)!=null&&L.runId)&&!!((ae=i==null?void 0:i.run)!=null&&ae.pid),O=async()=>{var ne;if(!(!((ne=i==null?void 0:i.run)!=null&&ne.runId)||!A||p)){g(null),h(!0);try{const K=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(i.run.runId)}`,{method:"POST"}),G=await K.json().catch(()=>null);if(!K.ok||!(G!=null&&G.ok))throw new Error((G==null?void 0:G.error)??`Stop failed (${K.status})`);c==null||c()}catch(K){g(K instanceof Error?K.message:"Stop failed")}finally{h(!1)}}},se=async()=>{var ne;if(!(!((ne=i==null?void 0:i.run)!=null&&ne.runId)||p)){g(null),h(!0);try{const K=new URLSearchParams;K.set("runId",i.run.runId);const G=await fetch(`/orgx/api/agents/restart?${K.toString()}`,{method:"POST"}),le=await G.json().catch(()=>null);if(!G.ok||!(le!=null&&le.ok))throw new Error((le==null?void 0:le.error)??`Restart failed (${G.status})`);c==null||c()}catch(K){g(K instanceof Error?K.message:"Restart failed")}finally{h(!1)}}};if(!e)return null;const M=i!=null&&i.run?n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"text-caption text-secondary",children:["Run ",i.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-1",children:["(",i.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:O,disabled:!A||p,className:"rounded-md px-2.5 py-1.5 text-caption font-medium text-red-400/70 hover:bg-red-500/[0.08] hover:text-red-300 disabled:opacity-40 transition-colors",children:p?"Stopping…":"Stop"}),n.jsx("button",{type:"button",onClick:se,disabled:p,className:"h-8 rounded-lg border border-lime/25 bg-lime/10 px-4 text-caption font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-40",children:p?"Restarting…":"Restart"})]})]}):void 0;return n.jsxs(oa,{open:e,onClose:t,maxWidth:"max-w-3xl",children:[n.jsx("div",{className:"h-[2px] rounded-t-xl",style:{background:`linear-gradient(90deg, ${k}, transparent)`}}),n.jsx(gf,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:M,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(ue.div,{className:"flex items-start gap-5",variants:vf,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(Rc,{running:T.running,blocked:T.blocked+T.failed,paused:0,size:72,children:n.jsx(Gt,{name:s,size:"lg",hint:s})}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-display font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"status-pill",style:{color:N.color,backgroundColor:N.bg,borderColor:`${N.color}30`},children:N.label})]}),w&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:w})]})]}),n.jsx(ue.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:kr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:T.running,color:q.lime},{label:"Blocked",value:T.blocked,color:q.red},{label:"Failed",value:T.failed,color:q.amber},{label:"Completed",value:T.completed,color:q.teal}].map(ne=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:ne.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:ne.value>0?ne.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:ne.value})]},ne.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(ue.div,{variants:kr,initial:"hidden",animate:"visible",custom:2,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Sessions"}),r.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No sessions recorded."}):n.jsxs("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-6",children:[b.map(ne=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[29px] top-1.5 h-2 w-2 rounded-full border border-black ring-4 ring-black",style:{backgroundColor:Ks(ne.status)}}),n.jsxs("button",{onClick:()=>{l(ne.id),t()},className:"w-full text-left focus:outline-none group-hover:bg-white/[0.02] -mx-3 px-3 py-2 rounded-lg transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("p",{className:"truncate text-[14px] font-medium text-white transition-colors group-hover:text-lime",children:ne.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:Rt(ne.updatedAt??ne.lastEventAt??ne.startedAt??Date.now())})]}),n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[12px] text-secondary",children:[n.jsx("span",{className:"capitalize",children:ne.status}),ne.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(ne.progress),"%"]})]})]})]})]},ne.id)),_&&n.jsx("button",{type:"button",onClick:()=>u(ne=>!ne),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${D.length-Da} older sessions`})]})]}),n.jsxs(ue.div,{variants:kr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),H.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:H.map((ne,K)=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[27px] top-1.5 h-1.5 w-1.5 rounded-full ring-4 ring-black",style:{backgroundColor:bf(ne.type)}}),n.jsxs("div",{className:"flex items-start justify-between gap-4 py-0.5",children:[n.jsx("p",{className:"text-[13px] leading-relaxed text-secondary group-hover:text-white transition-colors line-clamp-2",children:ne.title??ne.summary??ne.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:Rt(ne.timestamp)})]})]},ne.id??K))})]})]}),n.jsx(wf,{}),i&&n.jsxs(ue.div,{variants:kr,initial:"hidden",animate:"visible",custom:4,children:[n.jsx("p",{className:"section-kicker mb-4",children:"Configuration"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(be=i.model)!=null&&be.includes("openrouter")?"OpenRouter":(ie=i.model)!=null&&ie.includes("anthropic")?"Anthropic":(P=i.model)!=null&&P.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:fe("text-[14px] truncate",i.model?"text-primary":"text-muted"),children:i.model??"Not configured"})]}),i.workspace&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:i.workspace})]}),((xe=i.context)==null?void 0:xe.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:i.context.initiativeTitle})]})]})]}),y&&n.jsx("p",{className:"rounded-md border border-red-400/30 bg-red-500/10 px-3 py-2 text-caption text-red-200",children:y})]})})]})}const Ir=120,xl=10,If=24,yl=520,Nf=58,jf=56,Af=20,_f=8,Sf=10,Cf=[{id:"orchestrator",name:"Orchestrator",role:"Coordinates cross-team execution"},{id:"engineering",name:"Engineering",role:"Builds and ships technical work"},{id:"product",name:"Product",role:"Defines features and requirements"},{id:"marketing",name:"Marketing",role:"Drives campaigns and content"},{id:"design",name:"Design",role:"Creates interfaces and experiences"},{id:"operations",name:"Operations",role:"Manages reliability and processes"}],Tf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,to=[{id:"eli",name:"Eli",role:"Engineering",aliases:[/\beli\b/i,/\borgx[\s_-]*engineering\b/i,/^\s*engineering\s*$/i]},{id:"dana",name:"Dana",role:"Product Design",aliases:[/\bdana\b/i,/\borgx[\s_-]*design\b/i,/\borgx[\s_-]*product\b/i,/\bproduct[\s_-]*design\b/i]},{id:"mark",name:"Mark",role:"Marketing",aliases:[/\bmark\b/i,/\borgx[\s_-]*marketing\b/i,/^\s*marketing\s*$/i]},{id:"sage",name:"Sage",role:"Sales",aliases:[/\bsage\b/i,/\borgx[\s_-]*sales\b/i,/^\s*sales\s*$/i]},{id:"orion",name:"Orion",role:"Operations",aliases:[/\borion\b/i,/\borgx[\s_-]*operations\b/i,/^\s*operations\s*$/i]},{id:"xandy",name:"Xandy",role:"Orchestrator",aliases:[/\bxandy\b/i,/\borgx[\s_-]*orchestrator\b/i,/^\s*orchestrator\s*$/i]},{id:"pace",name:"Pace",role:"Engineering",aliases:[/\bpace\b/i,/\borgx[\s_-]*pace\b/i]}];function xt(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function Sn(e,t){const s=xt(e),i=xt(t);if(!s&&!i)return null;const r=[s,i].filter(Boolean).join(" ");if(!r)return null;for(const a of to)if(a.aliases.some(l=>l.test(r)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Mf(e){const t=Sn(e.agentId,e.agentName);if(t)return t;const s=[e.groupLabel,e.title,e.runtimeLabel,e.lastEventSummary];for(const i of s){const r=Sn(null,i);if(r)return r}return null}function Ef(e){const t=xt(e.runtimeClient);if(t==="codex")return"codex";if(t==="claude-code")return"claude-code";if(t==="openclaw")return"openclaw";if(t==="api")return"api";const s=[e.title,e.lastEventSummary,e.runtimeLabel,e.runtimeProvider,e.groupLabel].filter(i=>typeof i=="string"&&i.trim().length>0).join(" ").toLowerCase();return s.includes("claude-code")||s.includes("anthropic")||s.includes("claude")?"claude-code":s.includes("openclaw")?"openclaw":s.includes("codex")||s.includes("openai")?"codex":s.includes("orgx api")||s.includes("source_client=api")?"api":null}function Lc(e){const t=Mf(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=xt(e.agentId),i=xt(e.agentName);if(s||i)return{agentId:e.agentId??null,agentName:e.agentName??null};const r=Ef(e);return r==="codex"?{agentId:"runtime:codex",agentName:"Codex"}:r==="claude-code"?{agentId:"runtime:claude-code",agentName:"Claude Code"}:r==="openclaw"?{agentId:"runtime:openclaw",agentName:"OpenClaw"}:r==="api"?{agentId:"runtime:api",agentName:"OrgX API"}:{agentId:null,agentName:null}}function Rf(e){const t=Lc(e),s=xt(t.agentId);if(s)return`id:${s}`;const i=xt(t.agentName);return i?`name:${i}`:"unassigned"}function Lf(e){const t=e.trim();return t?Tf.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function ea(e){const t=(e??"").trim();return t?ki(t):!1}function Df(e){var t,s;return!!(ea((t=e.context)==null?void 0:t.initiativeId)||ea(((s=e.run)==null?void 0:s.initiativeId)??null))}function Nr(e){if(Sn(e.agentId,e.agentName))return!0;const s=xt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function _n(e){const t=Lt(e.status??"")||"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=Lt(e.phase??"");if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const i=Lt(e.state??"");return i==="error"?"failed":i==="stopped"?"paused":i==="stale"?"queued":mo(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function no(e){const t=Lt(e??"");return!!t&&(mo(t)||sf(t)||nf(t))}function bl(e){const t=Lt(e??"");return!!t&&mo(t)}function mi(e){return e?!!(no(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function $f(e){return e?e.state==="active":!1}function Pf(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Bn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function jr(e,t){return Bn(t.updatedAt??t.lastEventAt??t.startedAt)-Bn(e.updatedAt??e.lastEventAt??e.startedAt)}function Of({status:e,nodes:t,onSelectSession:s,selectedSessionId:i}){const[r,a]=o.useState(!1),l=Ks(e),c=e==="blocked"?"blocked":e==="failed"?"failed":"paused";return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>a(d=>!d),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:l}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",c," sessions"]}),n.jsx(ue.span,{animate:{rotate:r?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(bt,{children:r&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden pl-4",children:t.map((d,u)=>{const p=i===d.id,h=Cs(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(ue.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(u*.02,.1)},className:fe("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",p?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(yi,{provider:h.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:Rt(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const qf=o.memo(function({sessions:t,activity:s,selectedSessionId:i,onSelectSession:r,timeFilterId:a,onAgentFilter:l,agentFilter:c,onReconnect:d,onLaunched:u,connectionStatus:p,runtimeInstances:h=[],showSyntheticEntities:y=!1,autopilotState:g=null}){var te;const[w,N]=o.useState(new Set),[k,T]=o.useState(!1),[D,b]=o.useState(!1),[_,H]=o.useState(0),[A,O]=o.useState(null),[se,M]=o.useState(!1),L=ho({enabled:!0}),ae=((te=L.data)==null?void 0:te.agents)??[],be=o.useMemo(()=>Yi(a),[a]),ie=o.useMemo(()=>be===null?s:s.filter(B=>Bn(B.timestamp)>=be),[s,be]);o.useMemo(()=>{var pe,Pe,We;const B=new Map,oe=[...ie].sort((rt,ge)=>Bn(ge.timestamp)-Bn(rt.timestamp));for(const rt of oe){const ge=rt.runId;if(!ge||B.has(ge))continue;const Ve=((pe=rt.summary)==null?void 0:pe.trim())??((Pe=rt.description)==null?void 0:Pe.trim())??((We=rt.title)==null?void 0:We.trim())??"";Ve.length>0&&B.set(ge,Ve)}return B},[ie]);const{agents:P,hiddenGroupCount:xe,filteredOutGroupsByDate:ne,filteredOutSessionsByDate:K,visibleSessionCount:G,archivedGroups:le,sessionCountInScope:Le}=o.useMemo(()=>{var rn;const B=y?t.nodes:t.nodes.filter(Z=>!ea(Z.initiativeId)),oe=y?ae:ae.filter(Z=>!Df(Z)),pe=y?h:h.filter(Z=>!ea(Z.initiativeId)),Pe=new Map,We=new Map,rt=[...pe].sort((Z,ve)=>Bn(ve.lastEventAt??ve.lastHeartbeatAt)-Bn(Z.lastEventAt??Z.lastHeartbeatAt));for(const Z of rt){Z.runId&&!Pe.has(Z.runId)&&Pe.set(Z.runId,Z);const ve=Sn(Z.agentId,Z.agentName??Z.displayName),Oe=xt((ve==null?void 0:ve.agentId)??Z.agentId);if(Oe){const Ge=We.get(Oe)??[];Ge.push(Z),We.set(Oe,Ge)}}const ge=new Map;for(const Z of B){const ve=Lc(Z),Oe=Rf(Z),Ge=xt(ve.agentId),Re=xt(ve.agentName);let He=ge.get(Oe)??null;if(!He&&Ge&&Re){const Ue=`name:${Re}`,ft=ge.get(Ue);ft&&(ge.delete(Ue),ft.groupKey=Oe,ge.set(Oe,ft),He=ft)}if(!He&&Re){const Ue=Array.from(ge.values()).find(ft=>xt(ft.agentName)===Re);Ue&&(He=Ue)}He?(He.nodes.push(Z),!He.agentId&&ve.agentId&&(He.agentId=ve.agentId),(He.agentName==="OrgX"||!He.agentName)&&ve.agentName&&(He.agentName=ve.agentName)):ge.set(Oe,{groupKey:Oe,agentId:ve.agentId,agentName:ve.agentName??ve.agentId??"OrgX",nodes:[Z],latest:Z,runtime:null,runtimeActiveCount:0})}for(const Z of oe){const ve=Sn(Z.id,Z.name),Oe=(ve==null?void 0:ve.agentId)??Z.id,Ge=(ve==null?void 0:ve.agentName)??Z.name,Re=xt(Oe),He=xt(Ge),Ue=Re?`id:${Re}`:null,ft=He?`name:${He}`:null;let Ht=null;if(Ue&&ge.has(Ue))Ht=Ue;else if(ft&&ge.has(ft))Ht=ft;else{const gt=Array.from(ge.entries()).find(([,vt])=>Re&&xt(vt.agentId)===Re||He&&xt(vt.agentName)===He);Ht=(gt==null?void 0:gt[0])??null}if(Ht){const gt=ge.get(Ht);gt.catalogAgent=Z,!gt.agentId&&Oe&&(gt.agentId=Oe),(gt.agentName==="OrgX"||!gt.agentName)&&Ge&&(gt.agentName=Ge),Ue&>.groupKey!==Ue&&!ge.has(Ue)&&(ge.delete(gt.groupKey),gt.groupKey=Ue,ge.set(Ue,gt))}else{const gt=Ue??ft??`catalog:${Ge.toLowerCase()}`;ge.set(gt,{groupKey:gt,agentId:Oe,agentName:Ge,nodes:[],latest:null,catalogAgent:Z,runtime:null,runtimeActiveCount:0})}}for(const Z of to){const ve=`orgx:${Z.id}`,Oe=`id:${ve}`;let Ge=ge.get(Oe)??null;if(!Ge){const Re=Array.from(ge.entries()).find(([,He])=>{const Ue=Sn(He.agentId,He.agentName);return xt(Ue==null?void 0:Ue.agentId)===xt(ve)});Re&&(ge.delete(Re[0]),Ge=Re[1],Ge.groupKey=Oe,ge.set(Oe,Ge))}if(Ge||(Ge={groupKey:Oe,agentId:ve,agentName:Z.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},ge.set(Oe,Ge)),Ge.agentId=ve,Ge.agentName=Z.name,!Ge.catalogAgent){const Re=oe.find(He=>{const Ue=Sn(He.id,He.name);return xt(Ue==null?void 0:Ue.agentId)===xt(ve)});Re&&(Ge.catalogAgent=Re)}}const Ve=new Map(to.map((Z,ve)=>[xt(`orgx:${Z.id}`),ve]));for(const Z of ge.values()){Z.nodes.length>0&&(Z.nodes.sort(jr),Z.latest=Z.nodes[0]);const ve=[],Oe=new Set;if((rn=Z.latest)!=null&&rn.runId){const Re=Pe.get(Z.latest.runId);Re&&!Oe.has(Re.id)&&(ve.push(Re),Oe.add(Re.id))}for(const Re of Z.nodes){if(!Re.runId)continue;const He=Pe.get(Re.runId);He&&!Oe.has(He.id)&&(ve.push(He),Oe.add(He.id))}const Ge=xt(Z.agentId);if(Ge)for(const Re of We.get(Ge)??[])Oe.has(Re.id)||(ve.push(Re),Oe.add(Re.id));ve.sort((Re,He)=>Bn(He.lastEventAt??He.lastHeartbeatAt)-Bn(Re.lastEventAt??Re.lastHeartbeatAt)),Z.runtime=ve[0]??null,Z.runtimeActiveCount=ve.filter(Re=>$f(Re)).length}const ce=Array.from(ge.values()).sort((Z,ve)=>{const Oe=Nr(Z),Ge=Nr(ve);if(Oe!==Ge)return Oe?-1:1;if(Oe&&Ge){const Re=Z.nodes.length>0||(Z.runtimeActiveCount??0)>0,He=ve.nodes.length>0||(ve.runtimeActiveCount??0)>0;if(Re!==He)return Re?-1:1;if(Re&&He){if(Z.latest&&ve.latest)return jr(Z.latest,ve.latest);if(Z.latest&&!ve.latest)return-1;if(!Z.latest&&ve.latest)return 1}const Ue=Sn(Z.agentId,Z.agentName),ft=Sn(ve.agentId,ve.agentName),Ht=Ve.get(xt((Ue==null?void 0:Ue.agentId)??Z.agentId))??999,gt=Ve.get(xt((ft==null?void 0:ft.agentId)??ve.agentId))??999;if(Ht!==gt)return Ht-gt}return Z.latest&&ve.latest?jr(Z.latest,ve.latest):Z.latest&&!ve.latest?-1:!Z.latest&&ve.latest?1:Z.agentName.localeCompare(ve.agentName)}),X=mc(a),Te=X.id==="live",Ze=X.minutes===null||Te?null:Date.now()-X.minutes*6e4,at=[],pt=[];let ct=0,ht=0;for(const Z of ce){const ve=(Z.runtimeActiveCount??0)>0,Oe=Nr(Z);if(Z.nodes.length===0){const Ue=mi(Z.catalogAgent);(Oe||Te&&(Ue||ve))&&at.push(Z);continue}if(Te){const Ue=Z.nodes.filter(gt=>no(_n(gt))),ft=Z.nodes.filter(gt=>!no(_n(gt))),Ht=mi(Z.catalogAgent);if(Ue.length===0){Oe||Ht||ve?at.push({...Z,nodes:[],latest:null}):(ct+=1,ht+=Z.nodes.length,pt.push(Z));continue}ht+=ft.length,ft.length>0&&pt.push({...Z,nodes:ft,latest:ft[0]??null}),at.push({...Z,nodes:Ue,latest:Ue[0]??null});continue}if(Ze===null){at.push(Z);continue}const Ge=Z.nodes.filter(Ue=>bl(_n(Ue))?!0:Bn(Ue.updatedAt??Ue.lastEventAt??Ue.startedAt)>=Ze),Re=mi(Z.catalogAgent);if(Ge.length===0){Oe||Re||ve?at.push({...Z,nodes:[],latest:null}):(ct+=1,ht+=Z.nodes.length,pt.push(Z));continue}const He=Z.nodes.filter(Ue=>bl(_n(Ue))?!1:Bn(Ue.updatedAt??Ue.lastEventAt??Ue.startedAt)<Ze);ht+=He.length,He.length>0&&pt.push({...Z,nodes:He,latest:He[0]}),at.push({...Z,nodes:Ge,latest:Ge[0]})}return{agents:at.slice(0,Ir),hiddenGroupCount:Math.max(0,at.length-Ir),filteredOutGroupsByDate:ct,filteredOutSessionsByDate:ht,visibleSessionCount:at.slice(0,Ir).reduce((Z,ve)=>Z+ve.nodes.length,0),archivedGroups:pt,sessionCountInScope:B.length}},[a,t.nodes,ae,h,y]);o.useEffect(()=>{b(!1),H(0)},[a]);const Me=o.useMemo(()=>le.reduce((B,oe)=>B+oe.nodes.length,0),[le]),me=o.useMemo(()=>P.filter(B=>B.nodes.length>0).map(B=>B.groupKey),[P]),{activeAgents:Ne,idleOrgxAgents:E,activeAgentCount:W}=o.useMemo(()=>{const B=[],oe=[];for(const pe of P)pe.nodes.length>0||(pe.runtimeActiveCount??0)>0||mi(pe.catalogAgent)?B.push(pe):Nr(pe)?oe.push(pe):B.push(pe);return{activeAgents:B,idleOrgxAgents:oe,activeAgentCount:B.filter(pe=>pe.nodes.length>0||(pe.runtimeActiveCount??0)>0||mi(pe.catalogAgent)).length}},[P]),V=o.useMemo(()=>{if(me.length===0)return{allCollapsed:!1,allExpanded:!0};let B=0;for(const oe of me)w.has(oe)&&(B+=1);return{allCollapsed:B===me.length,allExpanded:B===0}},[w,me]),Y=o.useMemo(()=>{const B=[];for(const oe of le)for(const pe of oe.nodes)B.push({node:pe,agentName:oe.agentName});return B.sort((oe,pe)=>jr(oe.node,pe.node)),B.slice(0,(_+1)*Sf)},[le,_]),Ie=B=>{N(oe=>{const pe=new Set(oe);return pe.has(B)?pe.delete(B):pe.add(B),pe})},De=()=>{N(()=>V.allCollapsed?new Set:new Set(me))},he=o.useMemo(()=>A?P.find(B=>B.groupKey===A)??null:null,[P,A]),je=o.useMemo(()=>(he==null?void 0:he.nodes)??[],[he]),R=o.useMemo(()=>{if(!he)return[];const B=xt(he.agentName),oe=xt(he.agentId),pe=Sn(he.agentId,he.agentName);return ie.filter(Pe=>{const We=xt(Pe.agentName),rt=xt(Pe.agentId),ge=Sn(Pe.agentId,Pe.agentName);return B!==null&&We===B||oe!==null&&rt===oe||pe!==null&&ge!==null&&xt(pe.agentId)===xt(ge.agentId)})},[ie,he]),Ae=Le===0,Se=ae.length>0,Ee=o.useRef(null),[$e,ye]=o.useState(0),[mt,Ce]=o.useState(0),_e=o.useCallback(B=>{const oe=B.currentTarget.scrollTop;ye(pe=>Math.abs(pe-oe)<1?pe:oe)},[]);o.useEffect(()=>{const B=Ee.current;if(!B)return;const oe=()=>{const pe=B.clientHeight,Pe=B.scrollTop;Ce(We=>We===pe?We:pe),ye(We=>Math.abs(We-Pe)<1?We:Pe)};if(oe(),typeof ResizeObserver<"u"){const pe=new ResizeObserver(()=>oe());return pe.observe(B),()=>pe.disconnect()}return window.addEventListener("resize",oe),()=>window.removeEventListener("resize",oe)},[Ne.length]);const{visibleAgentGroups:ee,topVirtualSpacerPx:dt,bottomVirtualSpacerPx:yt,virtualizationEnabled:Be}=o.useMemo(()=>{if(!(Ne.length>If&&mt>0))return{visibleAgentGroups:Ne,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const oe=Ne.map(ce=>{const Te=w.has(ce.groupKey)?0:Math.min(ce.nodes.length,xl);let Ze=Nf;return Te>0&&(Ze+=Af+Te*jf,ce.nodes.length>Te&&(Ze+=20)),Ze+_f}),pe=new Array(oe.length+1).fill(0);for(let ce=0;ce<oe.length;ce+=1)pe[ce+1]=pe[ce]+oe[ce];const Pe=pe[pe.length-1],We=Math.max(0,$e-yl),rt=$e+mt+yl;let ge=0;for(;ge<Ne.length&&pe[ge+1]<We;)ge+=1;let Ve=ge;for(;Ve<Ne.length&&pe[Ve]<rt;)Ve+=1;return Ve<=ge&&(Ve=Math.min(Ne.length,ge+1)),{visibleAgentGroups:Ne.slice(ge,Ve),topVirtualSpacerPx:pe[ge],bottomVirtualSpacerPx:Math.max(0,Pe-pe[Ve]),virtualizationEnabled:!0}},[Ne,w,$e,mt]);return n.jsxs(Ts,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(hf,{open:k,onClose:()=>T(!1),onLaunched:()=>{L.refetch(),u==null||u()}}),n.jsx(kf,{open:A!==null,onClose:()=>O(null),agentName:(he==null?void 0:he.agentName)??"",catalogAgent:(he==null?void 0:he.catalogAgent)??null,sessions:je,activity:R,onSelectSession:r,onRefresh:()=>L.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[W," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:De,disabled:me.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:V.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:V.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>T(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:Ee,onScroll:_e,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[P.length===0&&!Ae&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.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"})}),n.jsx("p",{className:"text-body text-secondary",children:"No sessions match the selected activity window."})]}),P.length===0&&Ae&&!d&&n.jsx(la,{icon:"agents",headline:"No active sessions yet",description:"Start a session to see agent conversations here."}),c&&l&&n.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-[#0AD4C4]/[0.08] px-3 py-1.5 text-caption text-[#0AD4C4]",children:[n.jsxs("span",{children:["Filtered: ",c]}),n.jsx("button",{type:"button",onClick:()=>l(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[Be&&dt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:dt}}),ee.map(B=>{var gt;const oe=B.groupKey,pe=w.has(oe),Pe=B.latest,We=Pe?_n(Pe):null,rt=(g==null?void 0:g.activeRunId)!=null&&(Pe==null?void 0:Pe.runId)!=null&&g.activeRunId===Pe.runId,ge=rt&&(g==null?void 0:g.state)==="running"?"running":We,Ve=rt&&(g==null?void 0:g.state)==="running"&&g.activeWorkstreamTitle?`Working on ${g.activeWorkstreamTitle}`:null,ce=B.nodes.length>0,X=B.nodes.length===1,Te=mi(B.catalogAgent),Ze=B.runtime??null,at=(B.runtimeActiveCount??0)>0,pt=!ce&&at&&Ze!==null,ct=ce||pt,ht=Pe?i===Pe.id:!1,rn=B.agentName||((gt=B.catalogAgent)==null?void 0:gt.name)||B.agentId||"OrgX",Z=Sn(B.agentId,rn),ve=(Z==null?void 0:Z.agentName)??Lf(rn),Oe=(Z==null?void 0:Z.role)??Xi(ve),Ge=Cs(B.agentId,ve,Ze==null?void 0:Ze.displayName,Pe==null?void 0:Pe.runtimeProvider,Pe==null?void 0:Pe.runtimeClient),Re=Z===null&&(Ge.id==="codex"||Ge.id==="openai"||Ge.id==="anthropic"||Ge.id==="openclaw"),He=Oe?`${rn} — ${Oe}`:rn,Ue=pe?[]:ce?B.nodes.slice(0,xl):[],ft=Math.max(0,ce?B.nodes.length-Ue.length:0),Ht=xt(c)===xt(ve)||xt(c)===xt(He);return n.jsxs(ue.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:fe("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",ht&&"border-white/20 bg-white/[0.05]",Ht&&"border-[#0AD4C4]/30",!ce&&!Te&&!at&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{X?r(B.nodes[0].id):pt?Ie(oe):!ce&&Te?O(oe):l?l(Ht?null:ve):Pe&&r(Pe.id)},className:"flex flex-1 items-start gap-2.5 rounded-lg px-1 py-0.5 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[Re?n.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-strong bg-white/[0.03]",children:n.jsx(yi,{provider:Ge.id,size:"sm",showRing:!1})}):n.jsx(Rc,{running:B.nodes.filter(vt=>{const Tt=_n(vt);return Tt==="running"||Tt==="handoff"||Tt==="review"}).length,blocked:B.nodes.filter(vt=>{const Tt=_n(vt);return Tt==="blocked"||Tt==="failed"}).length,paused:B.nodes.filter(vt=>{const Tt=_n(vt);return Tt==="paused"||Tt==="cancelled"}).length,size:36,children:n.jsx(Gt,{name:ve,size:"sm",hint:`${B.agentId??""} ${ve}`})}),Z&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})}),Pe&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ks(ge??Pe.status),borderColor:q.cardBg}}),!Pe&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Te?Ks("running"):"rgba(255,255,255,0.2)",borderColor:q.cardBg}})]}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"flex min-w-0 items-baseline",title:Oe?`${rn} — ${Oe}`:rn,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[ve,Oe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Oe]})]})}),Ve&&n.jsx("p",{className:"truncate text-micro text-teal-400",title:Ve,children:Ve}),n.jsx("div",{className:"flex items-center gap-1.5",children:ce?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const vt={};for(const Tt of B.nodes){const Ut=_n(Tt);vt[Ut]=(vt[Ut]??0)+1}return Object.entries(vt).map(([Tt,Ut])=>`${Ut} ${Tt}`).join(" · ")})(),children:(()=>{const vt={};for(const Ut of B.nodes){const nt=_n(Ut);vt[nt]=(vt[nt]??0)+1}const Tt=B.nodes.length;return Object.entries(vt).map(([Ut,nt])=>n.jsx("span",{style:{width:`${nt/Tt*100}%`,backgroundColor:Ks(Ut)}},Ut))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:B.nodes.length})]}):Te||at?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("span",{className:"h-1.5 w-full",style:{backgroundColor:Ks("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,B.runtimeActiveCount??0)})]}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]"}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-muted",style:{fontVariantNumeric:"tabular-nums"},children:"0"})]})})]})]}),n.jsx("button",{type:"button",onClick:()=>O(oe),"aria-label":`View ${ve} details`,className:"flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-white/[0.05] hover:text-primary",children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 16v-4"}),n.jsx("path",{d:"M12 8h.01"})]})}),n.jsx("button",{type:"button",onClick:()=>{ct&&Ie(oe)},disabled:!ct,"aria-label":ct?pe?"Expand sessions":"Collapse sessions":"No sessions to expand",className:fe("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",ct?"hover:bg-white/[0.05] hover:text-primary":"cursor-default opacity-35"),children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:fe("transition-transform",ct&&!pe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(bt,{initial:!1,children:ct&&!pe&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsxs("div",{className:"max-h-[500px] space-y-1.5 overflow-y-auto p-2",children:[(()=>{const vt=new Map,Tt=[];for(const et of Ue){const $t=_n(et);if($t==="blocked"||$t==="paused"||$t==="failed"){const St=`${$t}:${et.blockerReason??""}`,Mt=vt.get(St)??[];Mt.push(et),vt.set(St,Mt)}else Tt.push(et)}const Ut=[];for(const[et,$t]of vt)$t.length>3?Ut.push({status:et.split(":")[0],nodes:$t}):Tt.push(...$t);const nt=(et,$t)=>{const St=i===et.id,Mt=_n(et),Ct=Cs(et.agentName,et.title,et.lastEventSummary,et);return n.jsx(ue.button,{onClick:()=>r(et.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min($t*.015,.12)},className:fe("w-full rounded-lg px-2.5 py-2 text-left transition-colors",St?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(yi,{provider:Ct.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:et.title,children:et.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:Ct.accent},children:Ct.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Mt}),n.jsx("span",{title:Kr(et.updatedAt??et.lastEventAt??et.startedAt??Date.now()),children:Rt(et.updatedAt??et.lastEventAt??et.startedAt??Date.now())})]}),et.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(et.progress)}%`,background:`linear-gradient(90deg, ${q.lime}, ${q.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:Ks(Mt)},"aria-label":Mt,title:Mt})]})},et.id)};return n.jsxs(n.Fragment,{children:[Tt.map((et,$t)=>nt(et,$t)),Ut.map(et=>n.jsx(Of,{status:et.status,nodes:et.nodes,onSelectSession:r,selectedSessionId:i},`cg-${et.status}-${et.nodes.length}`))]})})(),ft>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",ft," older sessions hidden"]})]})})})]},oe)}),Be&&yt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:yt}})]}),E.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>M(B=>!B),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-caption text-secondary transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:fe("transition-transform",se?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[E.length," idle agent",E.length===1?"":"s"]})]}),n.jsx(bt,{initial:!1,children:se&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsx("div",{className:"space-y-1 p-2",children:E.map(B=>{const oe=Sn(B.agentId,B.agentName),pe=(oe==null?void 0:oe.agentName)??B.agentName,Pe=(oe==null?void 0:oe.role)??Xi(pe);return n.jsxs("button",{type:"button",onClick:()=>O(B.groupKey),className:"flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left opacity-55 transition-colors hover:bg-white/[0.05] hover:opacity-75",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[n.jsx(Gt,{name:pe,size:"sm",hint:`${B.agentId??""} ${pe}`}),oe&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})})]}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsxs("p",{className:"truncate text-caption font-medium text-secondary",children:[pe,Pe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Pe]})]})}),n.jsx("span",{className:"text-micro text-muted",children:"Idle"})]},B.groupKey)})})})})]}),xe>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Ir," most recent agent groups (",xe," older groups omitted)."]}),d&&p!=="connected"&&!Se&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsx("p",{className:"px-3 pt-2 pb-1.5 text-micro uppercase tracking-[0.1em] text-muted",children:"OrgX Agent Roster"}),n.jsx("div",{className:"space-y-1 px-2 pb-2",children:Cf.map(B=>n.jsxs("div",{className:"flex items-center gap-2.5 rounded-lg px-2 py-1.5 opacity-55",children:[n.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.08] bg-white/[0.03]",children:n.jsx("span",{className:"text-micro font-semibold text-secondary",children:B.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:B.name}),n.jsx("p",{className:"text-micro text-muted",children:B.role})]}),n.jsx("button",{onClick:d,className:"rounded-md border border-lime/25 bg-lime/10 px-2 py-0.5 text-micro font-semibold text-lime transition-colors hover:bg-lime/20",children:"Connect"})]},B.id))})]}),K>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{b(B=>!B),D&&H(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:fe("transition-transform",D?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[Me," archived session",Me===1?"":"s",ne>0?` across ${ne} agent${ne===1?"":"s"}`:""]})]}),n.jsx(bt,{initial:!1,children:D&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[Y.map(({node:B,agentName:oe})=>{const pe=_n(B),Pe=B.runtimeProvider?{id:Pf(B.runtimeProvider)}:Cs(B.agentName,B.title,B.lastEventSummary,B);return n.jsxs("button",{onClick:()=>r(B.id),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left opacity-60 transition-colors hover:bg-white/[0.05] hover:opacity-80",children:[n.jsx(yi,{provider:Pe.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"truncate text-caption font-medium text-primary",children:oe}),n.jsx("span",{className:"text-micro text-muted",title:Kr(B.updatedAt??B.lastEventAt??B.startedAt??Date.now()),children:Rt(B.updatedAt??B.lastEventAt??B.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:B.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:pe})]})]},B.id)}),Y.length<Me&&n.jsxs("button",{onClick:()=>H(B=>B+1),className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-1.5 text-micro text-secondary transition-colors hover:bg-white/[0.05]",children:["Load more (",Me-Y.length," remaining)"]})]})})})]})]})]})}),Ff=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Bf=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),Uf=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),zf=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Wf=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function pi(e){return e?Lt(e):""}function $a(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Hf(e){return e.some(t=>Ff.has(t))}function Kf(e){return e.some(t=>Bf.has(t))}function Vf(e){return e.some(t=>Uf.has(t))}function Gf(e){return e.some(t=>zf.has(t))}function Xf(e){return e.some(t=>Wf.has(t))}function ps(e,t,s){const i=e==="in_progress"?"In progress":e==="needs_attention"?"Needs attention":e==="completed"?"Completed":e==="failed"?"Failed":"Update",r=(s==null?void 0:s.tone)??(e==="completed"?"positive":e==="failed"?"critical":e==="needs_attention"?"warning":"neutral"),a=e==="completed"||e==="failed",l=e==="needs_attention"||e==="failed";return{status:e,label:i,sentence:t,nextAction:(s==null?void 0:s.nextAction)??null,tone:r,isTerminal:a,isActionRequired:l}}function Qf(e){const t=pi(e.sessionStatus),s=pi(e.sessionPhase),i=pi(e.sessionState),r=pi(e.sliceStatus),a=pi(e.activityStatus),l=pi(e.stopReason),c=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,i,r,a,l].filter(_=>_.length>0),u=$a(e.blockingDecisionCount),p=$a(e.nonBlockingDecisionCount),h=$a(e.blockerCount),y=c==="run_failed",g=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",w=y||Hf(d),N=Kf(d)||c==="decision_requested"||u>0||e.decisionRequired===!0,k=Vf(d)||h>0,T=g||Gf(d),D=Xf(d)||c==="run_started";if(w)return ps("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(T&&!N&&!w&&h===0&&!e.blockerReason)return p>0?ps("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ps("completed","Execution completed successfully.",{tone:"positive"});if(N||k)return u>0||e.decisionRequired===!0||c==="decision_requested"?ps("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):ps("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:k?"critical":"warning"});if(T)return p>0?ps("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ps("completed","Execution completed successfully.",{tone:"positive"});if(D){const _=p>0?`Running with ${p} optional decision${p===1?"":"s"} available.`:"Running.";return ps("in_progress",_,{tone:"neutral"})}return ps("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const Pa=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Yf(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vs(e,t){const s=[];let i=0,r=0;Pa.lastIndex=0;for(let a=Pa.exec(e);a;a=Pa.exec(e)){const[l]=a,c=a.index;c>i&&s.push(e.slice(i,c));const d=`${t}-${r++}`,u=a[1],p=a[2],h=a[3],y=a[4],g=a[5],w=a[6],N=a[7];u&&p&&Yf(p)?s.push(n.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):h?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:h},d)):y||g?s.push(n.jsx("strong",{className:"font-semibold text-white",children:y??g},d)):w||N?s.push(n.jsx("em",{className:"italic text-bright",children:w??N},d)):s.push(l),i=c+l.length}return i<e.length&&s.push(e.slice(i)),s}function Jf(e,t){const s=e.split(`
|
|
204
|
+
`),i=[];return s.forEach((r,a)=>{i.push(...Vs(r,`${t}-line-${a}`)),a<s.length-1&&i.push(n.jsx("br",{},`${t}-br-${a}`))}),i}function zr(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Zf(e){const t=zr(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function eh(e){const t=e.trim(),s=t.startsWith(":"),i=t.endsWith(":");return s&&i?"center":i?"right":"left"}function th(e){const t=e.replace(/\r\n/g,`
|
|
205
|
+
`).split(`
|
|
206
|
+
`),s=[];let i=0;for(;i<t.length;){const r=t[i]??"",a=r.trim();if(!a){i+=1;continue}const l=r.includes("|"),c=t[i+1]??"";if(l&&c.includes("|")&&Zf(c)){const y=zr(r),w=zr(c).map(k=>eh(k));i+=2;const N=[];for(;i<t.length;){const k=t[i]??"";if(!k.trim()||!k.includes("|"))break;N.push(zr(k)),i+=1}s.push(n.jsx("div",{className:"overflow-x-auto rounded-xl border border-white/[0.1] bg-black/25",children:n.jsxs("table",{className:"min-w-full border-collapse text-left",children:[n.jsx("thead",{children:n.jsx("tr",{className:"border-b border-white/[0.08] bg-white/[0.03]",children:y.map((k,T)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:w[T]??"left"},children:Vs(k,`tbl-h-${i}-${T}`)},`tbl-h-${T}`))})}),n.jsx("tbody",{children:N.map((k,T)=>n.jsx("tr",{className:T<N.length-1?"border-b border-subtle":void 0,children:y.map((D,b)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:w[b]??"left"},children:Vs(k[b]??"",`tbl-r-${i}-${T}-${b}`)},`tbl-r-${T}-c-${b}`))},`tbl-r-${T}`))})]})},`tbl-${i}`));continue}if(a.startsWith("```")){const y=a.slice(3).trim(),g=[];for(i+=1;i<t.length&&!(t[i]??"").trim().startsWith("```");)g.push(t[i]??""),i+=1;i<t.length&&(i+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[y&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:y}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:g.join(`
|
|
207
|
+
`)})})]},`code-${i}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const y=d[1].length,g=d[2],w=y===1?"text-title font-semibold":y===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:fe("tracking-[-0.01em] text-white",w),children:Vs(g,`h-${i}`)},`h-${i}`)),i+=1;continue}if(r.match(/^\s*[-*]\s+(.+)$/)){const y=[];for(;i<t.length;){const w=(t[i]??"").match(/^\s*[-*]\s+(.+)$/);if(!w)break;y.push(w[1]),i+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:y.map((g,w)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Vs(g,`ul-${i}-${w}`)},`ul-${i}-${w}`))},`ul-${i}`));continue}if(r.match(/^\s*\d+\.\s+(.+)$/)){const y=[];for(;i<t.length;){const w=(t[i]??"").match(/^\s*\d+\.\s+(.+)$/);if(!w)break;y.push(w[1]),i+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:y.map((g,w)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Vs(g,`ol-${i}-${w}`)},`ol-${i}-${w}`))},`ol-${i}`));continue}const h=[];for(;i<t.length;){const y=t[i]??"",g=y.trim();if(!g||/^(#{1,3})\s+/.test(g)||/^\s*[-*]\s+/.test(y)||/^\s*\d+\.\s+/.test(y)||g.startsWith("```"))break;h.push(y),i+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Jf(h.join(`
|
|
208
|
+
`),`p-${i}`)},`p-${i}`))}return s}function Wi({text:e,mode:t="inline",className:s}){const i=e.replace(/\r\n/g,`
|
|
209
|
+
`);return i.trim()?t==="inline"?n.jsx("span",{className:s,children:Vs(i,"inline")}):n.jsx("div",{className:fe("space-y-2",s),children:th(i)}):null}function Dc(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function nh(e){if(!e)return;const t=Dc(e.metadata);return t?{...e,...t}:e}const $c={run_started:{icon:"play",label:"Run started",color:q.teal},run_completed:{icon:"check_circle",label:"Run completed",color:q.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:q.red},artifact_created:{icon:"file",label:"Artifact",color:q.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:q.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:q.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:q.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:q.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:q.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:q.red},milestone_completed:{icon:"flag",label:"Milestone",color:q.cyan},delegation:{icon:"workflow",label:"Delegation",color:q.iris}};function is(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function so(e){return e?e.toLowerCase():""}function sh(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,is(t,["source","event","eventType","artifact_type","action","kind"]),is(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function ih(e,t){const s=so(is(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:q.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:q.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:q.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:q.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:q.cyan}:$c.artifact_created}function rh(e){const t=nh(Dc(e.metadata)),s=sh(e,t),i=so(is(t,["source"])),r=so(is(t,["action"])),a=is(t,["event","event_name","eventName"]);if(a==="auto_continue_started"||a==="auto_continue_stopped"||a==="autopilot_transition"||a==="autopilot_slice_result"||a==="autopilot_slice_finished"){if(a==="auto_continue_started"||a==="autopilot_transition"&&is(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:q.teal};if(a==="auto_continue_stopped"){const c=is(t,["stop_reason"]);return c==="error"||c==="blocked"?{icon:"infinity",label:"Needs attention",color:q.red}:c==="budget_exhausted"?{icon:"infinity",label:"Paused",color:q.amber}:{icon:"infinity",label:"Paused",color:q.amber}}if(a==="autopilot_transition"){const c=is(t,["new_state"]);return c==="blocked"||c==="error"?{icon:"infinity",label:"Needs attention",color:q.red}:{icon:"infinity",label:"In progress",color:q.teal}}const l=is(t,["parsed_status","status"]);return l==="completed"||l==="success"?{icon:"check_circle",label:"Completed",color:q.lime}:l==="blocked"||l==="needs_decision"?{icon:"infinity",label:"Needs attention",color:q.amber}:{icon:"infinity",label:"In progress",color:q.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:q.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:q.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:q.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:q.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:q.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:q.iris};if(i==="local_openclaw")return{icon:"terminal",label:"Local",color:q.teal};if(e.type==="artifact_created")return ih(t,s);if(e.type==="decision_resolved")return r==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:q.red}:{icon:"shield_check",label:"Decision approved",color:q.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:q.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:q.teal}}return $c[e.type]??{icon:"message",label:"Activity",color:q.textMuted}}function ah({icon:e,size:t=14,className:s}){const i={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",className:s};switch(e){case"play":return n.jsx("svg",{...i,children:n.jsx("path",{d:"m8 6 10 6-10 6z"})});case"check_circle":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m8.5 12 2.5 2.5 4.5-5"})]});case"alert_triangle":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m12 3 9 16H3z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 17h.01"})]});case"file":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"})]});case"file_code":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"}),n.jsx("path",{d:"m10 13-2 2 2 2"}),n.jsx("path",{d:"m14 13 2 2-2 2"})]});case"git_commit":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M3 12h6M15 12h6"})]});case"shield":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 16h.01"})]});case"shield_check":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"shield_x":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m10 10 4 4M14 10l-4 4"})]});case"handoff":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M7 8h6a3 3 0 1 1 0 6H8"}),n.jsx("path",{d:"m10 14-3 3-3-3"}),n.jsx("path",{d:"M17 10h-4"})]});case"handoff_claimed":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M8.5 12.5 12 9l3.5 3.5"}),n.jsx("path",{d:"M6 14h12"}),n.jsx("path",{d:"M7 18h10"})]});case"sparkles":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m12 3 1.5 3.5L17 8l-3.5 1.5L12 13l-1.5-3.5L7 8l3.5-1.5z"}),n.jsx("path",{d:"m5 14 .8 1.8L8 16.6l-2.2.8L5 19l-.8-1.6L2 16.6l2.2-.8z"}),n.jsx("path",{d:"m19 14 .8 1.8 2.2.8-2.2.8L19 19l-.8-1.6-2.2-.8 2.2-.8z"})]});case"octagon_x":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m10.2 3-5.8 3.3v11.4L10.2 21h3.6l5.8-3.3V6.3L13.8 3z"}),n.jsx("path",{d:"m9 9 6 6M15 9l-6 6"})]});case"flag":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1"})]});case"workflow":return n.jsx(kc,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...i,children:[n.jsx("ellipse",{cx:"12",cy:"5.5",rx:"6.5",ry:"2.5"}),n.jsx("path",{d:"M5.5 5.5v6c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-6"}),n.jsx("path",{d:"m8 17-2 2 2 2"}),n.jsx("path",{d:"M16 17l2 2-2 2"})]});case"heartbeat":return n.jsx("svg",{...i,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3v6"}),n.jsx("path",{d:"M8 5h8"}),n.jsx("path",{d:"M7 11h10v10H7z"}),n.jsx("path",{d:"M9 14h6"})]});case"quality_gate":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"route":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"6",cy:"6",r:"2"}),n.jsx("circle",{cx:"18",cy:"18",r:"2"}),n.jsx("path",{d:"M8 6h4a4 4 0 0 1 4 4v6"}),n.jsx("path",{d:"M16 6h2"})]});case"terminal":return n.jsxs("svg",{...i,children:[n.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),n.jsx("path",{d:"m7 9 3 3-3 3"}),n.jsx("path",{d:"M13 15h4"})]});case"compass":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m10 10 6-2-2 6-6 2z"})]});case"infinity":return n.jsx("svg",{...i,children:n.jsx("path",{d:"M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.739-8-4.585 0-4.585 8 0 8 5.606 0 7.644-8 12.74-8z"})});case"message":default:return n.jsx("svg",{...i,children:n.jsx("path",{d:"M21 12a8 8 0 0 1-8 8H7l-4 2 1.5-4A8 8 0 1 1 21 12z"})})}}function ta(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function io(e){if(!e)return;const t=ta(e.metadata);return t?{...e,...t}:e}function oh(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function lh(e){let t=0;for(const s of e){const i=io(ta(s.metadata)),r=i==null?void 0:i.costTotal;typeof r=="number"&&(t+=r)}return t<=0?null:t<.01?"<$0.01":`$${t.toFixed(2)}`}const ch=o.memo(function({items:t,session:s,agentName:i,onBack:r,onOpenItem:a}){const[l,c]=o.useState(!1),d=o.useMemo(()=>[...t].sort((g,w)=>Date.parse(g.timestamp)-Date.parse(w.timestamp)),[t]),u=o.useMemo(()=>lh(d),[d]),p=o.useMemo(()=>{if(d.length<2)return null;const g=Date.parse(d[0].timestamp),N=Date.parse(d[d.length-1].timestamp)-g;return N<6e4?`${Math.round(N/1e3)}s`:N<36e5?`${Math.round(N/6e4)}m`:`${(N/36e5).toFixed(1)}h`},[d]),h=o.useMemo(()=>{let g=null,w=null,N=null,k=null,T=null;for(const b of d){const _=io(ta(b.metadata));if(_&&(!g&&typeof _.domain=="string"&&(g=_.domain),!w&&typeof _.provider=="string"&&(w=_.provider),!N&&typeof _.model=="string"&&(N=_.model),!k&&typeof _.spawn_guard_model_tier=="string"&&(k=_.spawn_guard_model_tier),!T&&typeof _.kickoff_context_hash=="string"&&(T=_.kickoff_context_hash),g&&(w||N)&&k&&T))break}return!(g||w||N||k||T)?null:{domain:g,provider:w,model:N,modelTier:k,kickoffContextHash:T}},[d]),y=(s==null?void 0:s.title)??i??"Session";return n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-3",children:[n.jsxs("button",{onClick:r,className:"mb-2 flex items-center gap-1.5 text-caption text-secondary transition-colors hover:text-primary",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back to timeline"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:q.lime,boxShadow:`0 0 12px ${q.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:Xe(y)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-micro text-secondary",children:[i&&n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-subtle px-1 py-0.5",children:[n.jsx(Gt,{name:i,hint:(s==null?void 0:s.id)??(s==null?void 0:s.runId)??null,size:"xs"}),n.jsx("span",{children:i})]}),n.jsxs("span",{children:[d.length," turn",d.length!==1?"s":""]}),p&&n.jsx("span",{children:p}),u&&n.jsx("span",{className:"text-muted",children:u}),(h==null?void 0:h.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:Xe(h.domain)}),(s==null?void 0:s.status)&&n.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-micro uppercase tracking-wider",style:{backgroundColor:s.status==="running"?`${q.lime}20`:s.status==="failed"?`${q.red}20`:`${q.teal}20`,color:s.status==="running"?q.lime:s.status==="failed"?q.red:q.teal},children:s.status}),h&&(h.provider||h.model||h.modelTier||h.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>c(g=>!g),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${l?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),l&&h&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(h.provider||h.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[h.provider?`${Xe(h.provider)} · `:"",h.model?Ki(h.model):"—"]}),h.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",Xe(h.modelTier)]}),h.kickoffContextHash&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 font-mono text-secondary",children:["kickoff ",h.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(bt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${q.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((g,w)=>{var O;const N=rh(g),k=N.color,T=(O=io(ta(g.metadata)))==null?void 0:O.model,D=typeof T=="string"?Ki(T):null,b=Xe(g.title??""),_=g.type==="run_failed",H=g.type==="artifact_created",A=g.type==="decision_requested"||g.type==="decision_resolved";return n.jsxs(ue.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:w*.02},onClick:()=>a==null?void 0:a(g),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-lime/35 focus-visible:ring-offset-1 focus-visible:ring-offset-background",children:[n.jsx("span",{className:"relative z-10 mt-1.5 flex h-[15px] w-[15px] flex-shrink-0 items-center justify-center rounded-full text-[8px]",style:{backgroundColor:`${k}20`,color:k,border:`1px solid ${k}40`},children:n.jsx(ah,{icon:N.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${_?"text-red-400":A?"text-amber-300":H?"text-cyan-300":"text-bright"}`,children:b}),g.summary&&g.summary!==b&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:Xe(g.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:Kr(g.timestamp),children:oh(g.timestamp)}),D&&n.jsx("span",{className:"text-micro text-faint",children:D})]})]},g.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",p?` over ${p}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:Kr(d[d.length-1].timestamp),children:Rt(d[d.length-1].timestamp)})]})]})]})});function dh({completedCount:e,decisionsCount:t,blockerCount:s,visible:i,onDismiss:r}){if(!(e>0||t>0||s>0))return null;const l=[];return e>0&&l.push(`${e} task${e===1?"":"s"} completed`),t>0&&l.push(`${t} need${t===1?"s":""} decisions`),s>0&&l.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(bt,{children:i&&n.jsx(ue.div,{initial:{opacity:0,height:0,marginBottom:0},animate:{opacity:1,height:"auto",marginBottom:12},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{className:"rounded-xl px-4 py-3",style:{backgroundColor:`${q.teal}08`,border:`1px solid ${q.teal}20`},children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"While you were away"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:l.join(" · ")})]}),n.jsx("button",{onClick:r,className:"flex-shrink-0 rounded-md px-2.5 py-1 text-caption font-medium text-secondary transition-colors hover:bg-white/[0.06] hover:text-white",children:"Got it"})]})})})})}const uh={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}},Bi={pr:"#BFFF00",commit:"#BFFF00",test:"#67e8f9",doc:"#0AD4C4",artifact:"#F5B700"};function vl(e){if(!e)return"#67e8f9";const t=e.toLowerCase();return t.includes("code")||t.includes("pull")||t.includes("commit")||t.includes("pr")?Bi.pr:t.includes("doc")||t.includes("spec")?Bi.doc:t.includes("test")?Bi.test:Bi.artifact}const mh={running:"#BFFF00",blocked:"#FF6B88",queued:"rgba(255,255,255,0.5)",completed:"rgba(191,255,0,0.5)",idle:"rgba(255,255,255,0.3)"};function ph({renderKey:e,displayTitle:t,headline:s,contextLabel:i,detailText:r,displayAgentName:a,railColor:l,statusColor:c,userStateLabel:d,userStateWhy:u,relativeTime:p,timeLabel:h,isRecent:y,enableMotion:g,onOpen:w,ariaLabel:N,artifactSnippet:k,evidenceChips:T,actorCategory:D,queuePosition:b}){const _=(T==null?void 0:T.slice(0,2))??[],H=((T==null?void 0:T.length)??0)-_.length,A="group w-full rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-left transition-colors hover:border-strong hover:bg-white/[0.05] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-lime/45 cv-auto",O=D==="system",se=n.jsxs("div",{className:fe("flex items-start gap-3",O&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Gt,{name:D==="user"?"You":a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:fe("absolute inset-y-0 left-0 w-[2px] rounded-full",y&&!O&&"pulse-soft"),style:{backgroundColor:l,boxShadow:O?"none":`0 0 14px ${l}66`}}),n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:fe("truncate text-caption",O?"text-muted italic":"text-secondary"),title:i,children:O?`OrgX · ${i}`:i}),n.jsx("p",{className:fe("mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug",O?"text-secondary":"text-bright"),children:s||t})]}),n.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[n.jsx("span",{className:"text-caption text-secondary",children:h}),n.jsx("span",{className:"text-micro text-muted",children:p})]})]}),k?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5",style:{borderColor:`${vl(k.typeBadge)}33`,backgroundColor:`${vl(k.typeBadge)}0A`},children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-60",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-caption",children:[k.typeBadge&&n.jsxs("span",{className:"mr-1.5 text-micro font-semibold uppercase tracking-wider opacity-70",children:["[",k.typeBadge,"]"]}),n.jsx("span",{className:"font-semibold text-bright",children:k.title??k.label}),k.preview&&!k.title&&n.jsx("span",{className:"ml-1.5 opacity-60",children:k.preview})]}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-40",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})]}):r?n.jsx("div",{className:"mt-1.5 line-clamp-2 text-caption leading-relaxed text-secondary",children:n.jsx(Wi,{mode:"inline",text:r})}):null,_.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[_.map(M=>{const L=Bi[M.kind];return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro font-semibold uppercase tracking-wider",style:{color:L,backgroundColor:`${L}14`,border:`1px solid ${L}30`},children:[M.kind==="pr"&&"PR",M.kind==="commit"&&"Commit",M.kind==="test"&&"Tests",M.kind==="doc"&&"Doc",M.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${L}CC`},children:M.label})]},`${M.kind}-${M.label}`)}),H>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",H," more"]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${c??l}55`,backgroundColor:`${c??l}1A`,color:c??l},title:u,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c??l}}),d]}),n.jsx("span",{className:"inline-flex max-w-[220px] items-center gap-1 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",title:a,children:n.jsx("span",{className:"truncate",children:a})}),b&&(()=>{const M=mh[b.state]??"rgba(255,255,255,0.3)";return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${M}55`,backgroundColor:`${M}1A`,color:M},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:M}}),b.state==="running"?"Active":`#${b.rank}`]})})()]})]})]});return g?n.jsx(ue.button,{type:"button",variants:uh,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:w,className:A,"aria-label":N,children:se},e):n.jsx("button",{type:"button",onClick:w,className:fe(A,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":N,children:se},e)}function fh({open:e,onClose:t,children:s}){return n.jsx(oa,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function hh(e){const t=e.metadata??{},s=e.phase??e.state??t.phase??"",i=e.state??"",r=t.event??t.event_name??"";if(s==="completed"||r==="auto_continue_started"||i==="completed")return"teal";if(s==="blocked"||i==="blocked"||i==="error"||r==="auto_continue_stopped"){const a=t.stop_reason??"";return a==="error"||a==="blocked"?"red":a==="budget_exhausted"||a==="stopped"?"amber":s==="blocked"||i==="error"?"red":"amber"}return e.decisionRequired||i==="needs_input"?"amber":"neutral"}const gh={teal:{border:"border-[#0AD4C4]/20",bg:"bg-[#0AD4C4]/[0.04]",dot:"bg-[#0AD4C4]",label:"text-[#7AEDE5]"},amber:{border:"border-[#F5B700]/20",bg:"bg-[#F5B700]/[0.04]",dot:"bg-[#F5B700]",label:"text-[#FFE7A8]"},red:{border:"border-[#FF6B6B]/20",bg:"bg-[#FF6B6B]/[0.04]",dot:"bg-[#FF6B6B]",label:"text-[#FFA8A8]"},neutral:{border:"border-white/[0.04]",bg:"bg-white/[0.02]",dot:"bg-white/40",label:"text-secondary"}};function xh({item:e,className:t}){var p,h,y;const s=o.useMemo(()=>wi(e),[e]),i=hh(e),r=gh[i],a=typeof((p=e.metadata)==null?void 0:p.agent_name)=="string"?e.metadata.agent_name:typeof((h=e.metadata)==null?void 0:h.agentName)=="string"?e.metadata.agentName:e.agentName??"OrgX",l=((y=e.type)==null?void 0:y.replace(/_/g," "))??"activity",d=s.scope||s.update||s.status||s.artifacts.length>0||s.outcomes.length>0||s.nextUp.length>0?null:`${a} recorded a ${l}`,u=[s.update?{label:"Update",value:s.update}:null,s.scope||d?{label:"Scope",value:s.scope??d}:null,s.status?{label:"Status",value:s.status}:null,s.artifacts.length>0?{label:"Artifacts",values:s.artifacts}:null,s.outcomes.length>0?{label:"Outcomes",values:s.outcomes}:null,s.nextUp.length>0?{label:"Next up",values:s.nextUp}:null].filter(Boolean);return n.jsx(ue.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:`rounded-lg border ${r.border} ${r.bg} p-6 space-y-5 ${t??""}`,children:u.map((g,w)=>n.jsx(ue.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{duration:.25,delay:.08+w*.06,ease:[.22,1,.36,1]},children:n.jsx(yh,{label:g.label,value:g.value,values:g.values,styles:r})},g.label))})}function yh({label:e,value:t,values:s,styles:i}){return n.jsx("div",{className:"flex items-start gap-4",children:n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:`text-micro font-semibold uppercase tracking-wider ${i.label}`,children:e}),typeof t=="string"?n.jsx("p",{className:"mt-1 text-body leading-relaxed text-primary",children:t}):null,Array.isArray(s)&&s.length>0?n.jsx("ul",{className:"mt-1 space-y-1",children:s.slice(0,5).map(r=>n.jsx("li",{className:"text-body leading-relaxed text-primary",children:r},r))}):null]})})}const wl=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),bh=[{id:"eli",name:"Eli",handle:"eli",domain:"engineering",domainLabel:"Engineering",role:"Engineering"},{id:"dana",name:"Dana",handle:"dana",domain:"design",domainLabel:"Product Design",role:"Product Design"},{id:"mark",name:"Mark",handle:"mark",domain:"marketing",domainLabel:"Marketing",role:"Marketing"},{id:"sage",name:"Sage",handle:"sage",domain:"sales",domainLabel:"Sales",role:"Sales"},{id:"orion",name:"Orion",handle:"orion",domain:"operations",domainLabel:"Operations",role:"Operations"},{id:"pace",name:"Pace",handle:"pace",domain:"engineering",domainLabel:"Engineering",role:"Engineering"}],$i=[{id:"auto",label:"Auto (best available)",shortLabel:"Auto",accent:"#8F9AB7",icon:"auto"},{id:"anthropic",label:"Claude Code",shortLabel:"Claude",accent:"#F5B700",icon:"anthropic"},{id:"openai",label:"Codex",shortLabel:"Codex",accent:"#10B981",icon:"openai"}],kl={type:"spring",stiffness:400,damping:25},Il={scale:.985};function fn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function vh(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?"Unknown size":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Pi(e,t){const s=(e??"").trim().toLowerCase();return s.includes("unknown api endpoint")?"Chat API unavailable in current runtime. Restart the plugin so /orgx/api/chat/* routes are active.":s.includes("network error")||s.includes("failed to fetch")?t==="load"?"Could not load thread details. Check connection and retry.":"Connection lost while sending. Draft is preserved.":s?It(Xt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function wh(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function kh(e,t){return t==="all"?!0:t==="completed"?e.status==="completed":t==="in_progress"?e.status==="queued"||e.status==="running":t==="needs_attention"?e.status==="blocked"||e.status==="failed":!0}function na(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function bi(e){return e==="running"?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":e==="completed"?"border-teal/30 bg-teal/[0.12] text-teal-100":e==="blocked"||e==="failed"?"border-rose-400/30 bg-rose-400/[0.12] text-rose-100":e==="queued"?"border-white/[0.18] bg-white/[0.08] text-primary":"border-white/[0.12] bg-white/[0.04] text-secondary"}function Pc(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function Ih(e){return e==="agent"?"assistant":e}function Nh(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function jh(e,t){return t.map(s=>({id:s.id,role:Ih(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function Oc(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function vi(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Wr(e){const t=vi(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const i=vi(t.latestMessage),r=vi(t.latestLaunch);return{id:s,commandCenterId:typeof t.commandCenterId=="string"?t.commandCenterId:null,initiativeId:typeof t.initiativeId=="string"?t.initiativeId:null,initiativeTitle:typeof t.initiativeTitle=="string"?t.initiativeTitle:null,workstreamId:typeof t.workstreamId=="string"?t.workstreamId:null,taskId:typeof t.taskId=="string"?t.taskId:null,title:typeof t.title=="string"&&t.title.trim().length>0?t.title:"Untitled thread",summary:typeof t.summary=="string"?t.summary:null,status:t.status==="queued"||t.status==="running"||t.status==="blocked"||t.status==="completed"||t.status==="failed"||t.status==="message_only"?t.status:"message_only",assigneeId:typeof t.assigneeId=="string"?t.assigneeId:null,assigneeName:typeof t.assigneeName=="string"?t.assigneeName:null,watcherIds:Array.isArray(t.watcherIds)?t.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(t.watcherNames)?t.watcherNames.filter(a=>typeof a=="string"):[],messageCount:typeof t.messageCount=="number"?Math.max(0,Math.floor(t.messageCount)):0,launchCount:typeof t.launchCount=="number"?Math.max(0,Math.floor(t.launchCount)):0,lastMessageAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:null,lastLaunchAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:null,lastActivityAt:typeof t.lastActivityAt=="string"&&t.lastActivityAt.length>0?t.lastActivityAt:new Date().toISOString(),lastSnippet:typeof t.lastSnippet=="string"?t.lastSnippet:null,createdAt:typeof t.createdAt=="string"?t.createdAt:new Date().toISOString(),updatedAt:typeof t.updatedAt=="string"?t.updatedAt:new Date().toISOString(),latestMessage:i?{id:typeof i.id=="string"?i.id:`msg_${s}`,threadId:typeof i.threadId=="string"?i.threadId:s,role:i.role==="agent"||i.role==="system"?i.role:"user",body:typeof i.body=="string"?i.body:"",senderId:typeof i.senderId=="string"?i.senderId:null,senderName:typeof i.senderName=="string"?i.senderName:null,createdAt:typeof i.createdAt=="string"?i.createdAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),updatedAt:typeof i.updatedAt=="string"?i.updatedAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),attachments:Array.isArray(i.attachments)?i.attachments.filter(a=>!!a&&typeof a=="object"):[],metadata:i.metadata&&typeof i.metadata=="object"?i.metadata:{}}:null,latestLaunch:r?{id:typeof r.id=="string"?r.id:`launch_${s}`,threadId:typeof r.threadId=="string"?r.threadId:s,messageId:typeof r.messageId=="string"?r.messageId:typeof t.lastMessageAt=="string"?`msg_${t.lastMessageAt}`:`msg_${s}`,assigneeId:typeof r.assigneeId=="string"?r.assigneeId:null,assigneeName:typeof r.assigneeName=="string"?r.assigneeName:null,watcherIds:Array.isArray(r.watcherIds)?r.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(r.watcherNames)?r.watcherNames.filter(a=>typeof a=="string"):[],executionMode:r.executionMode==="cloud"||r.executionMode==="hybrid"?r.executionMode:"local_queue",provider:typeof r.provider=="string"?r.provider:null,runId:typeof r.runId=="string"?r.runId:null,status:r.status==="queued"||r.status==="running"||r.status==="blocked"||r.status==="completed"||r.status==="failed"||r.status==="requested"?r.status:"requested",blockedReason:typeof r.blockedReason=="string"?r.blockedReason:null,warnings:Array.isArray(r.warnings)?r.warnings.filter(a=>typeof a=="string"):[],requestedAt:typeof r.requestedAt=="string"?r.requestedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),metadata:r.metadata&&typeof r.metadata=="object"?r.metadata:{}}:null}}function Ah(e){const t=vi(e);if(!t)return null;const s=Wr({...t,latestMessage:Array.isArray(t.messages)?t.messages[t.messages.length-1]:null,latestLaunch:Array.isArray(t.launches)?t.launches[0]:null});if(!s)return null;const i=Array.isArray(t.messages)?t.messages.map(a=>vi(a)).filter(a=>!!a).map(a=>{const l=a.role==="agent"||a.role==="system"?a.role:"user";return{id:typeof a.id=="string"?a.id:`msg_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,role:l,body:typeof a.body=="string"?a.body:"",senderId:typeof a.senderId=="string"?a.senderId:null,senderName:typeof a.senderName=="string"?a.senderName:null,createdAt:typeof a.createdAt=="string"?a.createdAt:s.createdAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,attachments:Array.isArray(a.attachments)?a.attachments.filter(c=>!!c&&typeof c=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],r=Array.isArray(t.launches)?t.launches.map(a=>vi(a)).filter(a=>!!a).map(a=>{const l=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",c=a.status==="queued"||a.status==="running"||a.status==="blocked"||a.status==="completed"||a.status==="failed"||a.status==="requested"?a.status:"requested";return{id:typeof a.id=="string"?a.id:`launch_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,messageId:typeof a.messageId=="string"?a.messageId:"",assigneeId:typeof a.assigneeId=="string"?a.assigneeId:null,assigneeName:typeof a.assigneeName=="string"?a.assigneeName:null,watcherIds:Array.isArray(a.watcherIds)?a.watcherIds.filter(d=>typeof d=="string"):[],watcherNames:Array.isArray(a.watcherNames)?a.watcherNames.filter(d=>typeof d=="string"):[],executionMode:l,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:c,blockedReason:typeof a.blockedReason=="string"?a.blockedReason:null,warnings:Array.isArray(a.warnings)?a.warnings.filter(d=>typeof d=="string"):[],requestedAt:typeof a.requestedAt=="string"?a.requestedAt:s.updatedAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[];return{...s,messages:i.sort((a,l)=>fn(a.createdAt)-fn(l.createdAt)),launches:r.sort((a,l)=>fn(l.requestedAt)-fn(a.requestedAt))}}function _h(e,t,s){const i=fn(e.lastActivityAt);if(!i)return!1;if(t==="custom"){const a=fn(s.startIso),l=fn(s.endIso);return!(a&&i<a||l&&i>l)}const r=Yi(t,Date.now());return r?i>=r:!0}async function Oi(e,t){try{const s=await fetch(e,t),i=await s.json().catch(()=>null);return s.ok?{ok:!0,status:s.status,data:i,error:null}:{ok:!1,status:s.status,data:null,error:(i&&typeof i.error=="string"?i.error:null)??`Request failed (${s.status})`}}catch(s){return{ok:!1,status:0,data:null,error:s instanceof Error?s.message:"Network error"}}}function Oa(e,t){const s=new Map;for(const i of e)s.set(i.id,i);return s.set(t.id,t),Array.from(s.values()).sort((i,r)=>fn(r.lastActivityAt??r.updatedAt)-fn(i.lastActivityAt??i.updatedAt))}function Sh(e,t){const s=new Map;for(const i of e)s.set(i.id,i);for(const i of t)s.set(i.id,i);return Array.from(s.values()).sort((i,r)=>fn(r.lastActivityAt??r.updatedAt)-fn(i.lastActivityAt??i.updatedAt))}const qc=o.createContext(null),Fc=o.createContext(null);function go(){const e=o.useContext(qc);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function xo(){const e=o.useContext(Fc);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function Ch({children:e,sessions:t,initiatives:s,workspaceId:i,query:r,statusFilter:a,sortOrder:l,timeFilterId:c,customTimeRange:d,snapshot:u,onRequestRefresh:p}){const[h,y]=o.useState((u==null?void 0:u.threads)??[]),[g,w]=o.useState(null),[N,k]=o.useState(null),[T,D]=o.useState(!1),[b,_]=o.useState(null),[H,A]=o.useState("resting"),[O,se]=o.useState(""),[M,L]=o.useState(!1),[ae,be]=o.useState(!1),[ie,P]=o.useState(null),[xe,ne]=o.useState(null),[K,G]=o.useState([]),[le,Le]=o.useState(""),[Me,me]=o.useState([]),[Ne,E]=o.useState(""),[W,V]=o.useState(null),[Y,Ie]=o.useState(""),[De,he]=o.useState(!1),[je,R]=o.useState(""),[Ae,Se]=o.useState([]),[Ee,$e]=o.useState(!1),[ye,mt]=o.useState("auto"),[Ce,_e]=o.useState(!1),[ee,dt]=o.useState(!1),[yt,Be]=o.useState(!1),te=o.useRef(null),B=o.useRef(null),oe=o.useRef(null),pe=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&y(z=>Sh(z,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{g&&y(z=>z.sort((we,ke)=>fn(ke.lastActivityAt)-fn(we.lastActivityAt)))},[g]);const{data:Pe}=ho({enabled:!0,refetchInterval:8e3}),We=o.useMemo(()=>{var we,ke;const z=new Map;for(const Fe of bh)z.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.handle,domain:Fe.domain,domainLabel:Fe.domainLabel,role:Fe.role,status:"idle",currentTask:null,isSystem:!1});if(Pe!=null&&Pe.agents)for(const Fe of Pe.agents){const wt=z.get(Fe.id);wt?(wt.status=Fe.status==="running"?"running":(we=Fe.blockers)!=null&&we.length?"blocked":"idle",wt.currentTask=Fe.currentTask??null):z.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Fe.status==="running"?"running":(ke=Fe.blockers)!=null&&ke.length?"blocked":"idle",currentTask:Fe.currentTask??null,isSystem:wl.has(Fe.id)})}for(const Fe of t){const wt=(Fe.agentId??"").trim(),jt=(Fe.agentName??"").trim();!wt||!jt||z.has(wt)||z.set(wt,{id:wt,name:jt,handle:wt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:wl.has(wt)})}return Array.from(z.values()).filter(Fe=>!Fe.isSystem).sort((Fe,wt)=>Fe.name.localeCompare(wt.name))},[Pe,t]),rt=o.useMemo(()=>s.map(z=>({id:z.id,name:z.name})).sort((z,we)=>z.name.localeCompare(we.name)),[s]),ge=o.useMemo(()=>We.find(z=>z.id===le)??null,[We,le]),Ve=o.useMemo(()=>{const z=new Set(Me);return We.filter(we=>z.has(we.id))},[We,Me]),ce=o.useMemo(()=>rt.find(z=>z.id===Ne)??null,[rt,Ne]);o.useEffect(()=>{le&&me(z=>z.filter(we=>we!==le))},[le]);const X=o.useMemo(()=>We.slice(0,8),[We]),Te=o.useMemo(()=>{const z=Y.trim().toLowerCase();return z?We.filter(we=>we.name.toLowerCase().includes(z)||we.handle.toLowerCase().includes(z)||we.domain.toLowerCase().includes(z)||we.role.toLowerCase().includes(z)):We},[We,Y]),Ze=o.useMemo(()=>{const z=je.trim().toLowerCase();return z?rt.filter(we=>we.name.toLowerCase().includes(z)):rt},[rt,je]),at=o.useMemo(()=>{const z=r.trim().toLowerCase(),we=h.filter(ke=>!kh(ke,a)||!_h(ke,c,d)?!1:z.length===0?!0:wh(ke).includes(z));return we.sort((ke,Fe)=>{const wt=fn(Fe.lastActivityAt)-fn(ke.lastActivityAt);return l==="newest"?wt:-wt}),we},[d,r,l,a,h,c]),pt=o.useMemo(()=>{if(!g||at.some(we=>we.id===g))return at;const z=h.find(we=>we.id===g);return z?[z,...at]:at},[g,at,h]),ct=o.useMemo(()=>h.find(z=>z.id===g)??null,[g,h]),ht=o.useMemo(()=>K.filter(z=>z.status!=="ready").length,[K]),Z=O.trim().length>0&&!M,ve=o.useMemo(()=>ht>0?`${ht} attachment(s) still processing.`:"Press Enter to send.",[ht]),Oe=o.useMemo(()=>M?"Sending…":ae?"Launching…":"Send",[ae,M]),Ge=o.useMemo(()=>new xd({api:"/orgx/api/chat/usechat"}),[]),{messages:Re,setMessages:He,sendMessage:Ue,status:ft,error:Ht,clearError:gt}=yd({id:`orgx-chat-guidance-${i??"global"}`,transport:Ge,onError:z=>{P(Pi((z==null?void 0:z.message)??null,"send"))}});o.useEffect(()=>{if(!N){He([]);return}He(jh(N.id,N.messages))},[N,He]);const vt=o.useMemo(()=>{const z=[...Re].reverse().find(ke=>ke.role==="assistant");if(!z)return null;const we=Nh(z);return we.length>0?we:null},[Re]),Tt=o.useRef(null);o.useEffect(()=>{if(ft!=="ready"&&ft!=="error"||!vt)return;const z=[...Re].reverse().find(we=>we.role==="assistant");!z||z.id===Tt.current||(Tt.current=z.id,Se(we=>[...we,{id:`guidance_${z.id}`,role:"agent",body:vt,timestamp:new Date().toISOString()}]))},[ft,vt,Re]);const Ut=o.useCallback(()=>{se(""),G([]),dt(!1),Be(!1),P(null),ne(null)},[]),nt=o.useCallback(z=>{Se(we=>[...we,{...z,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),et=o.useCallback(()=>Se([]),[]),$t=o.useCallback(()=>$e(z=>!z),[]),St=o.useMemo(()=>$i.find(z=>z.id===ye)??$i[0],[ye]),Mt=o.useCallback(()=>{mt(z=>{const we=$i.findIndex(ke=>ke.id===z);return $i[(we+1)%$i.length].id})},[]),Ct=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),Kt=o.useCallback(async z=>{var Fe;D(!0),_(null);const we=await Oi(`/orgx/api/chat/threads/${encodeURIComponent(z)}`);if(!we.ok||!((Fe=we.data)!=null&&Fe.thread))return D(!1),_(Pi(we.error,"load")),null;const ke=Ah(we.data.thread);return ke?(k(ke),D(!1),ke):(D(!1),_("Thread detail payload was invalid."),null)},[]),vn=o.useCallback(async(z,we)=>{we&&(oe.current=we),w(z),await Kt(z),requestAnimationFrame(()=>{var ke;return(ke=B.current)==null?void 0:ke.focus()})},[Kt]),ys=o.useCallback(()=>{var z;w(null),k(null),_(null),D(!1),(z=oe.current)==null||z.focus()},[]),Kn=o.useCallback(z=>{window.setTimeout(()=>{G(we=>we.map(ke=>ke.id===z?{...ke,status:"indexing",updatedAt:new Date().toISOString()}:ke))},80),window.setTimeout(()=>{G(we=>we.map(ke=>{var jt;if(ke.id!==z)return ke;const Fe=((jt=ke.mimeType)==null?void 0:jt.toLowerCase())==="application/x-msdownload"||ke.name.toLowerCase().endsWith(".exe"),wt=(ke.sizeBytes??0)>25*1024*1024;return Fe?{...ke,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:wt?{...ke,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...ke,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Vn=o.useCallback(z=>{if(!z||z.length===0)return;const we=new Date().toISOString(),ke=Array.from(z).map(Fe=>({id:`draft_att_${crypto.randomUUID()}`,name:Fe.name,mimeType:Fe.type||null,sizeBytes:Number.isFinite(Fe.size)?Fe.size:null,status:"preparing",error:null,masked:!1,createdAt:we,updatedAt:we}));G(Fe=>Fe.concat(ke)),ke.forEach(Fe=>Kn(Fe.id)),js("chat_attachment_state_changed",{count:ke.length,state:"preparing"})},[Kn]),Gn=o.useCallback(z=>{G(we=>we.map(ke=>ke.id===z?{...ke,status:"preparing",error:null,updatedAt:new Date().toISOString()}:ke)),Kn(z),js("chat_attachment_state_changed",{state:"retry"})},[Kn]),Xn=o.useCallback(z=>{Le(we=>we===z?"":z),me(we=>we.filter(ke=>ke!==z)),V(null),Ie("")},[]),Es=o.useCallback(z=>{me(we=>we.includes(z)?we.filter(ke=>ke!==z):we.concat(z))},[]),wn=o.useCallback(()=>{he(!1),R(""),V(z=>z==="assignee"?null:"assignee"),Ie("")},[]),Qt=o.useCallback(()=>{he(!1),R(""),V(z=>z==="watcher"?null:"watcher"),Ie("")},[]),an=o.useCallback(()=>{V(null),Ie(""),he(z=>!z),R("")},[]),hn=o.useCallback(async(z,we)=>{var jt;_e(!0);const ke=rt.find(st=>st.id===we)??null,Fe=await Oi("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:z,project_id:i??void 0,initiativeId:(ke==null?void 0:ke.id)??null,initiativeTitle:(ke==null?void 0:ke.name)??null,relinked:!0})});if(_e(!1),!Fe.ok||!((jt=Fe.data)!=null&&jt.thread)){_(Fe.error??"Scope link failed.");return}const wt=Wr(Fe.data.thread);wt&&y(st=>Oa(st,wt)),await Kt(z),await Ct(),js("chat_thread_linked_initiative",{threadId:z,initiativeId:(ke==null?void 0:ke.id)??null})},[rt,Kt,Ct,i]),Rs=o.useCallback(async z=>{gt(),await Ue({text:z.prompt},{body:{threadId:z.thread.id,project_id:i??void 0,initiativeId:z.thread.initiativeId??(ce==null?void 0:ce.id)??void 0,initiativeTitle:z.thread.initiativeTitle??(ce==null?void 0:ce.name)??void 0,assigneeId:(ge==null?void 0:ge.id)??z.thread.assigneeId??void 0,assigneeName:(ge==null?void 0:ge.name)??z.thread.assigneeName??void 0,watcherIds:Ve.map(we=>we.id),watcherNames:Ve.map(we=>we.name)}}),await Ct(),await Kt(z.thread.id)},[gt,Kt,Ct,ge==null?void 0:ge.id,ge==null?void 0:ge.name,ce==null?void 0:ce.id,ce==null?void 0:ce.name,Ve,Ue,i]),Qn=o.useCallback(async()=>{var wt,jt;const z=O.trim();if(!z)return P("Write a message before sending."),{thread:null,messageId:null};P(null),ne(null),L(!0);const we=await Oi("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:g??void 0,project_id:i??void 0,initiativeId:(ce==null?void 0:ce.id)??(N==null?void 0:N.initiativeId)??void 0,initiativeTitle:(ce==null?void 0:ce.name)??(N==null?void 0:N.initiativeTitle)??void 0,assigneeId:(ge==null?void 0:ge.id)??(N==null?void 0:N.assigneeId)??void 0,assigneeName:(ge==null?void 0:ge.name)??(N==null?void 0:N.assigneeName)??void 0,watcherIds:Ve.map(st=>st.id),watcherNames:Ve.map(st=>st.name),body:z,attachments:K.map(st=>({id:st.id,name:st.name,mimeType:st.mimeType,sizeBytes:st.sizeBytes,status:st.status,error:st.error,masked:st.masked}))})});if(L(!1),!we.ok||!((wt=we.data)!=null&&wt.thread))return P(Pi(we.error,"send")),js("chat_message_send_failed",{reason:we.error??"unknown"}),{thread:null,messageId:null};const ke=Wr(we.data.thread);if(!ke)return P("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};y(st=>Oa(st,ke)),nt({role:"user",body:z}),ye!=="auto"&&ge&&nt({role:"system",body:`Routing to ${ge.name} via ${St.label}`}),js("chat_message_sent",{threadId:ke.id,watcherCount:ke.watcherIds.length}),await Ct();const Fe=we.data.message&&typeof we.data.message.id=="string"?we.data.message.id:((jt=ke.latestMessage)==null?void 0:jt.id)??null;return w(ke.id),await Kt(ke.id),Rs({thread:ke,prompt:z}).catch(st=>{nt({role:"error",body:Pi(st instanceof Error?st.message:String(st??""),"send")})}),Ut(),A("reviewing"),{thread:ke,messageId:Fe}},[N==null?void 0:N.assigneeId,N==null?void 0:N.assigneeName,N==null?void 0:N.initiativeId,N==null?void 0:N.initiativeTitle,g,O,K,Kt,Ct,Ut,Rs,ge==null?void 0:ge.id,ge==null?void 0:ge.name,ce==null?void 0:ce.id,ce==null?void 0:ce.name,ye,St,Ve,i]),bs=o.useCallback(async(z,we)=>{var Zn,Et,dn,as,es,Ds,$s;if(!we){nt({role:"error",body:"Send a message first to launch."});return}if(!ge){nt({role:"error",body:"Pick an agent with @ before launching."});return}if(ht>0&&!yt){dt(!0),nt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}be(!0),P(null),ne(null);const ke=await Oi("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:ge.id,message:O.trim().length>0?O.trim():z.lastSnippet??z.title,initiativeId:z.initiativeId??(ce==null?void 0:ce.id)??void 0,initiativeTitle:z.initiativeTitle??(ce==null?void 0:ce.name)??void 0,workstreamId:z.workstreamId??void 0,taskId:z.taskId??void 0,provider:ye!=="auto"?ye:void 0})}),Fe=((Zn=ke.data)==null?void 0:Zn.sessionId)??((Et=ke.data)==null?void 0:Et.runId)??null,wt=ke.ok&&Fe?"running":ke.ok?"queued":"blocked",jt=ke.ok?null:ke.error??"Launch request failed before queueing.",st=await Oi("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:z.id,messageId:we,assigneeId:ge.id,assigneeName:ge.name,watcherIds:Ve.map(os=>os.id),watcherNames:Ve.map(os=>os.name),executionMode:"local_queue",provider:((dn=ke.data)==null?void 0:dn.provider)??(ye!=="auto"?ye:"openclaw"),runId:Fe??void 0,status:wt,blockedReason:jt??void 0,warnings:ht>0?[`${ht} attachment(s) were not ready at launch.`]:[]})});if(be(!1),Be(!1),dt(!1),!st.ok||!((as=st.data)!=null&&as.thread)){P(st.error?Pi(st.error,"launch"):jt??"Launch state could not be persisted. Message remained saved."),js("chat_launch_failed",{threadId:z.id,reason:st.error??jt??"unknown"});return}const Yt=Wr(st.data.thread);if(Yt&&y(os=>Oa(os,Yt)),await Kt(z.id),await Ct(),!ke.ok){P(`Launch blocked: ${jt??"Set assignee and retry."}`),js("chat_launch_blocked",{threadId:z.id,reason:jt??"unknown"});return}const At=((es=ke.data)==null?void 0:es.provider)==="anthropic"?"Claude Code":((Ds=ke.data)==null?void 0:Ds.provider)==="openai"?"Codex":St.shortLabel,Jn=($s=ke.data)!=null&&$s.model?` (${ke.data.model})`:"";ne(Fe?`Launch started via ${At}${Jn}. Thread timeline now tracks execution state.`:`Launch queued locally via ${At}. Run starts when a worker is available.`),js(Fe?"chat_launch_started":"chat_launch_queued",{threadId:z.id,runId:Fe,assigneeId:ge.id})},[O,yt,Kt,Ct,ge,ce==null?void 0:ce.id,ce==null?void 0:ce.name,ye,St,Ve,ht]),ti=o.useCallback(async()=>{var we;const z=await Qn();(we=z.thread)!=null&&we.id&&await vn(z.thread.id)},[vn,Qn]),Ls=o.useCallback(async()=>{const z=await Qn();z.thread&&(await bs(z.thread,z.messageId),await vn(z.thread.id))},[bs,vn,Qn]),Vt=o.useCallback(async()=>{if(Z){if(ge){await Ls();return}await ti()}},[Z,Ls,ti,ge]),Cn=o.useMemo(()=>({threads:h,activeThreadId:g,activeThread:N,activeThreadSummary:ct,displayedThreads:pt,composerMode:H,draft:O,draftAttachments:K,sending:M,launching:ae,composerError:ie,composerNotice:xe,selectedAssigneeId:le,selectedAssignee:ge,selectedWatcherIds:Me,selectedWatchers:Ve,selectedInitiativeId:Ne,selectedInitiative:ce,agentOptions:We,quickAssigneeOptions:X,initiativeOptions:rt,agentPickerMode:W,agentPickerQuery:Y,filteredAgentOptions:Te,scopePickerOpen:De,scopePickerQuery:je,filteredInitiativeOptions:Ze,panelLoading:T,panelError:b,scopeSaving:Ce,launchWarningOpen:ee,launchWarningAccepted:yt,unresolvedAttachmentCount:ht,canSend:Z,composerGuidance:ve,primaryActionLabel:Oe,guidanceStatus:ft,guidancePreview:vt,guidanceError:Ht??null,inlineMessages:Ae,threadSidebarOpen:Ee,workspaceId:i,selectedProvider:ye,selectedProviderDef:St}),[h,g,N,ct,pt,H,O,K,M,ae,ie,xe,le,ge,Me,Ve,Ne,ce,We,X,rt,W,Y,Te,De,je,Ze,T,b,Ce,ee,yt,ht,Z,ve,Oe,ft,vt,Ht,Ae,Ee,i,ye,St]),Yn=o.useMemo(()=>({setDraft:se,setComposerMode:A,setDraftAttachments:G,selectAssignee:Xn,toggleWatcher:Es,setSelectedInitiativeId:E,toggleAssigneePicker:wn,toggleWatcherPicker:Qt,toggleScopePicker:an,setAgentPickerQuery:Ie,setScopePickerQuery:R,setAgentPickerMode:V,setScopePickerOpen:he,handlePrimaryAction:Vt,handleFilesAdded:Vn,handleRetryAttachment:Gn,openThreadPanel:vn,closeThreadPanel:ys,loadThreadDetail:Kt,applyScopeLink:hn,resetComposer:Ut,setComposerError:P,setComposerNotice:ne,setLaunchWarningAccepted:Be,pushInlineMessage:nt,clearInlineMessages:et,toggleThreadSidebar:$t,setSelectedProvider:mt,cycleProvider:Mt,fileInputRef:te,panelHeadingRef:B,composerShellRef:pe}),[Xn,Es,wn,Qt,an,Vt,Vn,Gn,vn,ys,Kt,hn,Ut,nt,et,$t,Mt]);return n.jsx(qc.Provider,{value:Cn,children:n.jsx(Fc.Provider,{value:Yn,children:e})})}const Th={type:"spring",stiffness:500,damping:35,mass:.5};function Mh({messages:e,isStreaming:t,collapsed:s,onClick:i}){var c;const r=xs(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(c=e[e.length-1])==null?void 0:c.body]);const l=s?e.slice(-2):e;return l.length===0?null:n.jsx(ue.div,{initial:r?!1:{opacity:0,height:0},animate:r?{}:{opacity:1,height:"auto"},exit:r?{}:{opacity:0,height:0},transition:r?void 0:{duration:.25,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{ref:a,onClick:i,role:i?"button":void 0,tabIndex:i?0:void 0,className:fe("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",i&&"cursor-pointer"),children:n.jsx(bt,{initial:!1,children:l.map(d=>n.jsx(ue.div,{initial:r?!1:{opacity:0,y:8,scale:.97},animate:r?{}:{opacity:1,y:0,scale:1},transition:r?void 0:Th,className:fe("flex",d.role==="user"?"justify-end":"justify-start",d.role==="system"&&"justify-center"),children:d.role==="system"?n.jsx("p",{className:"text-micro italic text-muted",children:d.body}):n.jsxs("div",{className:fe("max-w-[85%] rounded-2xl px-3 py-2",d.role==="user"&&"bg-lime/[0.1]",d.role==="agent"&&"bg-white/[0.05]",d.role==="error"&&"bg-rose-400/[0.1]"),children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:fe("text-micro font-medium",d.role==="user"&&"text-[#E1FFB2]/80",d.role==="agent"&&"text-secondary",d.role==="error"&&"text-rose-200"),children:d.role==="user"?"You":d.role==="error"?"Error":"Agent"}),n.jsx("time",{className:"text-[10px] text-muted/60",dateTime:d.timestamp,children:Rt(d.timestamp)})]}),n.jsxs("p",{className:fe("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===l[l.length-1]&&d.role==="agent"&&n.jsx("span",{className:"ml-0.5 inline-block h-[14px] w-[2px] translate-y-[2px] rounded-full bg-white/50",style:{animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}})]})]})},d.id))})})})}function Nl({open:e,onClose:t}){const s=xs(),{displayedThreads:i,activeThreadId:r,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:u,initiativeOptions:p}=go(),{openThreadPanel:h,closeThreadPanel:y,loadThreadDetail:g,applyScopeLink:w,panelHeadingRef:N}=xo(),k=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,T=o.useCallback((b,_)=>{h(b,_)},[h]),D=o.useCallback(()=>{y(),t()},[y,t]);return n.jsx(bt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ue.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:D,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(ue.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Wt.durationEntrance/1e3,ease:Wt.easingEntrance},"aria-label":"Thread history","data-testid":"thread-drawer",className:"fixed bottom-0 left-0 right-0 z-25 flex max-h-[min(60vh,480px)] flex-col rounded-t-[22px] border-t border-white/[0.14] bg-[#0A0E16]/95 shadow-[0_-12px_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",style:{paddingBottom:"max(12px, env(safe-area-inset-bottom))"},children:[n.jsx("div",{className:"flex justify-center py-2",children:n.jsx("div",{className:"h-1 w-10 rounded-full bg-white/[0.16]"})}),n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:i.length})]}),n.jsx("button",{type:"button",onClick:D,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread drawer",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:fe("grid min-h-0 flex-1 overflow-hidden",r&&"lg:grid-cols-[minmax(260px,0.8fr)_minmax(0,1.2fr)]"),children:[n.jsx("div",{className:"min-h-0 overflow-y-auto px-3 pb-3",children:i.length===0?n.jsx(la,{icon:"inbox",headline:"No threads yet",description:"Send a message to start a conversation thread.",className:"py-6"}):n.jsx("div",{className:"space-y-1.5",children:i.map(b=>n.jsxs("button",{type:"button",onClick:_=>T(b.id,_.currentTarget),className:fe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",r===b.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:b.lastSnippet?`"${b.lastSnippet.length>40?b.lastSnippet.slice(0,40)+"...":b.lastSnippet}"`:b.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:b.lastActivityAt,children:Rt(b.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[b.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",b.assigneeName]}),n.jsx("span",{children:b.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:fe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",bi(b.status)),children:na(b.status)})]})]},b.id))})}),n.jsx(bt,{initial:!1,children:r&&n.jsxs(ue.div,{initial:s?!1:{opacity:0,x:12},animate:s?{}:{opacity:1,x:0},exit:s?{}:{opacity:0,x:12},transition:s?void 0:{duration:Wt.durationStandard/1e3,ease:Wt.easingStandard},className:"hidden min-h-0 flex-col overflow-hidden border-l border-white/[0.08] lg:flex",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:N,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(l==null?void 0:l.title)??"Thread"}),n.jsx("span",{className:fe("rounded-full border px-2 py-0.5 text-micro font-semibold",bi((l==null?void 0:l.status)??"message_only")),children:na((l==null?void 0:l.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:c?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):d?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:d}),k&&n.jsx("button",{type:"button",onClick:()=>void g(k),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):a&&a.messages.length>0?n.jsx("div",{className:"space-y-2",children:a.messages.map(b=>n.jsx("article",{className:fe("flex",b.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:fe("max-w-[90%] rounded-xl border px-2.5 py-1.5",b.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":b.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:b.senderName??Pc(b.role)}),n.jsx("time",{dateTime:b.createdAt,children:Rt(b.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:b.body})]})},b.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),a&&a.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[a.launches.length," launch",a.launches.length===1?"":"es"]}),a.launches.slice(0,2).map(b=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:fe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",bi(Oc(b.status))),children:b.status}),n.jsx("span",{children:b.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:b.requestedAt,children:Rt(b.requestedAt)})]},b.id))]})]})})]})]})]})})}function jl(){const e=xs(),{displayedThreads:t,activeThreadId:s,activeThread:i,activeThreadSummary:r,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:u}=go(),{openThreadPanel:p,closeThreadPanel:h,loadThreadDetail:y,applyScopeLink:g,setComposerMode:w,toggleThreadSidebar:N,panelHeadingRef:k}=xo(),T=(i==null?void 0:i.id)??(r==null?void 0:r.id)??null,D=o.useCallback(()=>{N()},[N]);return u?n.jsx(bt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ue.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:D,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(ue.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Wt.durationEntrance/1e3,ease:Wt.easingEntrance},"aria-label":"Thread sidebar","data-testid":"thread-sidebar",className:"fixed inset-y-0 left-0 z-25 flex w-[380px] max-w-[85vw] flex-col border-r border-white/[0.14] bg-[#0A0E16]/95 shadow-[12px_0_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",children:[n.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-white/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:t.length})]}),n.jsx("button",{type:"button",onClick:D,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread sidebar",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:t.length===0?n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:[n.jsx("p",{className:"text-primary",children:"No threads yet."}),n.jsx("p",{className:"mt-0.5",children:"Send a message to start one."}),n.jsx(ue.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:Il,transition:kl,onClick:()=>{D(),w("focused"),requestAnimationFrame(()=>{const b=document.getElementById("chat-dock-input");b instanceof HTMLTextAreaElement&&b.focus()})},className:"mt-2 inline-flex min-h-[34px] items-center rounded-full border border-lime/30 bg-lime/[0.12] px-2.5 text-micro font-semibold text-[#E1FFB2] hover:bg-lime/[0.18]",children:"Start thread"})]}):n.jsx("div",{className:"space-y-1.5",children:t.map((b,_)=>n.jsxs(ue.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:kl,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Il,onClick:H=>void p(b.id,H.currentTarget),className:fe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===b.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:b.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:b.lastActivityAt,children:Rt(b.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:b.lastSnippet??b.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[b.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Gt,{name:b.assigneeName,hint:b.assigneeName,size:"xs"}),n.jsx("span",{children:b.assigneeName})]}),n.jsx("span",{children:b.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:fe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",bi(b.status)),children:na(b.status)})]})]},b.id))})}),n.jsx(bt,{initial:!1,children:s&&n.jsxs(ue.div,{initial:e?!1:{opacity:0,y:12},animate:e?{}:{opacity:1,y:0},exit:e?{}:{opacity:0,y:12},transition:e?void 0:{duration:Wt.durationStandard/1e3,ease:Wt.easingStandard},className:"flex min-h-0 max-h-[50%] flex-col border-t border-white/[0.08]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:k,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(i==null?void 0:i.title)??(r==null?void 0:r.title)??"Thread"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:fe("rounded-full border px-2 py-0.5 text-micro font-semibold",bi((r==null?void 0:r.status)??"message_only")),children:na((r==null?void 0:r.status)??"message_only")}),n.jsx("button",{type:"button",onClick:h,className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-micro text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread detail",children:"×"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:a?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):l?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:l}),T&&n.jsx("button",{type:"button",onClick:()=>void y(T),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):i&&i.messages.length>0?n.jsx("div",{className:"space-y-2",children:i.messages.map(b=>n.jsx("article",{className:fe("flex",b.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:fe("max-w-[90%] rounded-xl border px-2.5 py-1.5",b.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":b.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:b.senderName??Pc(b.role)}),n.jsx("time",{dateTime:b.createdAt,children:Rt(b.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:b.body})]})},b.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),i&&i.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[i.launches.length," launch",i.launches.length===1?"":"es"]}),i.launches.slice(0,2).map(b=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:fe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",bi(Oc(b.status))),children:b.status}),n.jsx("span",{children:b.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:b.requestedAt,children:Rt(b.requestedAt)})]},b.id))]})]})})]},"sidebar-panel")]})}):null}const Eh={type:"spring",stiffness:500,damping:30,mass:.5};function Rh({open:e,agents:t,query:s,activeIndex:i,onSelect:r}){const a=xs(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(u=>{const p=s.toLowerCase();return u.name.toLowerCase().includes(p)||u.handle.toLowerCase().includes(p)||u.domain.toLowerCase().includes(p)||u.role.toLowerCase().includes(p)}):t;if(!e||c.length===0)return null;const d=c.slice(0,6);return n.jsx(bt,{children:n.jsx(ue.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:Eh,className:fe("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref:l,className:"space-y-px",children:d.map((u,p)=>{const h=p===i;return n.jsxs("button",{type:"button",role:"option","aria-selected":h,"data-active":h,onClick:()=>r(u),onMouseDown:y=>y.preventDefault(),className:fe("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",h?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Gt,{name:u.name,hint:u.name,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-caption font-medium",children:u.name}),u.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime","aria-label":"Running"})]}),n.jsx("span",{className:"text-micro text-muted",children:u.domainLabel})]})]},u.id)})})})})}const Lh={type:"spring",stiffness:500,damping:30,mass:.5};function Dh({open:e,initiatives:t,query:s,activeIndex:i,onSelect:r}){const a=xs(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=c.slice(0,6);return n.jsx(bt,{children:n.jsx(ue.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:Lh,className:fe("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref:l,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":i===0,"data-active":i===0,onClick:()=>r(null),onMouseDown:u=>u.preventDefault(),className:fe("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",i===0?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:"Unscoped"}),d.map((u,p)=>{const h=p+1===i;return n.jsx("button",{type:"button",role:"option","aria-selected":h,"data-active":h,onClick:()=>r(u),onMouseDown:y=>y.preventDefault(),className:fe("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",h?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function $h({open:e,mode:t,agents:s,quickAgents:i,query:r,selectedAssigneeId:a,selectedWatcherIds:l,onQueryChange:c,onSelectAssignee:d,onToggleWatcher:u,onClose:p,onSwitchMode:h,anchorRef:y}){const g=xs();return n.jsx(bt,{children:e&&n.jsxs(ue.div,{initial:g?!1:{opacity:0,scale:.95,y:8},animate:g?{}:{opacity:1,scale:1,y:0},exit:g?{}:{opacity:0,scale:.95,y:8},transition:g?void 0:Wt.easingBounce,className:"absolute bottom-[calc(100%+8px)] left-0 z-30 w-[320px] rounded-xl border border-white/[0.14] bg-[#0A0E16]/98 p-2.5 shadow-[0_20px_44px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[n.jsx("div",{className:"absolute -bottom-[6px] left-4 h-0 w-0 border-l-[6px] border-r-[6px] border-t-[6px] border-l-transparent border-r-transparent border-t-white/[0.14]","aria-hidden":!0}),n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsxs("div",{className:"flex gap-1",children:[n.jsx("button",{type:"button",onClick:()=>h("assignee"),className:fe("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>h("watcher"),className:fe("rounded-full px-2 py-0.5 text-micro",t==="watcher"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Watchers"})]}),n.jsx("button",{type:"button",onClick:p,className:"h-7 rounded-full border border-white/[0.12] bg-white/[0.03] px-2 text-micro text-secondary hover:bg-white/[0.08] hover:text-primary",children:"Close"})]}),i.length>0&&t==="assignee"&&n.jsx("div",{className:"mb-2 flex items-center gap-1.5 overflow-x-auto border-b border-white/[0.06] pb-2 scrollbar-none",children:i.map(w=>{const N=a===w.id;return n.jsx("button",{type:"button",onClick:()=>d(w.id),title:w.name,className:fe("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",N?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":N,"aria-label":`Select ${w.name} as assignee`,children:n.jsx(Gt,{name:w.name,hint:w.name,size:"xs"})},w.id)})}),n.jsx("input",{value:r,onChange:w=>c(w.target.value),placeholder:"Search agents...",className:"mb-2 h-9 w-full rounded-lg border border-white/[0.12] bg-black/35 px-2.5 text-caption text-primary outline-none focus:border-lime/35",autoFocus:!0}),n.jsx("div",{className:"max-h-[240px] space-y-1 overflow-y-auto",children:s.map(w=>{const N=a===w.id,k=l.includes(w.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(w.id);return}N||u(w.id)},className:fe("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",N?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":k?"border-teal/30 bg-teal/[0.12] text-teal-100":"border-white/[0.1] bg-white/[0.02] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsxs("span",{className:"inline-flex items-center gap-2",children:[n.jsx(Gt,{name:w.name,hint:w.name,size:"xs"}),n.jsx("span",{children:w.name})]}),n.jsx("span",{className:"text-micro",children:N?"Assignee":k?"Watcher":"Select"})]},w.id)})})]})})}const Al=24,_l=200;function Sl(e){return e?e.startsWith("application/pdf")?"#EF4444":e.startsWith("image/")?"#A78BFA":e.includes("spreadsheet")||e.includes("csv")?"#22C55E":e.includes("presentation")?"#F97316":"#8F9AB7":"#8F9AB7"}function Ph(e,t){var i;if(e!=null&&e.startsWith("application/pdf"))return"PDF";if(e!=null&&e.startsWith("image/"))return"Image";if(e!=null&&e.includes("spreadsheet")||e!=null&&e.includes("csv"))return"Sheet";if(e!=null&&e.includes("presentation"))return"Slides";const s=(i=t.split(".").pop())==null?void 0:i.toUpperCase();return s&&s.length<=5?s:"File"}function Cl({icon:e,className:t}){return e==="anthropic"?n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:t,children:n.jsx("path",{d:"M16.5 2.3L12 21.7l-1.7-6.5L3.8 13l6.5-1.7L12 4.8l1.7 6.5 6.5 1.7-6.5 1.7L12 21.7"})}):e==="openai"?n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"}),n.jsx("line",{x1:"10",y1:"21",x2:"14",y2:"21"})]}):n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})})}const ro="orgx-chat-dock-collapsed";function Oh(){try{return localStorage.getItem(ro)==="1"}catch{return!1}}function qh(){const e=go(),t=xo(),s=xs(),i=o.useRef(null),r=o.useRef(null),[a,l]=o.useState(Oh),c=o.useCallback(()=>{l(X=>{const Te=!X;try{localStorage.setItem(ro,Te?"1":"0")}catch{}return Te})},[]),[d,u]=o.useState(!1),[p,h]=o.useState(!1),y=o.useRef(null),[g,w]=o.useState(!1),[N,k]=o.useState(""),[T,D]=o.useState(0),[b,_]=o.useState(-1),[H,A]=o.useState(!1),[O,se]=o.useState(""),[M,L]=o.useState(0),[ae,be]=o.useState(-1),{composerMode:ie,draft:P,draftAttachments:xe,sending:ne,launching:K,selectedAssigneeId:G,selectedAssignee:le,selectedWatcherIds:Le,selectedInitiative:Me,agentOptions:me,quickAssigneeOptions:Ne,agentPickerMode:E,agentPickerQuery:W,filteredAgentOptions:V,initiativeOptions:Y,canSend:Ie,activeThreadId:De,guidanceStatus:he,inlineMessages:je,displayedThreads:R,launchWarningOpen:Ae,launchWarningAccepted:Se,selectedProvider:Ee,selectedProviderDef:$e}=e,ye=P.trim(),mt=je.length>0;ye.length>0;const Ce=o.useCallback(()=>{const X=i.current;if(!X)return;X.style.height="0";const Te=Math.min(Math.max(X.scrollHeight,Al),_l);X.style.height=`${Te}px`},[]);o.useLayoutEffect(()=>{Ce()},[P,Ce]);const _e=o.useMemo(()=>{if(!g)return me;const X=N.toLowerCase();return X?me.filter(Te=>Te.name.toLowerCase().includes(X)||Te.handle.toLowerCase().includes(X)||Te.domain.toLowerCase().includes(X)||Te.role.toLowerCase().includes(X)):me},[me,g,N]),ee=o.useMemo(()=>{if(!H)return Y;const X=O.toLowerCase();return X?Y.filter(Te=>Te.name.toLowerCase().includes(X)):Y},[Y,H,O]);o.useEffect(()=>{if(y.current&&clearTimeout(y.current),je.length<=2){h(!1);return}return h(!1),y.current=window.setTimeout(()=>{h(!0)},5e3),()=>{y.current&&clearTimeout(y.current)}},[je.length]),o.useEffect(()=>{const X=Te=>{if((Te.metaKey||Te.ctrlKey)&&Te.key==="k"){if(Te.preventDefault(),a){l(!1);try{localStorage.setItem(ro,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var Ze;return(Ze=i.current)==null?void 0:Ze.focus()})}};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,a]);const dt=o.useCallback(()=>{ie==="resting"&&t.setComposerMode("focused")},[ie,t]),yt=o.useCallback(()=>{window.setTimeout(()=>{ye.length===0&&!mt&&!g&&!H&&xe.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),w(!1),A(!1))},100)},[ye,mt,g,H,xe.length,t]),Be=o.useCallback(X=>{const Te=X.target.value,Ze=X.target.selectionStart??Te.length;t.setDraft(Te),(ie==="resting"||ie==="focused")&&t.setComposerMode("composing");const at=Te.slice(0,Ze),pt=at.match(/@(\w*)$/);if(pt){w(!0),k(pt[1]),D(0),_(Ze-pt[0].length),A(!1);return}const ct=at.match(/#(\w*)$/);if(ct){A(!0),se(ct[1]),L(0),be(Ze-ct[0].length),w(!1);return}g&&w(!1),H&&A(!1)},[ie,t,g,H]),te=o.useCallback(X=>{var pt;const Te=P.slice(0,b),Ze=P.slice(((pt=i.current)==null?void 0:pt.selectionStart)??P.length),at=`${Te}@${X.name} ${Ze}`;t.setDraft(at),t.selectAssignee(X.id),w(!1),k(""),requestAnimationFrame(()=>{if(i.current){const ct=Te.length+X.name.length+2;i.current.setSelectionRange(ct,ct),i.current.focus()}})},[P,b,t]),B=o.useCallback(X=>{var at;const Te=P.slice(0,ae),Ze=P.slice(((at=i.current)==null?void 0:at.selectionStart)??P.length);if(X){const pt=`${Te}#${X.name} ${Ze}`;t.setDraft(pt),t.setSelectedInitiativeId(X.id),requestAnimationFrame(()=>{if(i.current){const ct=Te.length+X.name.length+2;i.current.setSelectionRange(ct,ct),i.current.focus()}})}else{const pt=`${Te}${Ze}`;t.setDraft(pt),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{i.current&&(i.current.setSelectionRange(Te.length,Te.length),i.current.focus())})}A(!1),se("")},[P,ae,t]),oe=o.useCallback(X=>{if(g&&_e.length>0){if(X.key==="ArrowDown"){X.preventDefault(),D(Te=>(Te+1)%_e.length);return}if(X.key==="ArrowUp"){X.preventDefault(),D(Te=>(Te-1+_e.length)%_e.length);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),te(_e[T]);return}if(X.key==="Escape"){X.preventDefault(),w(!1);return}}if(H){const Te=ee.length+1;if(X.key==="ArrowDown"){X.preventDefault(),L(Ze=>(Ze+1)%Te);return}if(X.key==="ArrowUp"){X.preventDefault(),L(Ze=>(Ze-1+Te)%Te);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),B(M===0?null:ee[M-1]);return}if(X.key==="Escape"){X.preventDefault(),A(!1);return}}if(X.key==="Enter"&&!X.shiftKey){X.preventDefault(),t.handlePrimaryAction();return}X.key==="Escape"&&(X.preventDefault(),E?t.setAgentPickerMode(null):mt?t.clearInlineMessages():(t.setComposerMode("resting"),X.target.blur()))},[t,E,mt,g,_e,T,te,H,ee,M,B]),pe=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),Pe=ne||K?n.jsx("svg",{className:"h-4 w-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"52",strokeDashoffset:"16",strokeLinecap:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),n.jsx("polyline",{points:"5 12 12 5 19 12"})]}),We=(ie==="reviewing"||mt)&&je.length>0,rt=he==="submitted"||he==="streaming",ge=o.useRef(je.length),[Ve,ce]=o.useState(0);return o.useEffect(()=>{if(!a){ge.current=je.length,ce(0);return}const X=je.length-ge.current;X>0&&ce(X)},[a,je.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(Nl,{open:d,onClose:()=>u(!1)}),n.jsx(jl,{}),n.jsx("div",{className:"sticky bottom-0 z-20 flex justify-end px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:n.jsxs(ue.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var X;return(X=i.current)==null?void 0:X.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:fe("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.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"})}),n.jsx(bt,{children:Ve>0&&n.jsx(ue.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:fe("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:Ve>9?"9+":Ve},"unread")}),De&&Ve===0&&n.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[#0A0E16] bg-lime"})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx(Nl,{open:d,onClose:()=>u(!1)}),n.jsx(jl,{}),n.jsxs("div",{ref:X=>{t.composerShellRef.current=X},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(bt,{children:Ae&&n.jsxs(ue.div,{initial:s?!1:{opacity:0,y:4},animate:s?{}:{opacity:1,y:0},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mb-2 rounded-lg border border-amber-300/35 bg-amber-300/[0.12] px-2.5 py-2 text-caption text-amber-100",children:[n.jsx("p",{children:"Launch includes non-ready attachments. Continue anyway?"}),n.jsxs("label",{className:"mt-1.5 flex items-center gap-2",children:[n.jsx("input",{type:"checkbox",checked:Se,onChange:X=>t.setLaunchWarningAccepted(X.target.checked)}),n.jsx("span",{children:"I understand unresolved attachment extraction may reduce context quality."})]})]},"launch-warning")}),n.jsx("div",{className:"relative",children:n.jsx($h,{open:E!==null,mode:E??"assignee",agents:V,quickAgents:Ne,query:W,selectedAssigneeId:G,selectedWatcherIds:Le,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:r})}),n.jsxs(ue.section,{"data-testid":"chat-dock","data-state":ie,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Wt.durationEntrance/1e3,ease:Wt.easingEntrance},className:fe("group/dock relative rounded-[22px] border border-white/[0.12] bg-[#0A0E16]/80 px-3 py-2.5 backdrop-blur-xl","shadow-[inset_0_1px_0_rgba(255,255,255,0.035),0_14px_34px_rgba(0,0,0,0.36)]","transition-[border-color] duration-200",ie!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:c,className:fe("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:X=>{t.fileInputRef.current=X},type:"file",multiple:!0,className:"hidden",onChange:X=>{t.handleFilesAdded(X.target.files),X.currentTarget.value=""}}),n.jsx(bt,{children:We&&n.jsx(Mh,{messages:je,isStreaming:rt,collapsed:p,onClick:pe})}),n.jsxs("div",{className:"relative",children:[n.jsx(Rh,{open:g,agents:_e,query:N,activeIndex:T,anchorRect:null,onSelect:te,onClose:()=>w(!1)}),n.jsx(Dh,{open:H,initiatives:ee,query:O,activeIndex:M,onSelect:B,onClose:()=>A(!1)})]}),n.jsx(bt,{initial:!1,children:xe.length>0&&n.jsx(ue.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:xe.map(X=>n.jsxs("div",{className:fe("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",X.status==="failed"?"border-rose-400/30 bg-rose-400/[0.08]":"border-white/[0.1] bg-white/[0.04]"),children:[n.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${Sl(X.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Sl(X.mimeType),strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"max-w-[180px] truncate text-caption font-medium text-primary",children:X.name}),n.jsxs("p",{className:"text-micro text-muted",children:[Ph(X.mimeType,X.name),X.sizeBytes?` · ${vh(X.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Te=>Te.filter(Ze=>Ze.id!==X.id)),className:fe("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${X.name}`,children:"×"}),X.status!=="ready"&&X.status!=="failed"&&n.jsx("div",{className:"absolute bottom-0.5 left-3 right-3 h-0.5 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("div",{className:"h-full w-1/2 animate-pulse rounded-full bg-white/[0.2]"})}),X.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(X.id),className:"ml-1 rounded-md border border-rose-300/20 bg-rose-400/[0.12] px-1.5 py-0.5 text-micro text-rose-200 hover:bg-rose-400/[0.2]",children:"Retry"})]},X.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var X;return(X=t.fileInputRef.current)==null?void 0:X.click()},className:fe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(ue.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:fe("mb-0.5 inline-flex h-7 flex-shrink-0 items-center gap-1.5 rounded-full px-2","border text-micro font-medium","transition-all duration-200",Ee==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":Ee==="openai"?"border-emerald-400/30 bg-emerald-400/[0.08] text-emerald-300":"border-white/[0.12] bg-white/[0.04] text-muted"),title:`Provider: ${$e.label}. Click to switch.`,"aria-label":`Current provider: ${$e.label}. Click to cycle.`,children:[n.jsx(Cl,{icon:$e.icon}),n.jsx("span",{children:$e.shortLabel})]}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"chat-dock-input",className:"sr-only",children:"Chat composer"}),n.jsx("textarea",{ref:i,id:"chat-dock-input",value:P,onFocus:dt,onBlur:yt,onChange:Be,onKeyDown:oe,placeholder:"Ask anything",rows:1,className:fe("w-full resize-none border-none bg-transparent py-1 text-[13px] leading-[22px] text-primary","placeholder:text-muted/60 focus:outline-none"),style:{minHeight:Al,maxHeight:_l,overflowY:"auto"},"aria-expanded":ie!=="resting"})]}),R.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:fe("mb-0.5 inline-flex h-7 min-w-[28px] flex-shrink-0 items-center justify-center gap-1 rounded-full px-1.5","text-micro text-muted transition-colors duration-150","hover:bg-white/[0.06] hover:text-secondary"),"aria-label":`${R.length} thread${R.length===1?"":"s"}`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.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"})}),R.length]}),n.jsx(ue.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!Ie,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:fe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",Ie?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:le?`Send to ${le.name} via ${$e.shortLabel}`:`Send via ${$e.shortLabel}`,"aria-label":le?`Send to ${le.name} via ${$e.shortLabel}`:`Send message via ${$e.shortLabel}`,children:Pe})]}),n.jsx(bt,{children:(le||Me)&&ie!=="resting"&&n.jsxs(ue.div,{initial:s?!1:{opacity:0},animate:s?{}:{opacity:1},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mt-1.5 flex items-center gap-2 px-10",children:[le&&n.jsxs("button",{ref:X=>{r.current=X},type:"button",onClick:t.toggleWatcherPicker,className:fe("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-micro","text-[#E1FFB2]/80 transition-colors duration-150 hover:bg-lime/[0.08]"),children:[n.jsx(Gt,{name:le.name,hint:le.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",le.name]}),le.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),Me&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",Me.name]}),Ee!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:$e.accent},children:[n.jsx(Cl,{icon:$e.icon}),$e.shortLabel]})]})})]})]})]})}const Tl={completed:q.lime,needs_attention:q.amber,in_progress:q.teal,blocked:q.red,unknown:"rgba(255,255,255,0.4)"};function Ml({workstreamTitle:e,items:t,firstTimestamp:s,lastTimestamp:i,onExpandItem:r}){const[a,l]=o.useState(!1),c=t.reduce((p,h)=>(p[h.status]=(p[h.status]??0)+1,p),{}),d=new Date(s).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),u=new Date(i).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsxs("button",{type:"button",onClick:()=>l(p=>!p),className:"flex w-full items-start justify-between gap-3 text-left",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-micro",style:{color:q.teal,opacity:.8},children:"∞"}),n.jsxs("p",{className:"text-body font-semibold text-bright",children:["Autopilot ran ",t.length," sessions in “",e,"”"]})]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-caption text-secondary",children:[c.completed&&c.completed>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:q.lime}}),c.completed," completed"]}),c.needs_attention&&c.needs_attention>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:q.amber}}),c.needs_attention," needs attention"]}),c.in_progress&&c.in_progress>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full status-breathe",style:{backgroundColor:q.teal}}),c.in_progress," in progress"]}),c.blocked&&c.blocked>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:q.red}}),c.blocked," blocked"]})]}),n.jsxs("p",{className:"mt-1 text-micro text-muted tabular-nums",children:[d," — ",u]})]}),n.jsx("span",{className:"mt-1.5 text-micro text-muted",children:a?"Hide":"Show details"})]}),n.jsx(bt,{children:a&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:n.jsx("div",{className:"mt-3 space-y-1.5 border-t border-white/[0.06] pt-3",children:t.map((p,h)=>n.jsxs(ue.button,{type:"button",initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:h*.04,duration:.15},onClick:()=>r==null?void 0:r(h),className:"flex w-full items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-left hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:Tl[p.status]??Tl.unknown}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-caption text-primary",children:p.title}),n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Rt(p.timestamp)})]},`burst-${h}`))})})})]})}const qa=50,Fh=50,qi=20,El=3600,Rl=12e3,Bh=o.memo(function({startMs:t,endMs:s,isTerminal:i}){const[r,a]=o.useState(()=>Date.now());o.useEffect(()=>{if(!t||s||i)return;const c=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(c)},[s,i,t]);const l=o.useMemo(()=>{if(!t)return null;const c=s??(i?null:r);if(!c)return null;const d=Math.max(0,c-t);return d<6e4?`${Math.round(d/1e3)}s`:`${Math.floor(d/6e4)}m ${Math.round(d%6e4/1e3)}s`},[s,i,r,t]);return l?n.jsx(n.Fragment,{children:l}):null});function Ar(e,t,s){if(!t)return;const i=e.get(t);if(i){i.push(s);return}e.set(t,[s])}function Uh(e,t){const s=new Set,i=[];for(const r of t){const a=e.get(r);if(a)for(const l of a)s.has(l.item.id)||(s.add(l.item.id),i.push(l))}return i}const _r={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},Ll=["live","24h","7d","all"];function Dl(e){if(e==="custom"||e==="all")return null;const t=Ll.indexOf(e);return t<0?null:Ll[t+1]??null}function $l(e,t){if(e.size!==t.size)return!1;for(const[s,i]of e){const r=t.get(s);if(!r)return!1;for(const a of Object.keys(i))if(i[a]!==r[a])return!1}return!0}function zh(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Pl(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function hs(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Sr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Cr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Fa(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function Ol(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function zt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function yo(e){if(!e)return;let t={...e},s=zt(t.metadata),i=0;for(;s&&i<4;)t={...t,...s},s=zt(s.metadata),i+=1;return t}function lt(e){const t=zt(e==null?void 0:e.metadata);return yo(t)}function Wh(e){const t=yo(e);if(!t)return"";const s=[];for(const[i,r]of Object.entries(t))typeof r=="string"&&(i.toLowerCase().includes("type")||i.toLowerCase().includes("kind")||i.toLowerCase().includes("summary")||i.toLowerCase().includes("message")||i.toLowerCase().includes("artifact")||i.toLowerCase().includes("decision")||i.toLowerCase().includes("run")||i.toLowerCase().includes("title")||i.toLowerCase().includes("task")||i.toLowerCase().includes("workstream")||i.toLowerCase().includes("milestone"))&&s.push(r);return s.join(" ")}function gi(e){if(e.runId)return e.runId;const t=lt(e);if(!t)return null;const s=["runId","run_id","sliceRunId","slice_run_id","sessionId","session_id","agentRunId"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Gs(e){const t=lt(e);if(!t)return{agentId:null,agentName:null};const s=(typeof t.agent_id=="string"&&t.agent_id.trim().length>0?t.agent_id.trim():null)??(typeof t.agentId=="string"&&t.agentId.trim().length>0?t.agentId.trim():null)??(typeof e.agentId=="string"&&e.agentId.trim().length>0?e.agentId.trim():null),i=(typeof t.agent_name=="string"&&t.agent_name.trim().length>0?t.agent_name.trim():null)??(typeof t.agentName=="string"&&t.agentName.trim().length>0?t.agentName.trim():null)??(typeof e.agentName=="string"&&e.agentName.trim().length>0?e.agentName.trim():null);return{agentId:s,agentName:i}}function ql(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Hh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Kh=/^[0-9a-f]{20,}$/i,Bc=/^\d+$/,Uc=/^(user|usr|clerk)_[a-z0-9]+$/i;function yn(e){if(!e)return null;const t=e.trim();return!t||Hh.test(t)||Kh.test(t)||Bc.test(t)||Uc.test(t)?null:t}const Vh=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Gh(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Vh.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Fl(e,t,s){if(!e)return null;let i=null;for(const a of t){const l=yn(ql(e[a]));if(l){i=l;break}}let r=null;for(const a of s){const l=yn(ql(e[a]));if(l){r=l;break}}return!i&&!r?null:{id:i,name:r,label:r??i??"OrgX"}}function Xh(e,t){var s,i;if(!e||!t)return!1;if(e.id&&t.id){const r=e.id.trim().toLowerCase(),a=t.id.trim().toLowerCase();if(r===a){const l=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,c=((i=t.name)==null?void 0:i.trim().toLowerCase())??null;return l&&c&&l!==c?!1:["unknown","system","agent","none","null","undefined"].includes(r)?!!(l&&c&&l===c):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function Bl(e){const t=lt(e),s=Gs(e),i=Qi(e),r=yn(s.agentId),a=yn(s.agentName),l=yn(e.requesterAgentId??null),c=yn(e.requesterAgentName??null),u=(l||c?{id:l,name:c,label:c??l??"OrgX"}:null)??Fl(t,["requested_by_agent_id","requestedByAgentId","requester_agent_id","requesterAgentId","runner_agent_id","runnerAgentId"],["requested_by_agent_name","requestedByAgentName","requester_agent_name","requesterAgentName","requester_name","requesterName","runner_agent_name","runnerAgentName"])??null,p=yn(e.executorAgentId??null),h=yn(e.executorAgentName??null),g=(p||h?{id:p,name:h,label:h??p??"Agent"}:null)??Fl(t,["executed_by_agent_id","executedByAgentId","executor_agent_id","executorAgentId","delegated_to_agent_id","delegatedToAgentId","handoff_to_agent_id","handoffToAgentId","agent_id","agentId"],["executed_by_agent_name","executedByAgentName","executor_agent_name","executorAgentName","delegated_to_agent_name","delegatedToAgentName","handoff_to_agent_name","handoffToAgentName","agent_name","agentName"])??(r||a?{id:r,name:a,label:a??r??"Agent"}:null);return u&&g?Xh(u,g)?{requester:u,executor:g,mode:"single",primaryLabel:g.label,subtitle:g.label}:{requester:u,executor:g,mode:"handoff",primaryLabel:g.label,subtitle:`${u.label} handed off to ${g.label}`}:u&&!g?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested a run`}:!u&&g?{requester:null,executor:g,mode:"single",primaryLabel:g.label,subtitle:g.label}:i.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:yn(e.agentName??null)??yn(e.agentId??null)??"OrgX",subtitle:yn(e.agentName??null)??yn(e.agentId??null)??"OrgX"}}function Ul(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const Qh=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Yh=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Jh(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=lt(e),i=de(s,["event","event_name","eventName"])??"";return(de(s,["source"])??"")==="user"?"user":Qh.has(i)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Yh.has(i)?"system":"agent"}const Zh={user:q.lime,system:"rgba(255,255,255,0.15)",orchestrator:q.iris,agent:""};function eg(e){switch(e){case"user":return"You";case"system":return"OrgX";case"orchestrator":return"Xandy";case"agent":return""}}function zs(e){const t=lt(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const r of s){const a=t[r];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const i=t.orgx_context;if(i&&typeof i=="object"&&!Array.isArray(i)){const r=i,a=r.workstreamId??r.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Tr(e){const t=lt(e);if(!t)return null;const s=["artifact_id","artifactId","work_artifact_id"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.length>0)return r}return null}const zl=new Map([["autopilot_slice_artifact_buffered","artifact"],["decision_buffered","decision"],["auto_continue_spawn_guard_blocked","decision"],["auto_continue_spawn_guard_rate_limited","decision"],["agent_launch_spawn_guard_blocked","decision"],["agent_launch_spawn_guard_rate_limited","decision"],["agent_restart_spawn_guard_blocked","decision"],["agent_restart_spawn_guard_rate_limited","decision"],["next_up_fallback_spawn_guard_blocked","decision"],["next_up_fallback_spawn_guard_rate_limited","decision"],["autopilot_slice_mcp_handshake_failed","decision"],["autopilot_slice_timeout","decision"],["autopilot_slice_log_stall","decision"],["autopilot_autofix_scheduled","decision"],["autopilot_autofix_executed","message"],["autopilot_autofix_skipped","message"]]);function Mr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function zc(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="boolean")return i;if(typeof i=="string"){const r=i.trim().toLowerCase();if(r==="true")return!0;if(r==="false")return!1}}return null}function Ys(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="number"&&Number.isFinite(i))return Math.max(0,i);if(typeof i=="string"){const r=Number(i);if(Number.isFinite(r))return Math.max(0,r)}}return null}function tg(e){if(!e)return null;const t=e.event;if(typeof t!="string")return null;const s=t.trim().toLowerCase();return s.length>0?s:null}function ng(e){const t=lt(e),s=Mr(e.kind)??Mr(t==null?void 0:t.activity_bucket)??Mr(t==null?void 0:t.activityBucket)??Mr(t==null?void 0:t.bucket);if(s)return s;if(e.type==="artifact_created")return"artifact";if(e.type==="decision_requested"||e.type==="decision_resolved")return"decision";const i=tg(t),r=e.decisionRequired===!0||zc(t,["decision_required","decisionRequired"])===!0,a=Ys(t,["artifacts","artifact_count","artifactCount"])??0,l=Ys(t,["decisions","decision_count","decisionCount"])??0,c=Ys(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ys(t,["non_blocking_decisions","nonBlockingDecisions","non_blocking_decision_count","nonBlockingDecisionCount"])??0;if(i==="autopilot_slice_result")return r||c>0?"decision":a>0?"artifact":l>0||d>0?"decision":"message";if(i==="auto_continue_stopped"){const p=$n(de(t,["stop_reason","stopReason"])??"");if(p==="blocked"||p==="error")return"decision"}return i&&zl.has(i)?zl.get(i):typeof(t==null?void 0:t.artifact_id)=="string"||typeof(t==null?void 0:t.artifactId)=="string"||typeof(t==null?void 0:t.work_artifact_id)=="string"||a>0?"artifact":r||l>0||c>0||d>0?"decision":"message"}function sg(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=de(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if(Ji(s))return!0;const i=de(t,["stop_reason","stopReason"]);if($n(i)==="completed")return!0;const r=t?Wc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||zc(t,["decision_required","decisionRequired"])===!0,l=Ys(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0;return r!==null&&r>=100&&!a&&l===0}function Xs(e){return{run_started:"Run started",run_completed:"Run completed",run_failed:"Run failed",artifact_created:"Artifact created",decision_requested:"Decision requested",decision_resolved:"Decision resolved",handoff_requested:"Handoff requested",handoff_claimed:"Handoff claimed",handoff_fulfilled:"Handoff fulfilled",blocker_created:"Blocker created",milestone_completed:"Milestone completed",delegation:"Delegation"}[e]}function ig(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"unknown";const s=new Date(t.getFullYear(),t.getMonth(),t.getDate());return String(s.getTime())}function rg(e){const t=Number(e);if(!Number.isFinite(t))return"Unknown day";const s=new Date(t),i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()),a=new Date(r);return a.setDate(r.getDate()-1),s.getTime()===r.getTime()?"Today":s.getTime()===a.getTime()?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:s.getFullYear()===i.getFullYear()?void 0:"numeric"})}function Ba(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function Ua(e){return e==="completed"?q.lime:e==="needs_input"?q.amber:e==="issue"?q.red:q.teal}function ag(e,t){var s;return t.status==="failed"?{state:"issue",why:t.sentence}:t.status==="needs_attention"?{state:(((s=t.nextAction)==null?void 0:s.toLowerCase())??"").includes("decision")?"needs_input":"issue",why:t.sentence}:t.status==="in_progress"?{state:"in_progress",why:t.sentence}:t.status==="completed"?{state:"completed",why:t.sentence}:e==="artifact"?{state:"completed",why:"Produced an artifact output."}:{state:"update",why:t.sentence}}function Wl(e){let t="Workstream";const s=e.allItems.map(i=>{const r=lt(i.item),a=de(r,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const c=de(r,["task_title","taskTitle","dispatch_task_title"])??Qi(i.item).title;let d="unknown";return i.userState==="completed"?d="completed":i.userState==="needs_input"||i.userState==="issue"?d="needs_attention":i.userState==="in_progress"&&(d="in_progress"),{title:c,status:d,timestamp:i.item.timestamp}});return{workstreamTitle:t,items:s}}function Hl(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function Ms(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);if(Number.isFinite(t))return t}return null}function bn(e){const t=Ms(e);if(t!==null)return Math.max(0,Math.round(t));if(Array.isArray(e))return e.length;if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e,i=Ms(s.count??s.total??s.size);if(i!==null)return Math.max(0,Math.round(i))}return null}function og(e){const t=Ms(e);if(t===null)return null;const s=t>0&&t<=1?t*100:t;return Math.max(0,Math.min(100,Math.round(s)))}function Wc(e,t){for(const s of t){const i=og(e[s]);if(i!==null)return i}return null}function Er(e,t){const s=[],i=new Set,r=a=>{if(typeof a!="string")return;const l=a.trim();!l||i.has(l)||(i.add(l),s.push(l))};for(const a of t){const l=e[a];if(Array.isArray(l)){for(const c of l)r(c);continue}r(l)}return s}function Hc(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Er(e,["blocking_decision_ids","blockingDecisionIds"]),s=Er(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),i=Er(e,["decision_id","decisionId","decision_ids","decisionIds"]),r=new Set([...i,...t,...s]),a=e.decisions_needed??e.decisionsNeeded;if(Array.isArray(a))for(const l of a){if(!l||typeof l!="object"||Array.isArray(l))continue;const c=l,d=Er(c,["id","decision_id","decisionId"]),u=c.blocking!==!1;for(const p of d)r.add(p),u?t.includes(p)||t.push(p):s.includes(p)||s.push(p)}return{decisionIds:Array.from(r),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function Kc(e){if(!e)return null;const t=lt(e);if(!t)return null;const s=typeof t.event=="string"&&t.event.trim().length>0?t.event.trim():null,i=s??"",r=i.startsWith("autopilot_slice")&&!i.includes("artifact")||i.startsWith("autopilot_autofix");if(!s||!r&&s!=="auto_continue_started"&&s!=="auto_continue_stopped"&&s!=="next_up_manual_dispatch_started")return null;const a=Gs(e),l=(typeof t.requested_by_agent_id=="string"&&t.requested_by_agent_id.trim().length>0?t.requested_by_agent_id.trim():null)??(typeof t.requestedByAgentId=="string"&&t.requestedByAgentId.trim().length>0?t.requestedByAgentId.trim():null)??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null)??a.agentId,c=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,p=Array.isArray(u)?u.filter(Se=>typeof Se=="string"&&Se.trim().length>0):[],h=yg(p),y=t.task_ids??t.taskIds,g=Array.isArray(y)?y.filter(Se=>typeof Se=="string"&&Se.trim().length>0):[],w=t.milestone_ids??t.milestoneIds,N=Array.isArray(w)?w.filter(Se=>typeof Se=="string"&&Se.trim().length>0):[],k=de(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),T=de(t,["initiative_title","initiativeTitle"]),D=de(t,["initiative_status","initiativeStatus"]),b=zs(e),_=de(t,["workstream_title","workstreamTitle"]),H=de(t,["workstream_status","workstreamStatus"]),A=de(t,["task_title","taskTitle"]),O=de(t,["milestone_title","milestoneTitle"]),se=de(t,["domain"]),M=de(t,["phase","slice_phase","slicePhase"]),L=de(t,["next_step","nextStep"]),ae=Wc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),be=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,ie=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,P=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,xe=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,ne=typeof t.error=="string"?t.error:null,K=bn(t.artifacts??t.artifact_count??t.artifactCount),G=bn(t.decisions??t.decision_count??t.decisionCount),le=Hc(t),Le=t.decisions_needed??t.decisionsNeeded;let Me=bn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),me=bn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((Me===null||me===null)&&Array.isArray(Le)){let Se=0,Ee=0;for(const $e of Le){if(!$e||typeof $e!="object"||Array.isArray($e))continue;$e.blocking===!1?Ee+=1:Se+=1}Me===null&&(Me=Se),me===null&&(me=Ee)}Me===null&&G!==null&&e.decisionRequired===!0&&(Me=G>0?G:1),me===null&&G!==null&&Me!==null&&(me=Math.max(0,G-Me)),Me===null&&G!==null&&me!==null&&(Me=Math.max(0,G-me));const Ne=bn(t.status_updates_applied??t.statusUpdatesApplied),E=bn(t.task_updates??t.taskUpdates),W=bn(t.milestone_updates??t.milestoneUpdates),V=Ne??(E!==null||W!==null?(E??0)+(W??0):null),Y=bn(t.status_updates_buffered??t.statusUpdatesBuffered),Ie=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,De=Ms(t.token_budget??t.tokenBudget),he=Ms(t.tokens_used??t.tokensUsed),je=a.agentId??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null),R=a.agentName??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??h,Ae=h&&!a.agentName?null:je;return{event:s,agentId:Ae,agentName:R,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:k,domain:se,phase:M,progressPct:ae,nextStep:L,requiredSkills:p,initiativeStatus:D,initiativeTitle:T,workstreamId:b,workstreamStatus:H,workstreamTitle:_,taskTitle:A,milestoneTitle:O,taskIds:g,milestoneIds:N,parsedStatus:be,hasOutput:ie,artifacts:K,decisions:G,blockingDecisions:Me,nonBlockingDecisions:me,decisionIds:le.decisionIds,blockingDecisionIds:le.blockingDecisionIds,nonBlockingDecisionIds:le.nonBlockingDecisionIds,statusUpdatesApplied:V,statusUpdatesBuffered:Y,stopReason:Ie,tokenBudget:De,tokensUsed:he,logPath:P,outputPath:xe,error:ne}}function Hr(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function lg(e){const t=yo(e);if(!t)return null;const s=t,i=s.orgx_provenance,r=i&&typeof i=="object"&&!Array.isArray(i)?i:null,a=r!=null&&r.skill_pack&&typeof r.skill_pack=="object"&&!Array.isArray(r.skill_pack)?r.skill_pack:null,l=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(r==null?void 0:r.plugin_version)=="string"?r.plugin_version:null),c=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),p=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),h=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,y=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,g=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,w=typeof s.provider=="string"?s.provider:null,N=typeof s.model=="string"?s.model:null,k=typeof s.domain=="string"?s.domain:null,T=s.required_skills??s.requiredSkills,D=Array.isArray(T)?T.filter(_=>typeof _=="string"&&_.trim().length>0):[];return!!l||!!(c||d||u)||!!h||!!(g||w||N||k)||D.length>0?{pluginVersion:l,skillPack:c||d||u||p?{name:c,version:d,checksum:u,source:p}:null,kickoffContextHash:h,kickoffContextSource:y,modelTier:g,provider:w,model:N,domain:k,requiredSkills:D}:null}function Vc(e){if(!e)return null;const t=lt(e);if(!t||typeof t!="object")return null;const s=["artifact","artifacts","output","outputs","result","results","payload","toolOutput","toolOutputs","toolResult","toolResults"];for(const i of s){const r=t[i];if(r!=null)return{source:i,value:r}}return e.type==="artifact_created"?{source:"metadata",value:t}:null}function sa(e){if(!e)return"Artifact";const t=e.toLowerCase();return t.includes("pull_request")||t.includes("pr")?"Pull Request":t.includes("document")||t.includes("doc")||t.includes("spec")?"Document":t.includes("code")||t.includes("implementation")?"Code":t.includes("test")?"Tests":t.includes("design")?"Design":t.includes("config")?"Config":t.includes("decision")?"Decision":Xe(e)}function cg(e){var p;const t=lt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),i=Vc(e);if(!i&&!s)return null;const r=de(t,["artifact_type","artifactType","atomic_unit_type"]),a=de(t,["artifact_title","title","name"]),l=de(t,["url","pr_url","commit_url"]),c=sa(r);let d=c;r||(e.type==="artifact_created"?d="Created artifact":(i==null?void 0:i.source)==="toolOutput"||(i==null?void 0:i.source)==="toolOutputs"?d="Tool output":(i==null?void 0:i.source)==="toolResult"||(i==null?void 0:i.source)==="toolResults"?d="Result":(i==null?void 0:i.source)==="output"||(i==null?void 0:i.source)==="outputs"?d="Output":s?d="Registered artifact":d="Artifact");let u="";if(a)u=a;else if(i){const h=i.value;if(typeof h=="string")u=h.length>80?h.slice(0,80)+"…":h;else if(Array.isArray(h))u=`${h.length} item${h.length===1?"":"s"}`;else if(h&&typeof h=="object"){const y=Zc(h);y!=null&&y.summary?u=y.summary:(p=y==null?void 0:y.artifactsCreated[0])!=null&&p.title?u=y.artifactsCreated[0].title:y!=null&&y.updatesApplied[0]?u=y.updatesApplied[0]:u="Structured artifact details attached"}}return{label:d,preview:u,hasRegisteredId:s,title:a,typeBadge:c,url:l}}function dg(e){const t=lt(e);if(!t)return[];const s=[],i=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,r=de(t,["pr_url"])??(i?de(i,["pr_url"]):null),a=de(t,["pr_number"])??(i?de(i,["pr_number"]):null);(a||r)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:r});const l=de(t,["commit_sha"])??(i?de(i,["commit_sha"]):null),c=de(t,["commit_url"])??(i?de(i,["commit_url"]):null);(l||c)&&s.push({kind:"commit",label:l?l.slice(0,7):"linked",url:c});const d=i==null?void 0:i.tests;if(d&&typeof d=="object"){const h=d,y=typeof h.passed=="number"?h.passed:null,g=typeof h.failed=="number"?h.failed:null;if(y!==null||g!==null){const w=[];y!==null&&w.push(`${y} passed`),g!==null&&g>0&&w.push(`${g} failed`),s.push({kind:"test",label:w.join(", ")})}}const u=typeof t.task_updates=="number"?t.task_updates:i&&typeof i.task_updates=="number"?i.task_updates:null;u&&u>0&&s.push({kind:"artifact",label:`${u} task${u===1?"":"s"} updated`});const p=Array.isArray(t.artifacts)?t.artifacts:null;if(p&&p.length>0&&s.length<2){const h=p[0],y=h&&typeof h=="object"&&typeof h.title=="string"?h.title:null;s.push({kind:"doc",label:y??`${p.length} artifact${p.length===1?"":"s"}`})}return s}function ca(e){if(!e)return[];const t=zt(e.result),s=[e,t].filter(l=>!!l),i=[],r=new Set,a=(l,c)=>{if(Array.isArray(c))for(const d of c){const u=zt(d);if(!u)continue;const p=l==="Task"?["task_id","taskId","id"]:["milestone_id","milestoneId","id"],h=l==="Task"?["task_title","taskTitle","title","name"]:["milestone_title","milestoneTitle","title","name"],y=de(u,p),g=de(u,h)??(y&&!Wn(y)?y:null)??l,w=_s(g,y)??Xe(g),N=de(u,["status","state"]),k=qt(de(u,["reason","summary","description","note"])),T=`${l}|${w.toLowerCase()}|${(N??"").toLowerCase()}|${(k??"").toLowerCase()}`;r.has(T)||(r.add(T),i.push({scope:l,label:w,status:N?Xe(N):null,reason:k}))}};for(const l of s)a("Task",l.task_updates??l.taskUpdates),a("Milestone",l.milestone_updates??l.milestoneUpdates);return i}function ug(e){var c;const t=lt(e);if(!t)return null;const s=((c=de(t,["event","event_name","eventName"]))==null?void 0:c.toLowerCase())??"",i=ca(t),r=bn(t.status_updates_applied??t.statusUpdatesApplied),a=t.status_updates_buffered??t.statusUpdatesBuffered;if(s.includes("status_updates_buffered")||a===!0||typeof a=="number"&&a>0||typeof a=="string"&&["true","1","yes"].includes(a.trim().toLowerCase())){if(i.length>0){const d=i[0];return`Updates being applied: ${i.length} queued update${i.length===1?"":"s"} · ${d.label}${d.status?` → ${d.status}`:""}`}return r!==null&&r>0?`Updates being applied: ${r} status update${r===1?"":"s"} queued for sync`:"Updates being applied: status updates queued for sync"}return r!==null&&r>0?`Applied ${r} status update${r===1?"":"s"}`:null}function mg(e){if(!e)return!1;const t=lt(e);if(!t)return!1;const s=zt(t.outcomes),i=zt(s==null?void 0:s.tests),r=ca(t),a=bn(t.status_updates_applied??t.statusUpdatesApplied),l=t.status_updates_buffered??t.statusUpdatesBuffered,c=l===!0||typeof l=="number"&&l>0||typeof l=="string"&&["true","1","yes"].includes(l.trim().toLowerCase());return!!(s!=null&&s.pr_url||s!=null&&s.pr_number||s!=null&&s.commit_sha||s!=null&&s.commit_url||i||s!=null&&s.artifacts)||r.length>0||(a??0)>0||c}function Gc(e){const t=e.trim();return!t||/^[a-z]+:\/\//i.test(t)||/^data:/i.test(t)?!1:t.startsWith("/")||t.startsWith("~/")||/^[A-Za-z]:[\\/]/.test(t)||/^[.]{1,2}\//.test(t)?!0:t.includes("/")&&!/\s{2,}/.test(t)}function Xc(e){const t=lt(e);if(!t)return[];const s=[],i=new Set,r=(l,c)=>{if(typeof c!="string")return;const d=c.trim();if(!d||!Gc(d))return;const u=`${l}:${d}`;i.has(u)||(i.add(u),s.push({key:l,path:d}))},a=(l,c="",d=0)=>{if(!(d>2))for(const[u,p]of Object.entries(l)){const h=c?`${c}.${u}`:u,y=u.toLowerCase();if(y.includes("path")||y==="url"||y==="uri"||y.endsWith("url")||y.endsWith("_file")||y.endsWith("file")||y.includes("artifact"))if(Array.isArray(p))for(const w of p)r(h,w);else r(h,p);p&&typeof p=="object"&&!Array.isArray(p)&&a(p,h,d+1)}};return a(t),s}function de(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}const pg=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,fg=/\b[0-9a-f]{20,}\b/gi;function Qc(e){let t=e.replace(pg,"").replace(fg,"").replace(/\[workstream\b[^\]]*\]/gi,"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s{2,}/g," ").trim();return t=t.replace(/(?:\s*(?:>|\/)\s*){2,}/g," > ").replace(/^\s*(?:>|\/)\s*/g,"").replace(/\s*(?:>|\/)\s*$/g,"").replace(/\s{2,}/g," ").trim(),t}function hg(e){return e.replace(/\bfor\s+slice\b/gi,"").replace(/\bfor\s+run\b/gi,"").replace(/\bwith\s+slice\b/gi,"").replace(/\s{2,}/g," ").replace(/\s*(?:-|:|>)\s*$/g,"").trim()}function _s(e,t){if(typeof e!="string")return null;const s=Qc(e.trim());if(!s)return null;const i=typeof t=="string"?t.trim().toLowerCase():"";if(i&&s.toLowerCase()===i||Wn(s))return null;const r=Xe(s).trim();return r.length>0?r:null}function Rr(e){for(const t of e){const s=_s(t.value,t.idHint);if(s)return s}return null}function gg(e){if(!e)return{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null};const t=e.match(/rate limit:\s*(\d+)\s*\/\s*(\d+)\s*domain(?:\s*,\s*(\d+)\s*\/\s*(\d+)\s*total)?/i);return t?{domainCurrent:Number.isFinite(Number(t[1]))?Number(t[1]):null,domainMax:Number.isFinite(Number(t[2]))?Number(t[2]):null,totalCurrent:Number.isFinite(Number(t[3]))?Number(t[3]):null,totalMax:Number.isFinite(Number(t[4]))?Number(t[4]):null}:{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null}}function xg(e,t){if(!e)return null;const s=lt(e);if(!s)return null;const i=de(s,["event","event_name","eventName"]),r=zt(s.spawn_guard),a=zt(r==null?void 0:r.checks),l=zt((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),c=de(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=gg(c),u=Ms(l==null?void 0:l.current)??d.domainCurrent,p=Ms(l==null?void 0:l.max)??d.domainMax,h=d.totalCurrent,y=d.totalMax,g=typeof(l==null?void 0:l.passed)=="boolean"?l.passed:null,w=((i==null?void 0:i.includes("rate_limited"))??!1)||!!(c&&/rate limit/i.test(c))||g===!1;return!((i==null?void 0:i.includes("spawn_guard"))??!1)&&!w&&!r&&!c?null:{event:i,blockedReason:c,domain:de(s,["domain"])??de(r,["domain","task_domain"]),modelTier:de(s,["spawn_guard_model_tier","model_tier"])??de(r,["modelTier","model_tier"]),domainCurrent:u,domainMax:p,totalCurrent:h,totalMax:y,retryAt:de(s,["next_retry_at","nextRetryAt"]),retryInMs:Ms(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:w}}function yg(e){var i;if(e.length!==1)return null;const t=(i=e[0])==null?void 0:i.trim();if(!t)return null;const s={"orgx-marketing-agent":"OrgX Marketing","orgx-engineering-agent":"OrgX Engineering","orgx-design-agent":"OrgX Design","orgx-product-agent":"OrgX Product","orgx-sales-agent":"OrgX Sales","orgx-operations-agent":"OrgX Operations","orgx-orchestrator-agent":"OrgX Orchestrator"};if(s[t])return s[t];if(t.endsWith("-agent")){const r=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return r.length===0?null:`OrgX ${Xe(r)}`}return null}function bg(e){if(!e)return!1;const t=e.trim().toLowerCase();return t.startsWith("orgx ")?t==="orgx engineering"||t==="orgx product"||t==="orgx marketing"||t==="orgx sales"||t==="orgx operations"||t==="orgx design"||t==="orgx orchestrator":!1}function za(e,t,s){const i=typeof e=="string"&&e.trim().length>0?e.trim():null,r=typeof t=="string"&&t.trim().length>0?t.trim():null,a=r?(s==null?void 0:s.get(r))??null:null,l=i&&a&&bg(i)?a:i??a;if(l)return ya(l);if(!r)return"OrgX";const c=r.toLowerCase();return c==="main"||c==="system"||c==="unknown"||c==="runtime"||c==="orgx"||c==="openclaw"||c==="null"||c==="undefined"?ya(r):Ui.test(r)||vg.test(r)||Bc.test(r)||Uc.test(r)?"OrgX":ya(r)}const Ui=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vg=/^[0-9a-f]{20,}$/i,wg=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function ia(e){const t=new Set;if(!e)return t;for(const a of[e.title,e.summary,e.description])if(typeof a=="string")for(const l of a.match(wg)??[]){const c=l.trim().toLowerCase();Ui.test(c)&&t.add(c)}typeof e.runId=="string"&&Ui.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=lt(e);if(!s)return t;const i=["run_id","runId","last_run_id","lastRunId","active_run_id","activeRunId","slice_id","sliceId","worker_run_id","workerRunId","correlation_id","correlationId","initiative_id","initiativeId","workstream_id","workstreamId","task_id","taskId","milestone_id","milestoneId","decision_id","decisionId","outbox_event_id","outboxEventId"],r=["task_ids","taskIds","milestone_ids","milestoneIds","decision_ids","decisionIds","blocking_decision_ids","blockingDecisionIds","non_blocking_decision_ids","nonBlockingDecisionIds","allowed_workstream_ids","allowedWorkstreamIds"];for(const a of i){const l=s[a];if(typeof l=="string"){const c=l.trim().toLowerCase();Ui.test(c)&&t.add(c)}}for(const a of r){const l=s[a];if(Array.isArray(l))for(const c of l){if(typeof c!="string")continue;const d=c.trim().toLowerCase();Ui.test(d)&&t.add(d)}}return t}function kg(e){if(!e)return[];const t=lt(e);return Hc(t).decisionIds}function Ig(e,t,s){if(!e)return[];const i=lt(e),r=de(i,["workstream_id","workstreamId"]),a=de(i,["initiative_id","initiativeId"]),l=ia(e);if(!r&&!a&&l.size===0)return[];const c=hs(e.timestamp),d=[];for(const y of t){if(y.id===e.id)continue;const g=lt(y);if(!g)continue;const w=de(g,["workstream_id","workstreamId"]),N=de(g,["initiative_id","initiativeId"]),k=ia(y),T=l.size>0&&Array.from(l).some(O=>k.has(O)),D=!!r&&!!w&&r===w;if(!T&&!D&&!(!!a&&!!N&&a===N))continue;const _=Xc(y).filter(O=>!s.has(O.path));if(_.length===0)continue;const H=Math.abs(hs(y.timestamp)-c);if(!T&&H>7200*1e3)continue;const A=T?0:D?1:2;!T&&H>1200*1e3||d.push({priority:A,delta:H,evidence:_})}if(d.length===0)return[];d.sort((y,g)=>y.priority!==g.priority?y.priority-g.priority:y.delta-g.delta);const u=[],p=new Set(s),h=d[0].priority;for(const y of d){if(y.priority!==h)break;for(const g of y.evidence)if(!p.has(g.path)&&(p.add(g.path),u.push({key:`related.${g.key}`,path:g.path}),u.length>=8))return u}return u}function Ng(e,t){if(!e)return null;const s=lt(e),i=de(s,["workstream_id","workstreamId"]),r=de(s,["initiative_id","initiativeId"]),a=ia(e);if(!i&&!r&&a.size===0)return null;const l=hs(e.timestamp),c=[];for(const u of t){if(u.id===e.id)continue;const p=Kc(u);if(!p)continue;const h=lt(u);if(!h)continue;const y=de(h,["workstream_id","workstreamId"]),g=de(h,["initiative_id","initiativeId"]),w=ia(u),N=a.size>0&&Array.from(a).some(H=>w.has(H)),k=!!i&&!!y&&i===y;if(!N&&!k&&!(!!r&&!!g&&r===g))continue;const D=Math.abs(hs(u.timestamp)-l);if(!N&&D>1200*1e3)continue;const b=N?"shared_id":k?"workstream":"initiative",_=b==="shared_id"?0:b==="workstream"?1:2;c.push({priority:_,delta:D,relation:b,detail:p})}if(c.length===0)return null;c.sort((u,p)=>u.priority!==p.priority?u.priority-p.priority:u.delta-p.delta);const d=c[0];return{detail:d.detail,relation:d.relation}}function $n(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function Ji(e){const t=$n(e);return["done","complete","completed","stopped","success"].includes(t)}function jg(e){const t=$n(e.parsedStatus),s=$n(e.event);return t==="failed"||t==="error"||t==="timed_out"||t==="timeout"||t==="aborted"||s.includes("error")||s.includes("timeout")?"critical":t==="blocked"||e.stopReason==="blocked"?"warning":Ji(t)||e.stopReason==="completed"?"positive":"neutral"}function Ag(e){if(Ji(e.parsedStatus)||e.stopReason==="completed")return 100;const t=$n(e.parsedStatus);if(t==="blocked"||t==="error"||t==="failed")return 100;const s=e.event;return s==="auto_continue_started"?3:s==="next_up_manual_dispatch_started"?8:s==="autopilot_slice_dispatched"?14:s==="autopilot_slice_status_updates_buffered"?72:s==="autopilot_slice_result"?92:s==="autopilot_autofix_scheduled"?6:s==="autopilot_autofix_executed"?18:s==="autopilot_autofix_skipped"||s==="auto_continue_stopped"?100:s.startsWith("autopilot_slice")?56:null}function Yc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function _g(e,t){if(!e&&t===null)return null;const s=e?jg(e):"neutral",i=c=>c>=100&&(s==="warning"||s==="critical"),r="Reached a terminal blocked state. Resolve blockers to continue.";if((e==null?void 0:e.progressPct)!==null&&(e==null?void 0:e.progressPct)!==void 0){const c=Yc(e.progressPct)??0,d=i(c);return{pct:c,source:"metadata",label:d?r:"Progress",tone:s,terminalStop:d}}if(t!==null){const c=i(t);return{pct:t,source:"session",label:c?r:"Progress",tone:s,terminalStop:c}}if(!e)return null;const a=Ag(e);if(a===null)return null;const l=i(a);return{pct:a,source:"lifecycle",label:l?r:"Progress",tone:s,terminalStop:l}}function Sg(e,t,s,i=null){var T;const r=lt(e),a=$n(de(r,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),l=$n(e.state??e.phase??e.kind??e.type),c=$n((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??l),d=$n((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=de(r,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,p=Math.max(0,(s==null?void 0:s.decisions)??(t==null?void 0:t.decisions)??0),h=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,p):0)),y=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,p-h)),g=e.decisionRequired===!0||e.type==="decision_requested"||h>0||c==="needs_decision"&&y===0,w=e.type==="run_completed"||e.type==="milestone_completed"||Ji(c)||d==="completed",N=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),k=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:qt(e.title)??"Autopilot is active and will continue dispatching work from the Next Up queue.",hint:"Watch Activity and Next Up for newly dispatched slices.",tone:"positive"};if(a==="auto_continue_stopped"){if(d==="budget_exhausted")return{label:"Paused",summary:"Paused — budget reached",hint:"Restart with a larger token budget or a narrower workstream scope.",tone:"warning"};if(d==="completed"){const D=typeof(r==null?void 0:r.tasks_completed)=="number"?r.tasks_completed:null;return{label:"All done",summary:D?`All queued work complete — ${D} task${D===1?"":"s"} finished`:"All queued work complete",hint:null,tone:"positive"}}if(d==="stopped")return{label:"Stopped",summary:qt(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:g?"Needs decision":"Blocked",summary:qt(e.title)??(g?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:g?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:g?"warning":"critical"};if(d==="error")return{label:"Error",summary:qt(e.title)??u??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const D=String((r==null?void 0:r.new_state)??"");return D==="running"?{label:"Resumed",summary:"Resumed — dispatching work",hint:"Autopilot is actively working through the queue.",tone:"positive"}:D==="blocked"||D==="error"?{label:"Paused",summary:"Paused — waiting for input",hint:"Review blockers and resolve to continue.",tone:"critical"}:null}if(N)return{label:"Rate limited",summary:"Rate limit reached — will retry in ~2 minutes",hint:"Adjust limits in settings or wait for the window to reset.",tone:"warning"};if(k)return{label:"Waiting on system",summary:u?qt(u)??"Waiting for system capacity.":"Waiting for system capacity.",hint:"Capacity will become available automatically, or adjust limits in settings.",tone:"critical"};if(i){if(i.status==="completed")return{label:y>0?"Completed + follow-up":"Completed",summary:y>0?`Execution completed. ${y} non-blocking decision${y===1?"":"s"} were logged for optional follow-up.`:i.sentence,hint:i.nextAction,tone:"positive"};if(i.status==="failed")return{label:"Failed",summary:u?qt(u)??i.sentence:i.sentence,hint:i.nextAction,tone:"critical"};if(i.status==="needs_attention"){const D=g||(((T=i.nextAction)==null?void 0:T.toLowerCase().includes("decision"))??!1);return{label:D?"Needs decision":"Needs attention",summary:i.sentence,hint:i.nextAction??(D?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:D?"warning":"critical"}}if(i.status==="in_progress")return{label:"In progress",summary:i.sentence,hint:null,tone:"neutral"}}return e.type==="run_failed"||e.type==="blocker_created"||c==="blocked"||c==="failed"||c==="error"||d==="blocked"||d==="error"?{label:g?"Waiting on you":"Blocked",summary:u?qt(u)??"Execution is blocked.":g?"Blocked waiting on decision from you":"Paused after top queue item blocked",hint:g?"Resolve the pending decision in the Decisions panel to continue.":"Review blocker details, then retry or skip to continue.",tone:"critical"}:g?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:w&&y>0?{label:"Completed + follow-up",summary:`Execution completed. ${y} non-blocking decision${y===1?"":"s"} were logged for optional follow-up.`,hint:"Review the decision for optimization, but no approval is required to mark this slice complete.",tone:"positive"}:e.type==="decision_resolved"?{label:"Decision resolved",summary:"A pending decision was completed.",hint:null,tone:"positive"}:w?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||l==="running"||l==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function Jc(e){if(typeof e=="string")return n.jsx(Wi,{mode:"block",text:e,className:"text-body leading-relaxed text-primary"});if(typeof e=="number"||typeof e=="boolean")return n.jsx("p",{className:"text-body text-primary",children:String(e)});if(Array.isArray(e))return n.jsx("div",{className:"space-y-1.5",children:e.map((t,s)=>n.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:Jc(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Tg(e);if(t)return t;const s=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:s.map(([i,r])=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("dt",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:Xe(i)}),n.jsx("dd",{className:"mt-1 text-body text-primary",children:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`${r.length} item${r.length===1?"":"s"}`:r&&typeof r=="object"?`${Object.keys(r).length} field${Object.keys(r).length===1?"":"s"}`:"—"})]},i))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function Cg(e){if(!e)return null;const t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^file:\/\//i.test(t)||!Gc(t)?null:Hr(t):null}function Zc(e){const t=zt(e);if(!t)return null;const s=zt(t.result),i=zt(t.outcomes),r=[s,i,t].filter(M=>!!M),a=M=>{for(const L of r)for(const ae of M){if(!(ae in L))continue;const be=L[ae];if(be!=null)return be}return null},l=M=>{for(const L of r){const ae=de(L,M);if(ae)return ae}return null},c=qt(l(["summary","user_summary","description","message"])),d=[],u=new Set,p=M=>{if(!M)return;const L=M.trim();if(!L)return;const ae=L.toLowerCase();u.has(ae)||(u.add(ae),d.push(L))},h=(M,L)=>{if(Array.isArray(M))for(const ae of M){const be=zt(ae);if(!be)continue;const ie=de(be,[`${L.toLowerCase()}_id`,`${L.toLowerCase()}Id`,"id"]),P=de(be,[`${L.toLowerCase()}_title`,`${L.toLowerCase()}Title`,"title","name"])??(ie&&!Wn(ie)?ie:null),xe=de(be,["status","state"]),ne=qt(de(be,["reason","summary","description","note"])),K=P?_s(P,ie)??Xe(P):L,G=xe?Xe(xe):null,le=[K];G&&le.push(`→ ${G}`),ne&&le.push(`· ${ne}`),p(le.join(" "))}};for(const M of r)h(M.task_updates??M.taskUpdates,"Task"),h(M.milestone_updates??M.milestoneUpdates,"Milestone");const y=bn(a(["status_updates_applied","statusUpdatesApplied"]));y!==null&&y>0&&p(`${y} status update${y===1?"":"s"} applied`);const g=a(["status_updates_buffered","statusUpdatesBuffered"]),w=bn(g);(g===!0||w!==null&&w>0)&&p("Status updates buffered for sync");const k=[],T=new Set,D=M=>{const L=qt(M);if(!L)return;const ae=L.toLowerCase();T.has(ae)||(T.add(ae),k.push(L))};D(l(["next_step","nextStep"]));for(const M of r){const L=M.next_actions??M.nextActions;if(Array.isArray(L))for(const ae of L)typeof ae=="string"&&D(ae)}const b=[],_=new Set,H=(M,L,ae)=>{const be=`${M.toLowerCase()}|${(L??"").toLowerCase()}|${ae??""}`;_.has(be)||(_.add(be),b.push({title:M,type:L,url:ae}))},A=M=>{const L=Array.isArray(M)?M:M?[M]:[];for(const ae of L){const be=zt(ae);if(!be){if(typeof ae=="string"&&ae.trim().length>0){const ne=qt(ae)??Xe(ae);ne&&H(ne,null,null)}continue}const ie=de(be,["artifact_type","artifactType","type"]),P=de(be,["url","source_pointer","sourcePointer","path"]),xe=de(be,["name","title","artifact_title","artifactTitle"])??(P?zn(P):sa(ie));H(Xe(xe),ie,P)}};for(const M of r)A(M.artifacts??M.artifact);const O=l(["artifact_type","artifactType"]),se=l(["url","artifact_url","artifactUrl"]);if(b.length===0&&(O||se)){const M=se?zn(se):sa(O);H(Xe(M),O,se)}return!c&&d.length===0&&b.length===0&&k.length===0?null:{summary:c,updatesApplied:d,artifactsCreated:b,nextUp:k}}function Tg(e){const t=Zc(e);return t?n.jsxs("div",{className:"space-y-3",children:[t.summary&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"What Changed"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-primary",children:t.summary})]}),t.updatesApplied.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Updates Applied"}),n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:t.updatesApplied.slice(0,6).map(s=>n.jsxs("li",{className:"flex items-start gap-2 text-caption text-primary",children:[n.jsx("span",{className:"mt-1 h-1.5 w-1.5 rounded-full bg-cyan-300/70"}),n.jsx("span",{className:"leading-relaxed",children:s})]},s))})]}),t.artifactsCreated.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Artifacts Created"}),n.jsx("div",{className:"mt-1.5 space-y-1.5",children:t.artifactsCreated.slice(0,5).map(s=>{const i=Cg(s.url);return n.jsxs("div",{className:"rounded-md border border-white/[0.07] bg-black/20 px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"text-caption font-medium leading-relaxed text-primary",children:s.title}),s.type&&n.jsx("span",{className:"rounded-full border border-cyan-300/30 bg-cyan-300/[0.10] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.06em] text-cyan-100/80",children:sa(s.type)})]}),s.url&&(i?n.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"mt-1 inline-flex items-center gap-1 text-caption text-cyan-200/85 transition-colors hover:text-cyan-100",children:n.jsx("span",{className:"truncate",children:zn(s.url)})}):n.jsx("p",{className:"mt-1 truncate text-micro text-secondary",children:zn(s.url)}))]},`${s.title}|${s.url??""}`)})})]}),t.nextUp.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Next Up"}),n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:t.nextUp.slice(0,4).map(s=>n.jsxs("li",{className:"flex items-start gap-2 text-caption text-primary",children:[n.jsx("span",{className:"mt-1 h-1.5 w-1.5 rounded-full bg-cyan-300/70"}),n.jsx("span",{className:"leading-relaxed",children:s})]},s))})]})]}):null}function qt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=Ki(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:Xe(t)}const Mg=[/^User:\s*System:/i,/Exec failed/i,/SIGKILL/i,/SIGTERM/i,/stack trace/i,/Traceback \(most recent/i,/^\s*\{[\s"]/,/Error: /,/execution policy/i,/outbox replay/i,/changeset replayed/i],Eg=[/^User:\s*Read /i,/Read HEARTBEAT\.md/i,/Follow it strictly/i,/reply HEARTBEAT_OK/i,/Current time:/i,/workspace context/i];function Rg(e){return Mg.some(t=>t.test(e))}function Lg(e){if(!e)return!1;const t=e.trim();return t?Eg.some(s=>s.test(t)):!1}function Lr(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s&&!Lg(s)&&!(s==="System event"||s==="Untitled session"))return s}return null}function ed(e){const t=lt(e);if(!t)return null;const s=de(t,["user_summary","userSummary"]);if(s)return s;const i=de(t,["task_title","taskTitle","dispatch_task_title"])??de(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),r=de(t,["event","event_name","eventName"]),a=de(t,["parsed_status","status"]),l=de(t,["stop_reason","stopReason"]),c=de(t,["artifact_type","artifactType"]),d=de(t,["artifact_title","title","name"]),u=de(t,["agent_name","agentName","requested_by_agent_name"]);switch(r){case"autopilot_slice_dispatched":case"autopilot_slice_started":return`Working on ${i??"queued task"}`;case"autopilot_slice_status_updates_buffered":{const p=ca(t);return p.length>0?`Applying ${p.length} status update${p.length===1?"":"s"}`:"Applying status updates"}case"autopilot_slice_result":case"autopilot_slice_finished":return a==="completed"||a==="success"?i?`Finished ${i}`:"Task completed":a==="blocked"||a==="needs_decision"?i?`Needs help with ${i}`:"Needs your input":i?`Worked on ${i}`:null;case"auto_continue_started":return"Autopilot started";case"auto_continue_stopped":return l==="budget_exhausted"?"Paused — budget reached":l==="completed"?"All queued work complete":l==="blocked"?"Paused — needs your input":l==="error"?"Paused — hit an error":"Autopilot paused";case"autopilot_transition":return null;case"autopilot_item_skipped":return`Skipped ${i??"blocked item"}, continuing`}if(e.type==="run_started")return i?`Started ${i}`:null;if(e.type==="run_completed")return i?`Completed ${i}`:null;if(e.type==="run_failed")return i?`Hit an issue with ${i}`:null;if(e.type==="artifact_created"){const p=c?Xe(c):"artifact";return d?`Created ${p}: ${d}`:`Created ${p}`}if(e.type==="artifact_updated")return d?`Updated ${d}`:"Updated artifact";if(e.type==="delegation"&&u&&i)return`${u} is handling ${i}`;if(r==="decision_needed"||r==="question_asked"||r==="review_item_created"){const p=de(t,["decision_title","decisionTitle","decision_prompt","decisionPrompt","question","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(r==="decision_resolved"){const p=de(t,["decision_title","decisionTitle","title"]);return p?`Decision resolved: ${p}`:"Decision resolved"}return r==="spawn_guard_blocked"||r==="spawn_guard_rate_limited"?"Waiting for capacity":null}function Dg(e,t,s,i){const r=new Set(["header"]);return t&&r.add("artifact"),s&&r.add("outcome"),(e.includes("slice_result")||e.includes("slice_finished")||e.includes("run_completed"))&&(r.add("summary"),r.add("evidence"),r.add("structured_outcomes")),(i||e.includes("status_updates"))&&r.add("structured_outcomes"),(e.includes("blocked")||e.includes("needs_attention")||e.includes("needs_decision")||e.includes("failed"))&&r.add("action_needed"),(e.includes("autopilot")||e.includes("auto_continue"))&&(r.add("session"),r.add("scope")),e.includes("decision")&&r.add("action_needed"),e.includes("artifact")&&(r.add("artifact"),r.add("evidence")),r}function Qi(e){const t=ed(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";if(!Rg(s)){const i=hg(Xe(Qc(s)));if(i&&i!=="Untitled session")return{title:i,isSystem:!1};const r=e.metadata,a=_d(r);return a!=="Activity event"?{title:a,isSystem:!1}:{title:Xe(Xs(e.type)),isSystem:!1}}return/Exec failed|SIGKILL|SIGTERM|Error: /i.test(s)?{title:"Execution failed",isSystem:!0}:/outbox replay|changeset replayed/i.test(s)?{title:"Changes synced",isSystem:!0}:/execution policy/i.test(s)?{title:"System directive",isSystem:!0}:{title:"System event",isSystem:!0}}const $g=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),Pg=new Set(["changeset_replayed","changeset_applied","changeset.replayed","changeset.applied","outbox_replay_applied","outbox_replayed","sync_applied","sync.applied","sentinel_changeset_applied","sentinel_decision_applied","sentinel.changeset.applied","sentinel.decision.applied"]);function Hi(e){const t=lt(e);if(!t)return!1;const s=(typeof t.event=="string"&&t.event.trim().length>0?t.event.trim().toLowerCase():null)??(typeof t.event_name=="string"&&t.event_name.trim().length>0?t.event_name.trim().toLowerCase():null)??(typeof t.eventName=="string"&&t.eventName.trim().length>0?t.eventName.trim().toLowerCase():null),i=(typeof t.source_client=="string"?t.source_client:null)??(typeof t.sourceClient=="string"?t.sourceClient:null),r=(i==null?void 0:i.toLowerCase())??"",a=(typeof e.kind=="string"&&e.kind.trim().length>0?e.kind.trim().toLowerCase():null)??(typeof t.kind=="string"&&t.kind.trim().length>0?t.kind.trim().toLowerCase():null)??(typeof t.event_kind=="string"&&t.event_kind.trim().length>0?t.event_kind.trim().toLowerCase():null)??(typeof t.eventKind=="string"&&t.eventKind.trim().length>0?t.eventKind.trim().toLowerCase():null)??"",l=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),c=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&Pg.has(s)||l||c&&(d||u)||d&&(u||r.includes("outbox")||r.includes("replay"))||r.includes("outbox_replay")&&u)}function Kl(e){var d;if(!e||!Hi(e))return null;const t=lt(e),s=bn((t==null?void 0:t.applied_count)??(t==null?void 0:t.appliedCount)??(t==null?void 0:t.applied)??null),i=(typeof(t==null?void 0:t.idempotency_key)=="string"?t.idempotency_key:null)??(typeof(t==null?void 0:t.idempotencyKey)=="string"?t.idempotencyKey:null),r=((d=i==null?void 0:i.match(/sentinel:([a-z_]+):/i))==null?void 0:d[1])??null,a=de(t,["entity_type","entityType"])??r??(e.type==="milestone_completed"?"milestone":null),l=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",c=a?` for ${Xe(a).toLowerCase()}`:"";return`${l}${c} were synced from local replay.`}function Wa(e){if(!Hi(e))return null;const t=lt(e);if(!t)return null;const s=de(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const i=de(t,["event","event_name","eventName"])??"",r=de(t,["changeset_id","changesetId"])??"",a=de(t,["entity_type","entityType"])??"",l=de(t,["entity_id","entityId"])??"",c=gi(e)??"",d=Qi(e).title.trim().toLowerCase();return`fallback:${i.toLowerCase()}:${r.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function Og(e){if(!e)return null;const t=lt(e);if(!t||typeof t!="object")return null;const s=typeof t.source=="string"?t.source.trim():"",i=typeof t.turnId=="string"?t.turnId.trim():"";if(s!=="local_openclaw"||!i)return null;const r=typeof t.sessionKey=="string"&&t.sessionKey.trim().length>0?t.sessionKey.trim():null;return{turnId:i,sessionKey:r,runId:e.runId??null}}function Vl(e){return e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1")}const qg=[/^Autopilot dispatched slice for\s*/i,/^Orchestrator (selected|dispatched)\s*/i,/^Auto[-_]?continue.*?dispatching\s*/i,/^Slice (started|dispatched) for\s*/i];function Gl(e,t){const s=ed(e);if(s)return s;let r=(qt(t??e.summary)??qt(e.description)??Xe(e.title||Xs(e.type))).replace(/\r\n/g,`
|
|
210
|
+
`).replace(/```[\s\S]*?```/g," ").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*[-*]\s+/gm,"").replace(/\s+/g," ").trim();for(const c of qg)r=r.replace(c,"");r=r.trim();const a=r.split(`
|
|
211
|
+
`).map(c=>Vl(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let l=a[0]??Vl(r);return l.length<24&&a.length>1&&(l=`${l} ${a[1]}`.trim()),l.length>108?`${l.slice(0,107).trimEnd()}…`:l}const Fg=o.memo(function({activity:t,sessions:s,sliceRuns:i=[],initiatives:r=[],timelineNarrative:a=[],selectedRunIds:l,selectedSessionLabel:c=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:p=null,timeFilterId:h="live",onTimeFilterChange:y,customTimeRange:g={startIso:null,endIso:null},onCustomTimeRangeChange:w,hasMore:N=!1,isLoadingMore:k=!1,onLoadMore:T,onClearSelection:D,onClearWorkstreamFilter:b,onClearAgentFilter:_,onFocusRunId:H,onOpenDecision:A,onResolveDecision:O,requestedActivityItemId:se=null,onActivityItemRequestHandled:M,onPlayNextUp:L,onStartAutopilot:ae,onPauseWorkstream:be,onCreateInitiative:ie,onOpenMissionControl:P,onOpenSettings:xe,workspaceId:ne=null,chatSnapshot:K,onRefreshData:G,isLoading:le=!1,onOpenNextUp:Le,devMode:Me=!1,nextUpQueue:me,autopilotState:Ne=null}){var C;const E=xs(),{open:W}=Ec(),V=o.useMemo(()=>{if(!me)return new Map;const m=new Map;for(let x=0;x<me.length;x++){const v=me[x];m.set(v.workstreamId,{rank:x+1,title:v.workstreamTitle,state:v.queueState})}return m},[me]),[Y,Ie]=o.useState("all"),[De,he]=o.useState(!1),[je,R]=o.useState(""),[Ae,Se]=o.useState(new Set),[Ee,$e]=o.useState({}),[ye,mt]=o.useState("oldest"),[Ce,_e]=o.useState(!1),[ee,dt]=o.useState(!1),[yt,Be]=o.useState(qa),[te,B]=o.useState(null),[oe,pe]=o.useState(null),[Pe,We]=o.useState(!1),[rt,ge]=o.useState(1),[Ve,ce]=o.useState("structured"),[X,Te]=o.useState(null),[Ze,at]=o.useState("feed"),[pt,ct]=o.useState(null),[ht,rn]=o.useState(null),[Z,ve]=o.useState(null),[Oe,Ge]=o.useState(null),[Re,He]=o.useState(!1),[Ue,ft]=o.useState(null),[Ht,gt]=o.useState(!1),vt=o.useRef(Date.now()),Tt=o.useRef(null),Ut=o.useRef(null),nt=o.useRef(null),et=o.useRef(null),$t=o.useRef(null),[St,Mt]=o.useState(()=>Sr(g.startIso)),[Ct,Kt]=o.useState(()=>Sr(g.endIso)),[vn,ys]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Kn=o.useMemo(()=>mc(h),[h]),Vn=o.useMemo(()=>Sr(g.startIso),[g.startIso]),Gn=o.useMemo(()=>Sr(g.endIso),[g.endIso]),Xn=o.useMemo(()=>!St||!Ct?!1:Ct.getTime()>=St.getTime(),[Ct,St]),Es=o.useMemo(()=>h!=="custom"?Kn.label:Vn&&Gn?`${Cr(Vn)} - ${Cr(Gn)}`:"Custom range",[Gn,Vn,h,Kn.label]);o.useEffect(()=>{Mt(Vn),Kt(Gn)},[Gn,Vn]),o.useEffect(()=>{if(typeof window>"u")return;const m=()=>ys(window.innerWidth<=640);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),o.useEffect(()=>{const x=()=>{vt.current=Date.now()};window.addEventListener("pointerdown",x),window.addEventListener("keydown",x);const v=setInterval(()=>{Date.now()-vt.current>3e5&>(!0)},3e4);return()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",x),clearInterval(v)}},[]);const wn=o.useMemo(()=>{const m=s.filter(I=>I.status==="completed").length,x=s.filter(I=>I.status==="blocked"||I.status==="failed").length,v=t.filter(I=>{var S;return I.type==="decision_requested"&&((S=I.metadata)==null?void 0:S.status)==="pending"}).length;return{completed:m,blocked:x,decisions:v}},[s,t]),Qt=o.useMemo(()=>{const m=new Map;for(const x of s)m.set(x.runId,x.title),m.set(x.id,x.title);return m},[s]),an=o.useMemo(()=>{const m=new Map;for(const x of s)x.status&&(m.set(x.runId,x.status),m.set(x.id,x.status));return m},[s]),hn=o.useRef(new Map),Rs=o.useMemo(()=>{var x;const m=new Map;for(const v of s){const I={status:v.status??null,phase:v.phase??null,state:v.state??null,blockerCount:Array.isArray(v.blockers)?v.blockers.length:0,blockerReason:v.blockerReason??((x=v.blockerDiagnostics)==null?void 0:x.reason)??null};m.set(v.runId,I),m.set(v.id,I)}return $l(hn.current,m)?hn.current:(hn.current=m,m)},[s]),Qn=o.useRef(new Map),bs=o.useMemo(()=>{const m=new Map;for(const x of i){const v={status:x.status??null,blockingDecisions:Math.max(0,x.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(x.decisionCount??0)-(x.blockingDecisionCount??0)),updatedEpoch:hs(x.updatedAt??x.lastEventAt??x.startedAt??null)},I=[x.runId,x.sliceRunId].filter(S=>typeof S=="string"&&S.trim().length>0).map(S=>S.trim());for(const S of I){const Q=m.get(S);(!Q||v.updatedEpoch>=Q.updatedEpoch)&&m.set(S,v)}}return $l(Qn.current,m)?Qn.current:(Qn.current=m,m)},[i]),ti=o.useMemo(()=>{const m=new Map;for(const x of i){const v={startedAt:x.startedAt??null,completedAt:x.completedAt??null},I=[x.runId,x.sliceRunId].filter(S=>typeof S=="string"&&S.trim().length>0);for(const S of I)m.set(S,v)}return m},[i]),Ls=o.useMemo(()=>{const m=new Map;for(const x of s){const v=Yc(x.progress);v!==null&&(m.set(x.runId,v),m.set(x.id,v))}return m},[s]),Vt=o.useMemo(()=>{const m=new Map;for(const x of s)!x.agentId||!x.agentName||m.set(x.agentId,x.agentName);return m},[s]),Cn=o.useMemo(()=>{const m=new Map;for(const x of s){const v=x.workstreamId??null;m.set(x.runId,v),m.set(x.id,v)}return m},[s]),Yn=o.useMemo(()=>{const m=new Map;for(const x of i){const v=x.workstreamId??null,I=_s(x.workstreamTitle,v);if(!I)continue;const S=[x.runId,x.sliceRunId].filter(Q=>typeof Q=="string"&&Q.trim().length>0).map(Q=>Q.trim());for(const Q of S)m.set(Q,I)}return m},[i]),z=o.useMemo(()=>{const m=new Map;for(const x of r){const v=_s(x.name,x.id);v&&m.set(x.id,v)}return m},[r]),we=o.useMemo(()=>{const m=new Map;for(const x of r)for(const v of x.workstreams??[]){const I=_s(v.name,v.id);I&&m.set(v.id,I)}for(const x of i){const v=x.workstreamId??null;if(!v||m.has(v))continue;const I=_s(x.workstreamTitle,v);I&&m.set(v,I)}return m},[r,i]);o.useMemo(()=>{const m=[...s];return m.sort((x,v)=>{const I=hs(x.updatedAt??x.lastEventAt??x.startedAt??null);return hs(v.updatedAt??v.lastEventAt??v.startedAt??null)-I}),m},[s]);const ke=o.useMemo(()=>t.map(m=>{const x=gi(m),v=ng(m),I=lt(m),S=x?Rs.get(x)??null:null,Q=x?bs.get(x)??null:null,J=sg(m,I),ze=Qf({sessionStatus:J?null:(S==null?void 0:S.status)??(x?an.get(x)??null:null),sessionPhase:J?null:(S==null?void 0:S.phase)??null,sessionState:J?null:(S==null?void 0:S.state)??null,sliceStatus:J?null:(Q==null?void 0:Q.status)??null,activityType:m.type,activityStatus:de(I,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:de(I,["stop_reason","stopReason"]),decisionRequired:m.decisionRequired??!1,blockingDecisionCount:Ys(I,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Q==null?void 0:Q.blockingDecisions)??0,nonBlockingDecisionCount:Ys(I,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Q==null?void 0:Q.nonBlockingDecisions)??0,blockerCount:J?0:(S==null?void 0:S.blockerCount)??0,blockerReason:J?null:(S==null?void 0:S.blockerReason)??null}),qe=ag(v,ze),it=[m.title,m.description,m.summary,m.agentName,Wh(I)].filter(tt=>typeof tt=="string"&&tt.length>0).join(" ").toLowerCase(),Ke=x?(Qt.get(x)??x).toLowerCase():"",Ye=I==null?void 0:I.scope,ot=Ye==="milestone"||Ye==="workstream"?Ye:void 0;return{item:m,bucket:v,userState:qe.state,userStateWhy:qe.why,canonicalProjection:ze,runId:x,timestampEpoch:hs(m.timestamp),searchText:it,runLabelSearch:Ke,scopeGroupId:ot?x??null:null,scope:ot}}),[t,Qt,Rs,an,bs]),Fe=o.useMemo(()=>{const m=[...ke];m.sort((I,S)=>{const Q=S.timestampEpoch-I.timestampEpoch;return Q!==0?Q:S.item.id.localeCompare(I.item.id)});const x=I=>{const S=new Map,Q=new Map,J=new Map,ze=new Map;for(const qe of I){Ar(S,qe.runId,qe),Ar(ze,qe.userState,qe);const it=zs(qe.item)??(qe.runId?Cn.get(qe.runId)??null:null);Ar(Q,it,qe);const Ke=Gs(qe.item).agentName;Ar(J,Ke,qe)}return{all:I,byRunId:S,byWorkstreamId:Q,byAgentName:J,byUserState:ze}},v=[...m].reverse();return{newest:x(m),oldest:x(v)}},[ke,Cn]),wt=o.useMemo(()=>{let m=0;for(const x of ke)m=Math.max(m,x.timestampEpoch);return m<=0?!1:Date.now()-m<6e4},[ke]),jt=o.useMemo(()=>new Set(l.filter(m=>m&&m.trim().length>0)),[l]),st=jt.size>0,Yt=o.useMemo(()=>Vi.filter(m=>["live","24h","7d","all"].includes(m.id)),[]),At=o.useMemo(()=>{if(!st)return null;for(const m of jt){const x=s.find(v=>v.runId===m||v.id===m);if(x)return x}return null},[st,jt,s]),Jn=o.useMemo(()=>st?At!=null&&At.runtimeProvider?{id:zh(At.runtimeProvider)}:Cs(At==null?void 0:At.agentId,At==null?void 0:At.agentName,At==null?void 0:At.title,At==null?void 0:At.lastEventSummary,At==null?void 0:At.runtimeClient,c):Cs(),[At,st,c]),Zn=o.useMemo(()=>p?Cs(p):Cs(),[p]),{filtered:Et,filteredTotal:dn,hiddenCount:as,hiddenSyncCount:es}=o.useMemo(()=>{const m=ye==="newest"?Fe.newest:Fe.oldest,x=[];st&&x.push(Uh(m.byRunId,jt)),d&&x.push(m.byWorkstreamId.get(d)??[]),p&&x.push(m.byAgentName.get(p)??[]),Y==="completed"?x.push(m.byUserState.get("completed")??[]):Y==="in_progress"?x.push(m.byUserState.get("in_progress")??[]):Y==="needs_attention"&&x.push([...m.byUserState.get("needs_input")??[],...m.byUserState.get("issue")??[]]);const v=x.length>0?[...x].sort((ot,tt)=>ot.length-tt.length)[0]:m.all,I=[];let S=0,Q=0,J=0;const ze=new Set,qe=je.trim().toLowerCase();for(const ot of v){const tt=ot.runId;if(st&&(!tt||!jt.has(tt)))continue;if(d){const Rn=zs(ot.item),tn=tt?Cn.get(tt)??null:null;if((Rn??tn)!==d)continue}const Dt=Gs(ot.item);if(p&&Dt.agentName!==p){J++;continue}if(!Me){const Rn=lt(ot.item),tn=de(Rn,["event","event_name","eventName"]);if(tn&&$g.has(tn))continue}const cn=Wa(ot.item);if(cn){if(ze.has(cn)){Q+=1;continue}if(ze.add(cn),!De){Q+=1;continue}}else if(!De&&Hi(ot.item)){Q+=1;continue}Y==="completed"&&ot.userState!=="completed"||Y==="needs_attention"&&ot.userState!=="needs_input"&&ot.userState!=="issue"||Y==="in_progress"&&ot.userState!=="in_progress"||qe.length>0&&!`${ot.searchText} ${ot.runLabelSearch}`.includes(qe)||(I.length<Rl?I.push(ot):S+=1)}const it=Math.min(Math.max(1,Math.min(El,yt)),I.length),Ke=I.slice(0,it),Ye=I.length+S;return{filtered:Ke,filteredTotal:Ye,hiddenCount:Math.max(0,Ye-Ke.length),hiddenSyncCount:Q,skippedByAgent:J}},[Y,p,Fe,st,je,yt,d,jt,Cn,De,ye]),Ds=o.useMemo(()=>{if(!p)return null;let m=0;for(const x of t)if(Gs(x).agentName===p){const I=hs(x.timestamp);I>m&&(m=I)}return m===0?null:Rt(m)},[p,t]),$s=o.useMemo(()=>{const m=new Map;for(const v of Et){const I=ig(v.item.timestamp),S=m.get(I);S?S.push(v):m.set(I,[v])}return Array.from(m.keys()).sort((v,I)=>{const S=Number(I)-Number(v);return ye==="newest"?S:-S}).map(v=>({key:v,label:rg(v),items:m.get(v)??[]}))},[Et,ye]),os=o.useMemo(()=>$s.map(m=>{const x=new Map;for(const v of m.items){const I=Qi(v.item).title.trim().toLowerCase(),S=Wa(v.item),Q=lt(v.item),J=de(Q,["event","event_name","eventName"]),ze=(J==null?void 0:J.startsWith("autopilot_"))||(J==null?void 0:J.startsWith("auto_continue_")),qe=typeof J=="string"&&/(transition|started|stopped|completed|blocked|paused|resumed|failed|decision|dispatch)/i.test(J),it=zs(v.item),Ke=S?`${v.item.type}::sync::${S}`:ze&&it&&!qe?`autopilot::${it}::${Math.floor(v.timestampEpoch/3e5)}`:qe?`autopilot-lifecycle::${v.item.id}`:`${v.item.type}::${I}`,Ye=x.get(Ke);Ye?(Ye.count+=1,Ye.firstTimestamp=Math.min(Ye.firstTimestamp,v.timestampEpoch),Ye.allItems.push(v),v.timestampEpoch>Ye.representative.timestampEpoch&&(Ye.representative=v)):x.set(Ke,{key:Ke,representative:v,count:1,firstTimestamp:v.timestampEpoch,allItems:[v]})}return{...m,clusters:Array.from(x.values())}}),[$s]),kn=o.useCallback(m=>{Se(x=>{const v=new Set(x);return v.has(m)?v.delete(m):v.add(m),v}),$e(x=>{if(Object.prototype.hasOwnProperty.call(x,m)){const v={...x};return delete v[m],v}return{...x,[m]:qi}})},[]),Zi=o.useCallback((m,x)=>{$e(v=>{const I=v[m]??qi,S=Math.min(x,I+qi);return S===I?v:{...v,[m]:S}})},[]),ls=o.useCallback(()=>{!w||!y||!St||!Ct||Ct.getTime()<St.getTime()||(w({startIso:St.toISOString(),endIso:Ct.toISOString()}),y("custom"),dt(!1))},[Ct,St,w,y]),da=o.useCallback(()=>{Mt(null),Kt(null),w==null||w({startIso:null,endIso:null}),h==="custom"&&(y==null||y("live"))},[w,y,h]),Pt=o.useMemo(()=>Math.min(El,Math.min(Rl,dn)),[dn]);o.useEffect(()=>{Be(qa),Se(new Set),$e({})},[Y,p,st,je,d,De,ye,h]),o.useEffect(()=>{if(!Ce)return;const m=v=>{var S;const I=v.target;I instanceof Node&&((S=Tt.current)!=null&&S.contains(I)||_e(!1))},x=v=>{v.key==="Escape"&&_e(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Ce]),o.useEffect(()=>{if(!ee)return;const m=v=>{var S;const I=v.target;I instanceof Node&&((S=Ut.current)!=null&&S.contains(I)||dt(!1))},x=v=>{v.key==="Escape"&&dt(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[ee]);const Pn=o.useRef(T);Pn.current=T;const ni=o.useRef(N);ni.current=N;const Ii=o.useRef(k);Ii.current=k;const[ts,ua]=o.useState(!1),vs=o.useRef(null),on=o.useRef(h),er=o.useRef(Date.now()),Ps=o.useRef(!1);o.useEffect(()=>{on.current!==h&&(on.current=h,vs.current=null,er.current=Date.now(),Ps.current=!1)},[h]),o.useEffect(()=>{const m=nt.current,x=et.current;if(!m||!x)return;const v=new IntersectionObserver(S=>{const Q=S.some(J=>J.isIntersecting);ua(Q)},{root:m,rootMargin:"0px 0px 600px 0px"});v.observe(x);const I=()=>{Ps.current=!0};return m.addEventListener("scroll",I,{passive:!0}),()=>{v.disconnect(),m.removeEventListener("scroll",I)}},[]),o.useEffect(()=>{var m;if(ts){if(Et.length<Pt){Be(x=>Math.min(Pt,Math.max(x,qa)+Fh));return}if(ni.current&&!Ii.current){(m=Pn.current)==null||m.call(Pn);return}}},[Et.length,Pt,ts]),o.useEffect(()=>{if(!ts||N||k||!y)return;const m=nt.current,x=m?m.scrollHeight<=m.clientHeight+4:!1;if(!Ps.current&&!x||Date.now()-er.current<3e3)return;const I=Dl(h);I&&vs.current!==I&&(vs.current=I,y(I))},[Et.length,N,k,y,ts,h]);const un=o.useMemo(()=>te?Et.findIndex(m=>m.item.id===te):-1,[te,Et]),$=un>=0?Et[un]:null,tr=o.useMemo(()=>{var x;const m=new Map;for(const v of a){const I=(x=v==null?void 0:v.sliceRunId)==null?void 0:x.trim();!I||m.has(I)||m.set(I,v)}return m},[a]),cs=o.useMemo(()=>{if(!$)return null;const m=$.runId??gi($.item);return m?tr.get(m)??null:null},[$,tr]),mn=o.useMemo(()=>Vc(($==null?void 0:$.item)??null),[$]),On=o.useMemo(()=>Tr(($==null?void 0:$.item)??null),[$]),Os=o.useMemo(()=>Kc(($==null?void 0:$.item)??null),[$]),ds=o.useMemo(()=>Os?null:Ng(($==null?void 0:$.item)??null,t),[Os,$,t]),Qe=o.useMemo(()=>$?Bl($.item):null,[$]),pn=o.useMemo(()=>Qe?Qe.executor??Qe.requester:null,[Qe]),re=Os??(ds==null?void 0:ds.detail)??null,si=o.useMemo(()=>{var m,x;return za((re==null?void 0:re.requesterAgentName)??((m=Qe==null?void 0:Qe.requester)==null?void 0:m.name)??null,(re==null?void 0:re.requesterAgentId)??((x=Qe==null?void 0:Qe.requester)==null?void 0:x.id)??null,Vt)},[re,Qe,Vt]),ws=o.useMemo(()=>Gh(si),[si]),In=o.useMemo(()=>{var x,v;const m=za((re==null?void 0:re.agentName)??((x=Qe==null?void 0:Qe.executor)==null?void 0:x.name)??null,(re==null?void 0:re.agentId)??((v=Qe==null?void 0:Qe.executor)==null?void 0:v.id)??null,Vt);return m==="—"?(Qe==null?void 0:Qe.primaryLabel)??"Codex":m},[re,Qe,Vt]),Ni=o.useMemo(()=>$!=null&&$.runId?Ls.get($.runId)??null:null,[$,Ls]),Ft=o.useMemo(()=>_g(re,Ni),[re,Ni]),U=o.useMemo(()=>{const m=re;if(!m)return null;const x=m.initiativeId??($==null?void 0:$.item.initiativeId)??null,v=x?r.find(tt=>tt.id===x)??null:null,I=m.initiativeTitle??(v==null?void 0:v.name)??null,S=m.initiativeStatus??(v==null?void 0:v.status)??null,Q=(v==null?void 0:v.workstreams)??[],J=Q.length>0?Q.length:null,ze=J!==null?Q.filter(tt=>Ji(tt.status)).length:null,qe=J&&ze!==null?Math.round(ze/J*100):null,it=m.workstreamId??null,Ke=it&&Q.length>0?Q.find(tt=>tt.id===it)??null:null,Ye=m.workstreamTitle??(Ke==null?void 0:Ke.name)??(it?we.get(it)??null:null),ot=m.workstreamStatus??(Ke==null?void 0:Ke.status)??null;return{initiativeId:x,initiativeTitle:I,initiativeStatus:S,totalInitiativeWorkstreams:J,doneInitiativeWorkstreams:ze,initiativeWorkstreamPct:qe,workstreamId:it,workstreamTitle:Ye,workstreamStatus:ot,taskTitle:m.taskTitle,milestoneTitle:m.milestoneTitle,scopedTaskCount:m.taskIds.length,scopedMilestoneCount:m.milestoneIds.length,statusUpdatesApplied:m.statusUpdatesApplied,statusUpdatesBuffered:m.statusUpdatesBuffered,artifacts:m.artifacts,decisions:m.decisions,blockingDecisions:m.blockingDecisions,nonBlockingDecisions:m.nonBlockingDecisions,tokensUsed:m.tokensUsed,tokenBudget:m.tokenBudget,nextStep:m.nextStep,phase:m.phase,stopReason:m.stopReason,parsedStatus:m.parsedStatus}},[re,$,r,we]),_t=o.useMemo(()=>$?Sg($.item,re,U?{decisions:U.decisions,blockingDecisions:U.blockingDecisions,nonBlockingDecisions:U.nonBlockingDecisions,stopReason:U.stopReason,parsedStatus:U.parsedStatus}:null,$.canonicalProjection??null):null,[re,$,U]),Bt=o.useMemo(()=>{if(!$)return new Set;if(Me)return new Set(["header","artifact","outcome","structured_outcomes","action_needed","session","scope","summary","evidence"]);const m=de(lt($.item),["event","event_name","eventName"])??"";return Dg(m,!!mn||!!Tr($.item),!!_t,mg($.item))},[$,mn,_t,Me]),us=o.useMemo(()=>{if(!U)return[];const m=[];_t&&m.push({label:"Status",value:_t.label}),U.scopedTaskCount>0&&m.push({label:"Tasks",value:U.scopedTaskCount}),U.scopedMilestoneCount>0&&m.push({label:"Milestones",value:U.scopedMilestoneCount});const x=U.artifacts??0;x>0&&m.push({label:"Artifacts",value:x});const v=U.decisions??0;v>0&&m.push({label:"Decisions",value:v}),U.blockingDecisions&&U.blockingDecisions>0&&m.push({label:"Blocking",value:U.blockingDecisions,tone:"critical"}),U.stopReason&&m.push({label:"Stop reason",value:fi(U.stopReason)??Xe(U.stopReason)});const I=Ad(U.tokensUsed,U.tokenBudget);return I&&m.push({label:"Token usage",value:I}),m},[U,_t]),Jt=o.useMemo(()=>{const m=new Set;for(const x of kg(($==null?void 0:$.item)??null))m.add(x);for(const x of(re==null?void 0:re.decisionIds)??[])m.add(x);for(const x of(re==null?void 0:re.blockingDecisionIds)??[])m.add(x);for(const x of(re==null?void 0:re.nonBlockingDecisionIds)??[])m.add(x);return Array.from(m)},[re,$]),nr=o.useMemo(()=>A?Jt.length>0||($==null?void 0:$.item.decisionRequired)===!0||((U==null?void 0:U.blockingDecisions)??0)>0?!0:(_t==null?void 0:_t.label)==="Needs decision":!1,[Jt,$,U,_t,A]),gn=o.useMemo(()=>{if(!$)return null;const m=gi($.item);return m?i.find(x=>x.runId===m||x.sliceRunId===m)??null:null},[$,i]),ma=o.useMemo(()=>(gn==null?void 0:gn.decisionOptions)??[],[gn]),sr=o.useMemo(()=>(gn==null?void 0:gn.pendingDecisions)??[],[gn]),ns=o.useMemo(()=>(gn==null?void 0:gn.blockers)??[],[gn]),ir=o.useMemo(()=>Ft?Ft.tone==="positive"?q.lime:Ft.tone==="warning"?q.amber:Ft.tone==="critical"?q.red:q.teal:q.teal,[Ft]),ms=(Ft==null?void 0:Ft.terminalStop)===!0,ut=o.useMemo(()=>lg(lt(($==null?void 0:$.item)??null)),[$]),qs=o.useMemo(()=>lt(($==null?void 0:$.item)??null),[$]),kt=o.useMemo(()=>xg(($==null?void 0:$.item)??null,re),[re,$]),ks=o.useMemo(()=>{if(!(kt!=null&&kt.retryAt))return null;const m=new Date(kt.retryAt);if(!Number.isFinite(m.getTime()))return null;const x=m.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),v=Rt(kt.retryAt);return v?`${x} (${v})`:x},[kt]),ji=o.useMemo(()=>$?Gs($.item):{agentId:null,agentName:null},[$]),Ai=o.useMemo(()=>Hl(zt($==null?void 0:$.item.metadata)??void 0),[$]),rr=o.useMemo(()=>{var v;if(!$)return[];const m=gi($.item);if(m){const I=i.find(S=>S.runId===m||S.sliceRunId===m);if((v=I==null?void 0:I.scopeProgress)!=null&&v.milestones)return I.scopeProgress.milestones.map(S=>({id:S.id,title:S.title,tasks:[],totalTasks:S.total,doneTasks:S.done}))}const x=de(lt($.item),["workstream_id","workstreamId"]);if(x&&me){const I=me.find(S=>S.workstreamId===x);if(I!=null&&I.milestoneBreakdown)return I.milestoneBreakdown}return[]},[$,i,me]);o.useMemo(()=>Hl(qs),[qs]);const xn=o.useMemo(()=>{const m=Xc(($==null?void 0:$.item)??null);return m.length>0?m:Ig(($==null?void 0:$.item)??null,t,new Set)},[$,t]),Tn=o.useMemo(()=>xn.filter((m,x,v)=>v.findIndex(I=>I.path===m.path)===x),[xn]),pa=o.useMemo(()=>Tn.slice(0,4),[Tn]),ar=o.useMemo(()=>Tn.slice(4),[Tn]),or=o.useMemo(()=>{if(Tn.length===0)return null;const m=Tn[0];return m?Hr(m.path):null},[Tn]),_i=o.useMemo(()=>{var I;const m=qt(X);if(m)return m;const x=Kl(($==null?void 0:$.item)??null);if(x)return x;const v=qt($==null?void 0:$.item.summary)??qt($==null?void 0:$.item.description);if(v)return v;if($){const S=$.item,Q=lt(S),J=de(Q,["agent_name","agentName"])??S.agentName??"OrgX",ze=de(Q,["task_title","taskTitle","workstream_title","workstreamTitle"]),qe=((I=S.type)==null?void 0:I.replace(/_/g," "))??"activity";return ze?`${J} worked on ${ze}`:`${J} recorded a ${qe}`}return null},[X,$]),lr=o.useMemo(()=>$?Hi($.item):!1,[$]),ln=o.useMemo(()=>{if(!re||!$)return null;const m=re.initiativeId??$.item.initiativeId??null,x=re.workstreamId??zs($.item);if(!m||!x)return null;const v=$n((U==null?void 0:U.parsedStatus)??re.parsedStatus),I=$n((U==null?void 0:U.stopReason)??re.stopReason),S=Math.max(0,(U==null?void 0:U.blockingDecisions)??re.blockingDecisions??($.item.decisionRequired?1:0)),Q=Math.max(0,(U==null?void 0:U.nonBlockingDecisions)??re.nonBlockingDecisions??0),J=v==="blocked"||v==="error"||v==="failed"||I==="blocked"||I==="error"||$.item.type==="blocker_created",ze=!J&&S===0&&Q>0&&(v==="needs_decision"||v==="completed"||I==="completed");return!J&&!ze?null:{initiativeId:m,workstreamId:x,runId:$.runId??null,event:re.event,requestedByAgentId:re.requesterAgentId??$.item.requesterAgentId??null,requestedByAgentName:re.requesterAgentName??$.item.requesterAgentName??null,actionLabel:J?"Auto-fix in 10s":"Auto-continue in 10s",helperText:J?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:J}},[re,$,U]),Mn=o.useCallback(()=>{B(null)},[]),ii=o.useCallback(async(m,x)=>{if(x){Ge(null),ve(m);try{await x()}catch(v){Ge(v instanceof Error?v.message:"Action failed")}finally{ve(v=>v===m?null:v)}}},[]),ri=o.useCallback(async()=>{var m;if(!(!ln||Re)){He(!0),ft(null);try{const x=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:ln.initiativeId,workstreamId:ln.workstreamId,runId:ln.runId,event:ln.event,requestedByAgentId:ln.requestedByAgentId,requestedByAgentName:ln.requestedByAgentName,graceMs:1e4})}),v=await x.json().catch(()=>null);if(!x.ok||(v==null?void 0:v.ok)!==!0)throw new Error((v==null?void 0:v.error)||`Request failed (${x.status})`);const I=(m=v==null?void 0:v.scheduled)!=null&&m.dueAt?new Date(v.scheduled.dueAt):null,S=I&&Number.isFinite(I.getTime())?I.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;ft(S?`Scheduled. Auto action starts by ${S} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(x){const v=x instanceof Error?x.message:"Failed to schedule auto-fix";ft(Xt(v)||v)}finally{He(!1)}}},[ln,Re]);o.useEffect(()=>{if(!oe)return;const m=window.setTimeout(()=>pe(null),2e3);return()=>window.clearTimeout(m)},[oe]),o.useEffect(()=>{Ge(null)},[Y,je,h]),o.useEffect(()=>{if(!se){$t.current=null;return}const m=se.trim();!m||$t.current===m||!t.some(v=>v.id===m)||($t.current=m,Ie("all"),R(""),ge(1),B(m),M==null||M(m))},[t,M,se]);const En=o.useCallback(async(m,x)=>{if(x)try{await navigator.clipboard.writeText(x),pe(`${m} copied`)}catch{pe("Copy failed")}},[]);o.useEffect(()=>{ce("structured"),We(!1),He(!1),ft(null)},[te]),o.useEffect(()=>{Te(null),at("feed"),ct(null),rn(null);const m=Og(($==null?void 0:$.item)??null);if(!m||Hn())return;const x=new URLSearchParams({turnId:m.turnId});m.sessionKey&&x.set("sessionKey",m.sessionKey),m.runId&&x.set("run",m.runId);const v=new AbortController;return fetch(`/orgx/api/live/activity/detail?${x.toString()}`,{method:"GET",headers:Ot({workspaceId:ne}),signal:v.signal}).then(async I=>I.ok?await I.json():(I.status===404&&at("missing"),null)).then(I=>{var J;const S=((J=I==null?void 0:I.detail)==null?void 0:J.summary)??null;typeof S=="string"&&S.trim().length>0?(Te(S),at("local")):at("missing");const Q=I==null?void 0:I.headline;typeof Q=="string"&&Q.trim().length>0&&(ct(Q.trim()),rn((I==null?void 0:I.headlineSource)??null))}).catch(I=>{I instanceof DOMException&&I.name==="AbortError"||at("missing")}),()=>v.abort()},[$,ne]);const Is=o.useCallback(m=>{var I;if(Et.length===0)return;const v=((un>=0?un:0)+m+Et.length)%Et.length;ge(m),B(((I=Et[v])==null?void 0:I.item.id)??null)},[un,Et]);o.useEffect(()=>{te&&(un>=0||B(null))},[un,te]),o.useEffect(()=>{if(!te)return;const m=x=>{x.key==="ArrowRight"||x.key.toLowerCase()==="l"?(x.preventDefault(),Is(1)):(x.key==="ArrowLeft"||x.key.toLowerCase()==="h")&&(x.preventDefault(),Is(-1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[te,Is]);const qn=jt.size===1,ai=qn?[...jt][0]:null,cr=ai?s.find(m=>m.runId===ai||m.id===ai)??null:null,f=o.useMemo(()=>{if(!qn)return[];const m=[],x=new Set;for(const v of ke){if(!v.runId||!jt.has(v.runId))continue;const I=Wa(v.item);if(I){if(x.has(I)||(x.add(I),!De))continue}else if(!De&&Hi(v.item))continue;m.push(v.item)}return m},[qn,ke,jt,De]),j=!E&&Et.length<=160,F=(m,x,v)=>{const I=m.item,S=v??I.id,Q=Gs(I),J=Bl(I),ze=Jh(I,J),qe=J.executor??J.requester,it=za(yn((qe==null?void 0:qe.name)??J.primaryLabel??I.agentName??Q.agentName??null),yn((qe==null?void 0:qe.id)??I.agentId??Q.agentId??null),Vt)||"OrgX";let Ke=eg(ze)||it;if(ze==="agent"&&it){const ko=Xi(it);ko&&(Ke=`${it} (${ko})`)}const Ye=Ua(m.userState),ot=ze==="agent"?uo(it)||Ye:Zh[ze]||Ye,tt=ye==="newest"&&x<2,Dt=m.runId,cn=Kl(I),Rn=ug(I),tn=wi(I),{title:Je}=Qi(I),nn=lt(I),Fn=Rr([{value:de(nn,["initiative_title","initiativeTitle"]),idHint:I.initiativeId},{value:I.initiativeId?z.get(I.initiativeId)??null:null,idHint:I.initiativeId}]),Ns=zs(I)??(Dt?Cn.get(Dt)??null:null),bo=Rr([{value:de(nn,["workstream_title","workstreamTitle"]),idHint:Ns},{value:Ns?we.get(Ns)??null:null,idHint:Ns},{value:Dt?Yn.get(Dt)??null:null,idHint:Ns}]),vo=[Fn,bo].filter(Boolean).join(" > "),dr=Lr(tn.scope,vo,Je,qt(I.description),Xe(Xs(I.type)))??Xe(Xs(I.type)),fa=Lr(cn,Rn,tn.update,qt(I.summary)),ha=Lr(tn.status,tn.outcomes[0],tn.nextUp[0]?`Next up: ${tn.nextUp[0]}`:null,qt(I.description)),ga=Lr(tn.update,Gl(I,fa??ha??null),Je,dr)??dr,td=_s(de(nn,["event","event_name","eventName"]),null),Si=Ns?V.get(Ns):void 0,nd=(Ne==null?void 0:Ne.state)==="running"&&Ns===(Ne==null?void 0:Ne.activeWorkstreamId),sd=Si?` — #${Si.rank} in queue`:"",id=(vo||Fn||bo||td||Xs(I.type))+(nd?sd:""),rd=Ba(m.userState),ad=new Date(I.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),od=Rt(I.timestamp),ld=m.bucket==="artifact"?cg(I):null,wo=dg(I);return n.jsx(ph,{renderKey:S,displayTitle:dr,headline:ga,contextLabel:id,detailText:(fa??ha)!==ga?fa??ha:null,displayAgentName:Ke,railColor:ot,statusColor:Ye,userStateLabel:rd,userStateWhy:m.userStateWhy,relativeTime:od,timeLabel:ad,isRecent:tt,enableMotion:j,onOpen:()=>{ge(1),B(I.id)},ariaLabel:`Open activity details for ${ga||dr||Xs(I.type)}`,artifactSnippet:ld,evidenceChips:wo.length>0?wo:void 0,actorCategory:ze,queuePosition:Si?{rank:Si.rank,state:Si.state}:null},S)};return n.jsx(Ch,{sessions:s,initiatives:r??[],workspaceId:ne??null,query:je,statusFilter:Y,sortOrder:ye,timeFilterId:h,customTimeRange:g,snapshot:K,onRequestRefresh:G,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[qn&&f.length>0?n.jsx(ch,{items:f,session:cr,agentName:((C=f[0])==null?void 0:C.agentName)??null,onBack:D,onOpenItem:m=>{ge(1),B(m.id)}}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h2",{className:"flex-shrink-0 text-heading font-semibold text-white",children:"Activity"}),n.jsx("span",{className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary tabular-nums",children:dn}),as>0&&n.jsxs("span",{className:"hidden flex-shrink-0 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums sm:inline-flex",children:["+",as," hidden"]}),es>0&&!De&&n.jsxs("button",{type:"button",onClick:()=>he(!0),className:"hidden flex-shrink-0 rounded-full border border-white/[0.14] bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums transition-colors hover:bg-white/[0.08] hover:text-primary sm:inline-flex",title:"Show low-signal sync replay events",children:[es," sync hidden"]}),De&&n.jsx("button",{type:"button",onClick:()=>he(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-lime transition-colors hover:bg-lime/[0.16] sm:inline-flex",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsx("span",{className:fe("h-1.5 w-1.5 flex-shrink-0 rounded-full",wt&&"pulse-soft"),style:{backgroundColor:q.lime},"aria-label":"Live",title:wt?"New activity within the last minute":"Live activity feed"}),n.jsx("div",{className:"ml-auto w-[180px] flex-shrink-0 sm:w-[220px]",children:n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-muted",children:[n.jsx("circle",{cx:"11",cy:"11",r:"7"}),n.jsx("path",{d:"m20 20-3.5-3.5"})]}),n.jsx("input",{value:je,onChange:m=>R(m.target.value),placeholder:"Search...",className:"h-7 w-full rounded-full border border-white/[0.08] bg-white/[0.03] pl-7 pr-2 text-micro text-primary placeholder:text-muted transition-colors focus:border-lime/30 focus:outline-none","aria-label":"Search activity"})]})})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("div",{className:"relative",ref:Ut,children:[n.jsxs("button",{type:"button",onClick:()=>{dt(m=>!m),_e(!1)},"aria-haspopup":"menu","aria-expanded":ee,className:fe("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",ee?"border-lime/30 bg-lime/[0.10] text-lime":"border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsx("span",{className:"max-w-[120px] truncate",children:Es}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:fe("transition-transform duration-200",ee&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:ee&&n.jsx(ue.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute left-0 z-30 mt-2 w-[min(92vw,380px)] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity time range",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Presets"}),n.jsx("div",{className:"flex flex-wrap gap-1",children:Vi.filter(m=>m.id!=="custom").map(m=>{const x=h===m.id;return n.jsx("button",{type:"button",onClick:()=>{y==null||y(m.id),dt(!1)},className:fe("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:m.label},m.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),vn?n.jsx("input",{type:"datetime-local",step:300,value:Fa(St),onChange:m=>Mt(Ol(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Io,{selected:St,onChange:m=>Mt(m instanceof Date?m:null),selectsStart:!0,startDate:St,endDate:Ct,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1}),n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"End"}),vn?n.jsx("input",{type:"datetime-local",step:300,min:Fa(St),value:Fa(Ct),onChange:m=>Kt(Ol(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Io,{selected:Ct,onChange:m=>Kt(m instanceof Date?m:null),selectsEnd:!0,minDate:St??void 0,startDate:St,endDate:Ct,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro text-secondary",children:Xn?`${Cr(St)} - ${Cr(Ct)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:da,className:"rounded-full border border-white/[0.14] bg-white/[0.03] px-2.5 py-1 text-micro font-semibold text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Clear"}),n.jsx("button",{type:"button",onClick:ls,disabled:!Xn,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-lime transition-colors hover:bg-lime/[0.2] disabled:opacity-45",children:"Apply"})]})]})]})]})})})]}),n.jsx("div",{className:"mx-0.5 h-3.5 w-px flex-shrink-0 bg-white/[0.08]"}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[(st||d||p)&&n.jsxs(n.Fragment,{children:[st&&n.jsxs("button",{onClick:D,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Pl(Jn.id)?n.jsx(yi,{provider:Jn.id,size:"xs"}):n.jsx(Gt,{name:(At==null?void 0:At.agentName)??"OrgX",hint:c??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",c?`: ${c}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:b,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),p&&n.jsxs("button",{onClick:_,className:"chip chip-avatar inline-flex min-w-0 items-center",style:{borderColor:"rgba(10,212,196,0.3)",color:"#0AD4C4"},"aria-label":"Clear agent filter",children:[Pl(Zn.id)?n.jsx(yi,{provider:Zn.id,size:"xs"}):n.jsx(Gt,{name:p,hint:p,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Agent: ",p]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]})]}),n.jsx("div",{className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-white/[0.08] bg-white/[0.02] p-0.5",role:"group","aria-label":"Activity status filters",children:Object.keys(_r).map(m=>{const x=Y===m;return n.jsx("button",{type:"button",onClick:()=>Ie(m),"aria-pressed":x,className:fe("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",x?"border border-lime/25 bg-lime/[0.10] text-lime":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:_r[m]},m)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:Tt,children:[n.jsxs("button",{type:"button",onClick:()=>{_e(m=>!m),dt(!1)},"aria-haspopup":"menu","aria-expanded":Ce,"aria-label":"Activity filters",title:"Activity filters",className:fe("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Ce?"border-lime/30 bg-lime/[0.10] text-lime":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"),children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 6h16"}),n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"M10 18h4"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Filters"}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:fe("transition-transform duration-200",Ce&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:Ce&&n.jsx(ue.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(m=>n.jsx("button",{type:"button",onClick:()=>{mt(m.id),_e(!1)},className:fe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",ye===m.id?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:m.label},m.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(_r).map(m=>{const x=Y===m;return n.jsx("button",{type:"button",onClick:()=>{Ie(m),_e(!1)},className:fe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:_r[m]},m)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{he(m=>!m)},className:fe("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",De?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:De?"Hide background sync events":"Show background sync events"}),n.jsx("p",{className:"mt-1 text-micro leading-relaxed text-muted",children:"Background sync events are routine system operations that most users can safely ignore."})]})]})})})]})]})]})]})}),n.jsxs("div",{ref:nt,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[Et.length===0&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-4 py-5",children:n.jsxs("div",{className:"mx-auto max-w-2xl",children:[n.jsx(la,{icon:"activity",headline:le?"Syncing activity feed...":st?"No activity yet for this session":d?"No activity yet for this workstream":p?`No recent activity from ${p}`:Y!=="all"?`No matches for this filter. ${dn>0?`${dn} events in other categories.`:""}`:me&&me.length>0?`Waiting for autopilot to start. Queue has ${me.length} item${me.length===1?"":"s"} ready.`:"No activity yet",description:le?"Live updates usually appear within a few seconds after dispatch.":Y!=="all"?'Try selecting "All" to see every event.':p?`Try widening the time window or select a different agent.${Ds?` Last active: ${Ds}.`:""}`:`Try widening the time window (${Es}), changing filters, or launch the next workstream.`,className:"py-6"}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:Yt.map(m=>{const x=h===m.id;return n.jsx("button",{type:"button",onClick:()=>y==null?void 0:y(m.id),className:fe("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.1] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:m.label},`empty-time-${m.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[p&&n.jsx("button",{type:"button",onClick:()=>{_==null||_(),y==null||y("all")},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Show all activity"}),(st||d||Y!=="all")&&n.jsx("button",{type:"button",onClick:()=>{st&&D(),d&&(b==null||b()),p&&(_==null||_()),Y!=="all"&&Ie("all")},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),L&&n.jsx("button",{type:"button",onClick:()=>void ii("play",L),disabled:Z!==null,className:"rounded-full border border-lime/28 bg-lime/12 px-3 py-1.5 text-caption font-semibold text-lime transition hover:bg-lime/18 disabled:opacity-45",children:Z==="play"?"Starting...":"Start next session"}),!L&&P&&n.jsx("button",{type:"button",onClick:P,className:"rounded-full border border-lime/28 bg-lime/12 px-3 py-1.5 text-caption font-semibold text-lime transition hover:bg-lime/18",children:"Browse initiatives"})]}),Oe&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Oe})]})}),n.jsx(dh,{completedCount:wn.completed,decisionsCount:wn.decisions,blockerCount:wn.blocked,visible:Ht,onDismiss:()=>{gt(!1),vt.current=Date.now()}}),Et.length>0&&n.jsxs("div",{className:"space-y-4",children:[os.map(m=>{const x=m.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:m.label}),j?n.jsx(bt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:x.map((v,I)=>{const S=Ae.has(v.key),Q=v.allItems.slice(1),J=Q.length,ze=Math.min(J,Ee[v.key]??qi),qe=Q.slice(0,ze);if(v.count===1)return F(v.representative,I);if(v.key.startsWith("autopilot::")&&v.count>=3){const Ke=Wl(v);return n.jsx(Ml,{workstreamTitle:Ke.workstreamTitle,items:Ke.items,firstTimestamp:v.firstTimestamp,lastTimestamp:v.representative.timestampEpoch,onExpandItem:Ye=>{const ot=v.allItems[Ye];ot&&B(ot.item.id)}},v.key)}const it=`cluster:${v.key}`;return n.jsxs("div",{children:[F(v.representative,I,it),n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),kn(v.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",v.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:S?"hide":`and ${v.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:fe("transition-transform",S?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),S&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[qe.map((Ke,Ye)=>F(Ke,I+Ye+1)),ze<J&&n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),Zi(v.key,J)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",J-ze," remaining)"]})]})]},v.key)})})}):n.jsx("div",{className:"space-y-2",children:x.map((v,I)=>{const S=Ae.has(v.key),Q=v.allItems.slice(1),J=Q.length,ze=Math.min(J,Ee[v.key]??qi),qe=Q.slice(0,ze);if(v.count===1)return F(v.representative,I);if(v.key.startsWith("autopilot::")&&v.count>=3){const Ke=Wl(v);return n.jsx(Ml,{workstreamTitle:Ke.workstreamTitle,items:Ke.items,firstTimestamp:v.firstTimestamp,lastTimestamp:v.representative.timestampEpoch,onExpandItem:Ye=>{const ot=v.allItems[Ye];ot&&B(ot.item.id)}},v.key)}const it=`cluster:${v.key}`;return n.jsxs("div",{children:[F(v.representative,I,it),n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),kn(v.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",v.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:S?"hide":`and ${v.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:fe("transition-transform",S?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),S&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[qe.map((Ke,Ye)=>F(Ke,I+Ye+1)),ze<J&&n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),Zi(v.key,J)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",J-ze," remaining)"]})]})]},v.key)})})]},m.key)}),n.jsx("div",{ref:et,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:fe("flex items-center justify-center py-6 transition-[opacity,transform] duration-500 ease-out",k?"opacity-100 translate-y-0":N?"opacity-0 translate-y-2":"opacity-0 translate-y-2 pointer-events-none"),children:n.jsx("div",{className:"flex items-center gap-2.5",children:n.jsxs("div",{className:"flex gap-1","aria-label":"Loading older events",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-lime/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-lime/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-lime/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!N&&!k&&Et.length>0&&!Dl(h)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:as>0?`${Et.length} of ${dn} events`:"Beginning of activity history"})]})]})]}),Me?n.jsx(qh,{}):null,n.jsx(fh,{open:$!==null,onClose:Mn,children:$&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:Ua($.userState),boxShadow:`0 0 12px ${Ua($.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Ba($.userState)," · ",un+1,"/",Et.length," sessions"]}),oe&&n.jsx(Ln,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:oe})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[$.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H($.runId),Mn()},className:"rounded-full border border-lime/25 bg-lime/10 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/20",children:"Focus session"}),n.jsx("button",{type:"button",onClick:()=>Is(-1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Previous activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}),n.jsx("button",{type:"button",onClick:()=>Is(1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Next activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",onClick:()=>We(m=>!m),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),Pe&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>We(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[$.runId&&n.jsx("button",{type:"button",onClick:()=>{En("Run id",$.runId??""),We(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy run ID"}),ji.agentId&&n.jsx("button",{type:"button",onClick:()=>{En("Agent id",ji.agentId??""),We(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy agent ID"}),n.jsx("button",{type:"button",onClick:()=>{En("Event id",$.item.id),We(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy event ID"})]})]})]}),n.jsx("button",{type:"button",onClick:Mn,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"Close activity detail",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]})]}),n.jsx("div",{className:"relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-5 pb-5 pt-4 sm:px-6",children:n.jsx(bt,{mode:"wait",custom:rt,children:n.jsx(ue.section,{custom:rt,initial:{opacity:0,x:rt*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:rt*-32,scale:.985},transition:{duration:.28,ease:[.16,1,.3,1]},className:"min-h-full w-full overscroll-contain",children:n.jsxs("div",{className:"space-y-6 pb-1",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-title font-semibold tracking-[-0.02em] text-white whitespace-pre-wrap break-words",children:pt||Gl($.item,X)||Xe($.item.title||Xs($.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date($.item.timestamp).toLocaleString()," · ",Rt($.item.timestamp),ht==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const m=lt($.item),x=(re==null?void 0:re.workstreamId)??zs($.item)??($.runId?Cn.get($.runId)??null:null),v=Rr([{value:(re==null?void 0:re.workstreamTitle)??null,idHint:x},{value:de(m,["workstream_title","workstreamTitle"]),idHint:x},{value:x?we.get(x)??null:null,idHint:x},{value:$.runId?Yn.get($.runId)??null:null,idHint:x}]),S=[Rr([{value:(re==null?void 0:re.initiativeTitle)??null,idHint:$.item.initiativeId},{value:de(m,["initiative_title","initiativeTitle"]),idHint:$.item.initiativeId},{value:$.item.initiativeId?z.get($.item.initiativeId)??null:null,idHint:$.item.initiativeId}]),v].filter(Boolean).join(" > ");return S?n.jsx(Ln,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:S})}):null})(),n.jsx(Ln,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Ba($.userState)}),n.jsxs(Ln,{tone:"muted",children:[n.jsx(Gt,{name:(pn==null?void 0:pn.label)??(Qe==null?void 0:Qe.primaryLabel)??"OrgX",hint:pn?Ul(pn):(Qe==null?void 0:Qe.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(pn==null?void 0:pn.label)??(Qe==null?void 0:Qe.primaryLabel)??"OrgX"})]}),lr&&n.jsx(Ln,{tone:"lime",children:"Sync replay"})]})]}),Bt.has("artifact")&&$&&Tr($.item)&&!mn&&n.jsxs("button",{type:"button",onClick:()=>{const m=Tr($.item);m&&W(m)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.cyan,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-body font-medium",style:{color:q.cyan},children:"View registered artifact"})]}),n.jsx(xh,{item:$.item}),Bt.has("artifact")&&mn&&n.jsxs("div",{className:"rounded-xl border border-cyan-400/25 bg-gradient-to-b from-cyan-500/[0.10] to-cyan-500/[0.04]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 pt-3.5 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-micro font-semibold uppercase tracking-wider text-cyan-200/80",children:mn.source==="metadata"?"Artifact":Xe(mn.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[Me&&n.jsxs("div",{className:"inline-flex rounded-full border border-cyan-400/20 bg-black/30 p-0.5 text-caption",children:[n.jsx("button",{type:"button",onClick:()=>ce("structured"),"aria-pressed":Ve==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ve==="structured"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"Structured"}),n.jsx("button",{type:"button",onClick:()=>ce("json"),"aria-pressed":Ve==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ve==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),On&&n.jsx("button",{type:"button",onClick:()=>W(On),className:"rounded-full border border-cyan-400/25 bg-cyan-500/[0.12] px-2.5 py-0.5 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.2]",children:"Open full artifact"})]})]}),n.jsx("div",{className:"max-h-[320px] overflow-y-auto px-4 pb-4",children:n.jsx("div",{className:"rounded-lg border border-white/[0.06] bg-black/20 p-3.5",children:Ve==="structured"?Jc(mn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(mn.value,null,2)})})})]}),Bt.has("outcome")&&_t&&n.jsxs("div",{className:fe("rounded-xl border px-3.5 py-3",_t.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",_t.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",_t.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",_t.tone==="neutral"&&"border-cyan-400/22 bg-cyan-500/[0.07]"),children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/78",children:_t.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:_t.summary}),_t.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:_t.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[$.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H($.runId),Mn()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}),nr&&n.jsx("button",{type:"button",onClick:()=>{A==null||A(Jt[0]??null),Mn()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:Jt.length>0?"Resolve decision":"Resolve decisions"}),On&&!mn&&n.jsx("button",{type:"button",onClick:()=>W(On),className:"rounded-full border border-cyan-300/25 bg-cyan-500/[0.1] px-3 py-1 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.16]",children:"Open artifact"}),or&&n.jsx("a",{href:or,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Review evidence"}),ln&&n.jsx("button",{type:"button",onClick:()=>void ri(),disabled:Re,className:fe("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",ln.isBlockedFlow?"border-amber-300/30 bg-amber-500/[0.12] text-amber-100 hover:bg-amber-500/[0.18]":"border-lime/30 bg-lime/[0.12] text-lime hover:bg-lime/[0.18]"),children:Re?"Scheduling...":ln.actionLabel})]}),ln&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Ue??ln.helperText})]}),(()=>{var cn,Rn,tn;if(!Bt.has("structured_outcomes"))return null;const m=lt($.item),x=zt(m==null?void 0:m.outcomes),v=ca(m),I=bn((m==null?void 0:m.status_updates_applied)??(m==null?void 0:m.statusUpdatesApplied)??((cn=zt(m==null?void 0:m.result))==null?void 0:cn.status_updates_applied)??((Rn=zt(m==null?void 0:m.result))==null?void 0:Rn.statusUpdatesApplied)),S=((tn=de(m,["event","event_name","eventName"]))==null?void 0:tn.toLowerCase())??"",Q=(m==null?void 0:m.status_updates_buffered)??(m==null?void 0:m.statusUpdatesBuffered),J=S.includes("status_updates_buffered")||Q===!0||typeof Q=="number"&&Q>0||typeof Q=="string"&&["true","1","yes"].includes(Q.trim().toLowerCase()),ze=de(x,["pr_url","prUrl","url"]),qe=x==null?void 0:x.pr_number,it=de(x,["commit_sha","commitSha"]),Ke=de(x,["commit_url","commitUrl"]),Ye=zt(x==null?void 0:x.tests),tt=(v.length>0||(I??0)>0||J)&&(!mn||S.includes("status_updates"));return ze||it||Ye||tt?n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-muted",children:tt?"Updates & outcomes":"Outcomes"}),tt&&n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/20 bg-[#14B8A6]/[0.06] px-3.5 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-[#14B8A6]"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-[#7ce0d3]",children:J?"Updates being applied":"Updates applied"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[v.length>0?`${v.length} scoped update${v.length===1?"":"s"}`:(I??0)>0?`${I} status update${I===1?"":"s"}`:"Status updates recorded",J?" · queued for sync":""]})]})]}),v.length>0&&n.jsx("ul",{className:"mt-2 space-y-1.5 pl-5",children:v.slice(0,6).map((Je,nn)=>n.jsxs("li",{className:"text-caption text-secondary",children:[n.jsxs("span",{className:"text-primary",children:[Je.scope,": ",Je.label]}),Je.status?` → ${Je.status}`:"",Je.reason?` · ${Je.reason}`:""]},`${Je.scope}-${Je.label}-${nn}`))})]}),ze&&n.jsxs("a",{href:ze,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 rounded-xl border border-lime/20 bg-lime/[0.06] px-3.5 py-2.5 transition-colors hover:bg-lime/[0.10]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-lime"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-lime/70",children:"Pull Request"}),n.jsx("p",{className:"mt-0.5 text-body font-semibold text-primary",children:qe?`#${qe}`:"View on GitHub"})]}),n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:"flex-shrink-0 text-muted",children:n.jsx("path",{d:"M7 17 17 7M17 7H7M17 7v10"})})]}),it&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-lime/15 bg-lime/[0.04] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-lime/60"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-lime/60",children:"Commit"}),n.jsx("p",{className:"mt-0.5 font-mono text-caption text-primary",children:it.slice(0,7)})]}),Ke&&n.jsx("a",{href:Ke,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary hover:text-primary transition-colors",children:"View"})]}),Ye&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-cyan-400/15 bg-cyan-500/[0.04] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:(Ye.failed??0)>0?q.red:"#67e8f9"}}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider",style:{color:(Ye.failed??0)>0?q.red:"rgba(103,232,249,0.7)"},children:"Tests"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[Ye.passed??0," passed",(Ye.failed??0)>0&&n.jsxs("span",{className:"text-red-300",children:[" · ",Ye.failed," failed"]}),(Ye.skipped??0)>0&&n.jsxs("span",{className:"text-muted",children:[" · ",Ye.skipped," skipped"]})]})]})]})]}):null})(),kt&&!Me&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/20 bg-amber-500/[0.06] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption text-amber-100/80",children:"Temporarily paused to manage capacity. Will resume automatically."}),kt.retryInMs!==null&&n.jsxs("p",{className:"mt-1 text-micro text-muted",children:["Retrying in ~",Math.max(1,Math.round(kt.retryInMs/1e3)),"s"]})]}),kt&&Me&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/26 bg-amber-500/[0.08] px-3.5 py-3",children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-amber-100/85",children:"Spawn guard"}),n.jsx(Ln,{tone:kt.isRateLimited?"muted":"red",children:kt.isRateLimited?"Rate limited":"Blocked"})]}),n.jsx("p",{className:"mt-1 text-caption text-amber-100/80",children:"Dispatch was stopped before launch. Adjust limits or retry after the window resets."}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Domain window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:kt.domainCurrent!==null&&kt.domainMax!==null?`${kt.domainCurrent}/${kt.domainMax} per hour`:"Not provided"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Global window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:kt.totalCurrent!==null&&kt.totalMax!==null?`${kt.totalCurrent}/${kt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[kt.domain&&n.jsxs(Ln,{tone:"muted",children:["Domain: ",Xe(kt.domain)]}),kt.modelTier&&n.jsxs(Ln,{tone:"muted",children:["Tier: ",Xe(kt.modelTier)]}),ks&&n.jsxs(Ln,{tone:"muted",children:["Retry: ",ks]}),!ks&&kt.retryInMs!==null&&n.jsxs(Ln,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(kt.retryInMs/1e3)),"s"]})]}),kt.blockedReason&&n.jsx("p",{className:"mt-2 rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2 text-caption text-primary",children:qt(kt.blockedReason)??kt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[xe&&n.jsx("button",{type:"button",onClick:xe,className:"rounded-full border border-amber-300/32 bg-amber-500/[0.14] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-500/[0.2]",children:"Edit limits"}),ln&&n.jsx("button",{type:"button",onClick:()=>void ri(),disabled:Re,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/[0.18] disabled:opacity-50",children:Re?"Scheduling...":"Retry now"})]})]}),us.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Results"}),n.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-caption sm:grid-cols-3",children:us.map(m=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:m.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${m.tone==="critical"?"text-red-300":"text-primary"}`,children:m.value})]},m.label))})]}),Qe&&!re&&Qe.mode!=="system"&&n.jsxs("div",{className:"flex items-center gap-2 text-body text-secondary",children:[Qe.executor&&n.jsxs(n.Fragment,{children:[n.jsx(Gt,{name:Qe.executor.label,hint:Ul(Qe.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Qe.executor.label}),(()=>{const m=Xi(Qe.executor.label);return m?n.jsxs("span",{className:"text-caption text-muted",children:["(",m,")"]}):null})()]}),Qe.mode==="handoff"&&Qe.requester&&n.jsxs("span",{className:"text-caption text-muted",children:["requested by ",Qe.requester.label]})]}),re&&n.jsxs("div",{className:"space-y-5",children:[Bt.has("action_needed")&&(U==null?void 0:U.nextStep)&&((Ft==null?void 0:Ft.tone)==="critical"||(Ft==null?void 0:Ft.tone)==="warning")&&n.jsxs("div",{className:"rounded-xl border border-red-400/25 bg-red-500/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-red-400"}),n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-red-200",children:"Action needed"})]}),n.jsx("p",{className:"text-body text-primary leading-relaxed",children:U.nextStep})]}),(()=>{if(!Bt.has("session"))return null;const m=lt($.item),x=de(m,["parsed_status","status"]),v=["Queued","Dispatched","Running","Completed"],I={queued:"Queued",dispatched:"Dispatched",running:"Running",completed:"Completed",success:"Completed",blocked:"Running",needs_decision:"Running",needs_attention:"Running",failed:"Running"},S=I[x??""]??I[re.event??""]??null,Q=S?v.indexOf(S):-1,J=x==="completed"||x==="success",ze=gi($.item),qe=ze?ti.get(ze):null,it=qe!=null&&qe.startedAt?new Date(qe.startedAt).getTime():null,Ke=qe!=null&&qe.completedAt?new Date(qe.completedAt).getTime():null;return n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Execution Flow"}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"rounded-full border border-lime/30 bg-lime/[0.08] px-2 py-0.5 text-micro font-semibold text-lime/85",children:fi(re.event)??Xe(re.event)}),it&&n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[n.jsx(Bh,{startMs:it,endMs:Ke,isTerminal:J})," ","elapsed"]})]})]}),Ft&&n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:ir},children:ms?(_t==null?void 0:_t.label)??"Stopped":`${Ft.pct}%`})]}),Q>=0&&n.jsx("div",{className:"mt-3 flex items-center gap-1",children:v.map((Ye,ot)=>{const tt=ot<Q||ot===Q&&J,Dt=ot===Q&&!J;return n.jsxs("div",{className:"flex items-center gap-1",children:[ot>0&&n.jsx("div",{className:"h-[1.5px] w-4 sm:w-5",style:{backgroundColor:tt||Dt?q.lime:"rgba(255,255,255,0.14)"}}),n.jsxs("div",{className:"flex flex-col items-center gap-1",children:[n.jsx("span",{className:fe("h-2 w-2 rounded-full transition-transform duration-200",Dt&&"animate-pulse scale-110"),style:{backgroundColor:tt||Dt?q.lime:"rgba(255,255,255,0.18)"}}),n.jsxs("span",{className:fe("text-[10px] leading-none tracking-[0.05em]",tt||Dt?"text-primary":"text-muted/60"),children:[Ye,tt&&ot===v.length-1&&" ✓"]})]})]},Ye)})}),Ft&&n.jsxs("div",{className:"mt-3 border-t border-white/[0.06] pt-3",children:[n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-300",style:{width:`${Math.max(4,Ft.pct)}%`,backgroundColor:ir}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:ms?(_t==null?void 0:_t.summary)??Ft.label:Ft.label})]})]})})(),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),ws.primary!==In?n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Gt,{name:ws.primary,hint:ws.secondary??ws.primary,size:"xs"}),n.jsx("span",{children:ws.primary}),n.jsx("span",{className:"text-white/[0.2]",children:"→"}),n.jsx(Gt,{name:In,hint:In,size:"xs"}),n.jsx("span",{children:In}),re.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",Xe(re.domain),")"]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Gt,{name:In,hint:In,size:"xs"}),n.jsx("span",{children:In}),re.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",Xe(re.domain),")"]})]}),Me&&n.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Requester"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:ws.primary})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Executor"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:In})]}),re.dispatcherClient&&re.dispatcherClient!=="unknown"&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:Xe(re.dispatcherClient)})]}),(re.domain||re.requiredSkills.length>0)&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Policy"}),n.jsxs("div",{className:"mt-0.5 text-caption text-primary",children:[re.domain??"",re.requiredSkills.length>0?`${re.domain?" · ":""}${re.requiredSkills.join(", ")}`:""]})]})]})]}),Bt.has("scope")&&U&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Scope"}),n.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Initiative"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:U.initiativeTitle??(U.initiativeId?Ss(U.initiativeId):"—")})]}),U.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Xe(U.initiativeStatus)})]}),(U.workstreamTitle||U.workstreamId)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Workstream"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:U.workstreamTitle??Ss(U.workstreamId)})]}),U.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Xe(U.workstreamStatus)})]})]}),U.initiativeWorkstreamPct!==null&&n.jsxs("div",{className:"mt-3",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro text-muted",children:[n.jsx("span",{children:"Workstreams complete"}),n.jsxs("span",{className:"tabular-nums",children:[U.doneInitiativeWorkstreams??0,"/",U.totalInitiativeWorkstreams??0]})]}),n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full bg-lime/80",style:{width:`${Math.max(4,U.initiativeWorkstreamPct)}%`}})})]})]}),rr.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Milestones"}),n.jsx(Hm,{nodes:Um(rr),compact:!0})]}),((U==null?void 0:U.taskTitle)||(U==null?void 0:U.milestoneTitle)||(U==null?void 0:U.phase)||(U==null?void 0:U.nextStep)||(U==null?void 0:U.parsedStatus)||(U==null?void 0:U.stopReason))&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Current step"}),n.jsxs("div",{className:"space-y-1 text-caption",children:[(U==null?void 0:U.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:U.taskTitle})]}),(U==null?void 0:U.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:U.milestoneTitle})]}),(U==null?void 0:U.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:fi(U.phase)??Xe(U.phase)})]}),(U==null?void 0:U.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:U.nextStep})]}),(U==null?void 0:U.parsedStatus)&&U.parsedStatus!==(U==null?void 0:U.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:fi(U.parsedStatus)??Xe(U.parsedStatus)})]}),(U==null?void 0:U.stopReason)&&U.stopReason!==(U==null?void 0:U.phase)&&U.stopReason!==(U==null?void 0:U.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:fi(U.stopReason)??Xe(U.stopReason)})]})]})]}),re.error&&n.jsx("div",{className:"rounded-lg border border-red-400/20 bg-red-500/10 px-4 py-3 text-body text-red-100/80",children:re.error})]}),Bt.has("summary")&&_i&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Ze==="missing"&&!lr&&Me&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(Wi,{mode:"block",text:_i,className:"text-body leading-relaxed text-primary"})]}),qt($.item.description)&&qt($.item.description)!==_i&&(()=>{const m=qt($.item.description)??"";return m.length>200?n.jsxs("details",{children:[n.jsx("summary",{className:"cursor-pointer text-micro font-semibold uppercase tracking-wider text-muted select-none",children:"Details"}),n.jsx("div",{className:"mt-2",children:n.jsx(Wi,{mode:"block",text:m,className:"text-body leading-relaxed text-secondary"})})]}):n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Details"}),n.jsx(Wi,{mode:"block",text:m,className:"text-body leading-relaxed text-secondary"})]})})(),cs&&n.jsxs("details",{children:[n.jsx("summary",{className:"cursor-pointer text-micro font-semibold uppercase tracking-wider text-muted select-none",children:"Narrative"}),n.jsxs("div",{className:"mt-2 space-y-1.5 text-caption",children:[n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Intent"})," ",n.jsx("span",{className:"text-primary",children:cs.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:cs.dispatch})]}),cs.highlights.length>0&&n.jsxs("div",{children:[n.jsx("span",{className:"text-muted",children:"Highlights"}),n.jsx("ul",{className:"mt-1 list-disc space-y-0.5 pl-4 text-primary",children:cs.highlights.slice(0,3).map((m,x)=>n.jsx("li",{children:m},`${cs.sliceRunId}:highlight:${x}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:cs.outcome.summary})]})]})]}),(()=>{var tn;if(!Bt.has("evidence"))return null;const m=lt($.item),x=zt(m==null?void 0:m.blocker),v=de(m,["error","reason","blocked_reason","blockedReason","last_error","lastError"])??null,I=ns[0]??null,S=x?{description:de(x,["description","summary"])??v??null,waiting_on:de(x,["waiting_on","required_actor","requiredActor"])??null,required_action:de(x,["required_action","requiredAction"])??de(m,["next_step","nextStep"])??null}:I?{description:I.reason,waiting_on:I.waitingOn,required_action:I.requiredAction}:($.item.type==="run_failed"||$.item.type==="blocker_created")&&v?{description:v,waiting_on:null,required_action:de(m,["next_step","nextStep"])}:void 0,Q=(m==null?void 0:m.decisions_needed)??(m==null?void 0:m.decisionsNeeded),J=Array.isArray(Q)?Q.map(Je=>{const nn=zt(Je);return nn?{title:de(nn,["title","label","question","summary"])??"Pending decision",id:de(nn,["id","decision_id","decisionId"])}:null}).filter(Je=>Je!==null):[],ze=J.length>0?J:sr.length>0?sr.map(Je=>({title:Je.title,id:Je.id})):Jt.length>0?Jt.map(Je=>({id:Je,title:"Pending decision"})):void 0,qe=m==null?void 0:m.outcomes,it=(tn=m==null?void 0:m.task_updates)==null?void 0:tn.filter(Je=>{var nn,Fn;return((nn=Je.title)==null?void 0:nn.trim().toLowerCase())!==((Fn=S==null?void 0:S.description)==null?void 0:Fn.trim().toLowerCase())}),Ke=(S==null?void 0:S.description)&&(_t==null?void 0:_t.summary)&&S.description.trim().toLowerCase()===_t.summary.trim().toLowerCase(),Ye=!!S&&!Ke,ot=!!(qe!=null&&qe.pr_url||qe!=null&&qe.commit_sha||qe!=null&&qe.tests||it&&it.length>0),tt=!!(Ye||ze&&ze.length>0),Dt=ot||tt,cn=tt,Rn=Tn.length>0;return!cn&&!Rn?null:n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Evidence"}),n.jsxs("div",{className:"space-y-2",children:[Ye&&n.jsxs("div",{className:"rounded-xl border border-red-400/20 bg-red-500/[0.06] px-3.5 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-red-400"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-red-300/70",children:"Blocker"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:S.description??"Blocked"}),S.waiting_on&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Waiting on: ",S.waiting_on]}),S.required_action&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Next action: ",S.required_action]})]})]}),nr&&Jt.length>0&&n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ma.map(Je=>n.jsx("button",{type:"button",onClick:()=>void(O==null?void 0:O(Jt[0],Je.id)),className:"rounded-full border border-lime/30 bg-lime/[0.10] px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/[0.16]",children:Je.label},Je.id)),n.jsx("button",{type:"button",onClick:()=>{A==null||A(Jt[0]??null),Mn()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption text-secondary transition hover:bg-white/[0.1]",children:"Review in detail"})]})]}),ze&&ze.length>0&&n.jsx("div",{className:"space-y-1.5",children:ze.map((Je,nn)=>n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-300/15 bg-amber-400/[0.05] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-amber-400"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-amber-200/70",children:"Decision needed"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:Je.title})]}),Je.id&&A&&n.jsx("button",{type:"button",onClick:()=>{A(Je.id),Mn()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-2.5 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:"Resolve"})]},Je.id??nn))}),Rn&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",open:!Dt,children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary select-none",children:[Tn.length," evidence file",Tn.length===1?"":"s"]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[pa.map((Je,nn)=>{const Fn=Hr(Je.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:Xe(Je.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:zn(Je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Fn&&n.jsx("a",{href:Fn,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open"}),n.jsx("button",{type:"button",onClick:()=>void En(`${Xe(Je.key)} path`,Je.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${Je.key}:${Je.path}:${nn}`)}),ar.length>0&&ar.map((Je,nn)=>{const Fn=Hr(Je.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:Xe(Je.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:zn(Je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Fn&&n.jsx("a",{href:Fn,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open"}),n.jsx("button",{type:"button",onClick:()=>void En(`${Xe(Je.key)} path`,Je.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${Je.key}:${Je.path}:overflow:${nn}`)})]})]})]})]})})(),Me&&(ut||(re==null?void 0:re.logPath)||Ai)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),Me&&(ut||(re==null?void 0:re.logPath)||(re==null?void 0:re.outputPath)||(U==null?void 0:U.initiativeId)||(U==null?void 0:U.workstreamId))&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Technical"]}),n.jsxs("div",{className:"mt-3 space-y-3 text-caption",children:[ut&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[ut.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:Xe(ut.domain)})]}),(ut.provider||ut.model)&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:[ut.provider?`${Xe(ut.provider)} · `:"",ut.model?Ki(ut.model):"—"]})]}),ut.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:Xe(ut.modelTier)})]}),ut.pluginVersion&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Plugin"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:["v",ut.pluginVersion]})]})]}),(ut==null?void 0:ut.skillPack)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skill pack"}),n.jsxs("span",{className:"text-primary",children:[ut.skillPack.name??"—",ut.skillPack.version?`@${ut.skillPack.version}`:"",ut.skillPack.source?` · ${ut.skillPack.source}`:""]}),ut.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var m;return void En("Skill pack checksum",((m=ut.skillPack)==null?void 0:m.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",ut.skillPack.checksum.slice(0,12)]})]}),ut&&ut.requiredSkills.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skills"}),ut.requiredSkills.map(m=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:m},m))]}),(ut==null?void 0:ut.kickoffContextHash)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-micro text-muted",children:"Kickoff context"})," ",n.jsxs("span",{className:"font-mono text-muted",children:[ut.kickoffContextSource?`${ut.kickoffContextSource} · `:"",ut.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void En("Kickoff context hash",ut.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((re==null?void 0:re.logPath)||(re==null?void 0:re.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(re==null?void 0:re.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",zn(re.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void En("Log path",(re==null?void 0:re.logPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),(re==null?void 0:re.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",zn(re.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void En("Output path",(re==null?void 0:re.outputPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]})]}),((U==null?void 0:U.initiativeId)||(U==null?void 0:U.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(U==null?void 0:U.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",Ss(U.initiativeId)]}),(U==null?void 0:U.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",Ss(U.workstreamId)]})]})]})]}),Me&&Ai&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Raw metadata"]}),n.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-muted",children:Ai})]})]})},$.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})});function Bg({workspaceLabel:e,suggestedTitle:t,sessionSummary:s,onCreateInitiative:i,onCreateFromSession:r,onOpenSandbox:a,onOpenSettings:l,onRefresh:c}){const d=!!(t&&t.trim().length>0);return n.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-8 sm:px-6",style:{backgroundColor:q.background},children:n.jsx(Ts,{className:"w-full max-w-5xl overflow-hidden",children:n.jsxs("div",{className:"grid gap-0 lg:grid-cols-[1.08fr_0.92fr]",children:[n.jsxs("div",{className:"border-b border-subtle p-6 sm:p-8 lg:border-b-0 lg:border-r",children:[n.jsxs(ue.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.28,ease:[.16,1,.3,1]},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(en,{type:"initiative",size:16,className:"opacity-95"}),n.jsx("span",{className:"text-caption font-semibold uppercase tracking-[0.12em] text-secondary",children:"First value runway"}),n.jsx("span",{className:"chip",children:e})]}),n.jsx("h2",{className:"mt-4 max-w-2xl text-[30px] font-semibold leading-[1.08] tracking-[-0.03em] text-white sm:text-[38px]",children:"Connected successfully. There is no tracked work here yet."}),n.jsx("p",{className:"mt-4 max-w-2xl text-body leading-relaxed text-secondary sm:text-heading",children:"The fastest path to value is to create one initiative, dispatch one workstream, and watch OrgX keep the execution visible inside OpenClaw."})]}),n.jsxs(ue.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:.06,duration:.3,ease:[.16,1,.3,1]},className:"mt-6 grid gap-3",children:[n.jsxs("button",{type:"button",onClick:i,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-lime/28 bg-lime/10 px-4 py-3 text-left transition hover:bg-lime/14",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-[#E4FFAD]",children:"Create first initiative"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-[#D7F3A3]/78",children:"Start with a real initiative and land directly in Mission Control once it exists."})]}),n.jsx(en,{type:"initiative",size:16,className:"shrink-0"})]}),n.jsxs("button",{type:"button",onClick:r,disabled:!d,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-white/[0.1] bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.05] disabled:cursor-not-allowed disabled:opacity-45",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-white",children:"Use current OpenClaw session as draft"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:d?`Prefill from “${t}” and refine before you launch.`:"No recent local session is available to prefill right now."})]}),n.jsx(en,{type:"session",size:16,className:"shrink-0 opacity-92"})]}),n.jsxs("button",{type:"button",onClick:a,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-white/[0.08] bg-white/[0.02] px-4 py-3 text-left transition hover:bg-white/[0.04]",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-white",children:"Open guided sandbox"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"See the operating model in a clearly marked sandbox before you set up real work."})]}),n.jsx(en,{type:"workstream",size:16,className:"shrink-0 opacity-92"})]})]})]}),n.jsxs("div",{className:"p-6 sm:p-8",children:[n.jsxs("div",{className:"rounded-2xl border border-white/[0.08] bg-white/[0.025] p-4",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(en,{type:"workstream",size:13,className:"text-lime"}),n.jsx("p",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:"What happens next"})]}),n.jsxs("div",{className:"mt-4 space-y-3",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"1. Create one initiative"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"Keep the title concrete. This becomes the first object OrgX can route, track, and score."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"2. Add the first workstream"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"One workstream is enough to prove the queue, dispatch, and progress model."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"3. Watch one live execution"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"The aha moment is seeing the work move from Next Up to In Progress with decisions and artifacts attached."})]})]})]}),n.jsxs("div",{className:"mt-4 rounded-2xl border border-white/[0.08] bg-white/[0.02] p-4",children:[n.jsx("p",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:"Draft signal"}),n.jsx("p",{className:"mt-3 text-body font-semibold text-white",children:d?t:"No current OpenClaw session detected"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:s&&s.trim().length>0?s:"As soon as a local work session exists, this runway can prefill the initiative draft instead of starting from a blank field."}),n.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",onClick:l,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Review settings"}),n.jsx("button",{type:"button",onClick:c,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-secondary transition hover:bg-white/[0.08] hover:text-primary",children:"Refresh workspace"})]})]})]})]})})})}const Ug=o.lazy(async()=>({default:(await sn(()=>import("./BIW2kmQr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),zg=o.lazy(async()=>({default:(await sn(()=>import("./BGqqzQfq.js"),__vite__mapDeps([14,1,5,2,10,11,12,13]))).SessionInspector})),Wg=o.lazy(async()=>({default:(await sn(()=>import("./CDsk---g.js"),__vite__mapDeps([15,1,8,5,2,10,11,12,13]))).DecisionQueue})),Hg=o.lazy(()=>sn(()=>import("./CSlBSRyv.js"),__vite__mapDeps([16,1,5])).then(e=>({default:e.TriageQueue}))),Kg=o.lazy(()=>sn(()=>import("./BafISmbX.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageDetailModal}))),Vg=o.lazy(async()=>({default:(await sn(()=>import("./dgbgHLWm.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),Gg=o.lazy(async()=>({default:(await sn(()=>import("./CQceXoUm.js"),__vite__mapDeps([18,1,2,5,9,10,11,12,13]))).SettingsModal})),Xg=o.lazy(async()=>({default:(await sn(()=>import("./CjGl4MOt.js"),__vite__mapDeps([19,1,2,5,10,11,12,13]))).BulkSessionsModal})),Qg=o.lazy(async()=>({default:(await sn(()=>import("./BYsvgOkA.js"),__vite__mapDeps([20,1,15,8,5,2,10,11,12,13]))).BulkDecisionsModal})),Yg=o.lazy(async()=>({default:(await sn(()=>import("./CKUnb6Tt.js"),__vite__mapDeps([21,1,2,5,10,11,12,13]))).BulkOutboxModal})),Jg=o.lazy(async()=>({default:(await sn(()=>import("./Cgp0m1Ld.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Zg=o.lazy(async()=>({default:(await sn(()=>import("./CgCm4tUc.js"),__vite__mapDeps([23,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),ex=o.lazy(async()=>({default:(await sn(()=>import("./oWHKFgkC.js").then(t=>t.a),__vite__mapDeps([7,1,8,5,6]))).SliceDetailModal})),tx=o.lazy(async()=>({default:(await sn(()=>import("./CPfdWIdE.js"),__vite__mapDeps([24,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),Xl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},nx={connected:q.lime,reconnecting:q.amber,disconnected:q.red},Ql={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},sx=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function Zt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ix(e){const t=Zt(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function rx(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),r=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return r.length<=t?r:`${r.slice(0,t-1).trimEnd()}…`}function ax(e){const t=e.trim().toLowerCase();if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted"))return{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"};if(t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth"))return{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"};if(t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes"))return{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"};const s=Xt(e);return{title:"Live stream degraded",message:rx(s),action:"settings"}}function Dr(e){if(e.runId&&e.runId.trim().length>0)return e.runId.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const t=e.metadata,s=["runId","run_id","sessionId","session_id","agentRunId"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function ox(e,t){const s=Array.isArray(t)?t.map(a=>typeof(a==null?void 0:a.sliceRunId)=="string"?a.sliceRunId.trim():"").filter(a=>a.length>0):[];if(s.length===0)return Br(e);const i=new Set(s),r=e.filter(a=>i.has(a.sliceRunId));return r.length>0?Br(r):Br(e)}function Yl(e){const t=e.sliceRunId;if(typeof t=="string"&&t.trim().length>0)return t.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const s=e.metadata,i=["sliceRunId","slice_run_id","sliceId","slice_id","sliceRun","slice_run"];for(const r of i){const a=s[r];if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Jl(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Zl(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function ec(e,t){const s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";return!s||!i?null:`${s}:${i}`}function lx(e,t){const s=new Set,i=new Set;for(const a of t){const l=typeof a.runId=="string"?a.runId.trim():"";l&&s.add(l);const c=typeof a.sliceRunId=="string"?a.sliceRunId.trim():"";c&&s.add(c);const d=ec(a.initiativeId,a.workstreamId);d&&i.add(d)}let r=0;for(const a of e){const l=typeof a.sourceRunId=="string"?a.sourceRunId.trim():"";if(l&&s.has(l))continue;const c=typeof a.sourceSessionId=="string"?a.sourceSessionId.trim():"";if(c&&s.has(c))continue;const d=ec(a.initiativeId,a.workstreamId);d&&i.has(d)||(r+=1)}return r}function cx(e){return e.filter(t=>t.queueState!=="running"&&t.queueState!=="completed").length}function dx(e,t=new Date){if(!e)return!1;const s=new Date(e);return Number.isNaN(s.getTime())?!1:s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Ha(e,t){const s=Ql[e.status]??99,i=Ql[t.status]??99;return s!==i?s-i:Zt(e.updatedAt??e.lastEventAt??e.startedAt)-Zt(t.updatedAt??t.lastEventAt??t.startedAt)}function tc(e,t=null){if(!Array.isArray(e)||e.length===0)return null;const s=i=>i.find(r=>{var d;if(typeof r.canStartNow=="boolean")return r.canStartNow;const a=r.queueState,l=r.playbackState??null,c=((d=r.autoContinue)==null?void 0:d.status)??null;return a==="blocked"||a==="running"||a==="completed"||l==="blocked"||l==="running"||l==="completed"||c==="running"||c==="stopping"?!1:a==="queued"||a==="idle"})??null;if(t&&t.trim().length>0){const i=e.filter(a=>a.initiativeId===t),r=s(i);if(r)return r}return s(e)}function nc(e){const t=e==null?void 0:e.run;if(!t)return null;const s=typeof t.activeRunId=="string"?t.activeRunId.trim():"";if(s)return s;if(Array.isArray(t.activeSliceRunIds)){for(const r of t.activeSliceRunIds)if(typeof r=="string"&&r.trim().length>0)return r.trim()}return(typeof t.lastRunId=="string"?t.lastRunId.trim():"")||null}function sc(e){var i;const t=((i=e.autoContinue)==null?void 0:i.updatedAt)??e.updatedAt??null;if(!t)return 0;const s=Date.parse(t);return Number.isFinite(s)?s:0}function ux(e){const t=e.toLowerCase();return t==="blocked"||t==="failed"?"blocked":t==="running"||t==="active"||t==="in_progress"?"working":t==="pending"||t==="queued"?"waiting":t==="completed"||t==="done"?"done":"idle"}function mx(e){if(ki(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function px(e){if(ki(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function fx(e){const t=e.metadata;return t==null||typeof t!="object"?!1:t.mock===!0}function hx(e){return sx.test(e)}function $r(e,t){for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function gx(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function xx(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function yx(e){const t=e.get("workspace_id")??e.get("workspaceId")??e.get("command_center_id")??e.get("commandCenterId")??e.get("project_id")??e.get("projectId")??e.get("center");return!t||t.trim().length===0?null:t.trim()}function bx(e,t){gs(e,t)}function vx(e){e.delete("workspace_id"),e.delete("workspaceId"),e.delete("command_center_id"),e.delete("commandCenterId"),e.delete("project_id"),e.delete("projectId"),e.delete("center")}function wx(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=yx(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Ka);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function kx(){const e=Lu();return e.showGate?n.jsx(jm,{state:e.state,isLoading:e.isLoading,isStarting:e.isStarting,isSubmittingManual:e.isSubmittingManual,onRefresh:e.refreshStatus,onStartPairing:e.startPairing,onSubmitManualKey:e.submitManualKey,onBackToPairing:e.backToPairing,onUseManualKey:e.setManualMode,onSkip:e.skipGate}):n.jsx(Kp,{children:n.jsx(_x,{onboarding:e})})}function Ix(e){const t=e.toLowerCase();return/market|email|campaign|content|brand/.test(t)?"Marketing":/product|feature|ux|discovery/.test(t)?"Product":/engineer|infra|platform|api|backend|frontend|dev/.test(t)?"Engineering":"Program"}function Nx(e){return e==="Marketing"?["Brief","Draft","Review","Ship"]:e==="Engineering"?["Spec","Dev","QA","Deploy"]:e==="Product"?["Brief","Define","Build","Ship"]:["Plan","Build","Review","Ship"]}function ic(e){const t=(e??"").trim().toLowerCase();return t?t==="critical"||t==="p0"||t==="urgent"?0:t==="high"||t==="p1"?1:t==="medium"||t==="normal"||t==="p2"?2:t==="low"||t==="p3"?3:4:4}function rc(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function jx(){return n.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-lg border border-strong bg-white/[0.04] p-0.5",children:n.jsx("img",{src:aa,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function Ax(){const{state:e}=Ec();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Zg,{})}):null}function _x({onboarding:e}){var cr;const[t,s]=o.useState(()=>zi()),[i,r]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(qr)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Na)==="1"}catch{return!1}}),[c,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,p]=o.useState(()=>wx()),h=o.useCallback(f=>{d(f);try{localStorage.setItem("orgx-dashboard-view",f)}catch{}},[]),{data:y=[]}=ei({queryKey:["workspace-options",t?"demo":"live",e.state.hasApiKey?"auth":"anon",e.state.connectionVerified?"verified":"unverified",u??"__all__"],queryFn:async()=>{if(t)return[];const f=new URLSearchParams;f.set("type","command_center"),f.set("limit","50");const j=await fetch(`/orgx/api/entities?${f.toString()}`,{headers:Ot({workspaceId:u})});if(!j.ok)return[];const F=await j.json().catch(()=>null),C=Array.isArray(F==null?void 0:F.data)?F.data:[],m=[];for(const x of C){if(!x||typeof x!="object"||Array.isArray(x))continue;const v=$r(x,["id"]);if(!v)continue;const I=$r(x,["status","priority"]);if(!gx(I))continue;const S=$r(x,["title","name"])??(v.length>10?`${v.slice(0,8)}…`:v),Q=x.is_default===!0,J=xx({title:S,isDefault:Q}),ze=$r(x,["created_at"]);m.push({id:v,title:J,status:I,isDefault:Q,createdAt:ze})}return m.sort((x,v)=>{if(x.isDefault!==v.isDefault)return x.isDefault?-1:1;const I=Zt(x.createdAt)-Zt(v.createdAt);return I!==0?I:x.title.localeCompare(v.title)}),m},staleTime:6e4}),g=o.useMemo(()=>{var f;return u?((f=y.find(j=>j.id===u))==null?void 0:f.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,y]),w=o.useMemo(()=>!u||y.some(f=>f.id===u)?y:[{id:u,title:g,status:null,isDefault:!1,createdAt:null},...y],[u,g,y]);o.useEffect(()=>{u&&y.length!==0&&(y.some(f=>f.id===u)||p(null))},[u,y]),t||e.state.hasApiKey&&e.state.connectionVerified;const N=o.useMemo(()=>c==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[c]),{data:k,isLoading:T,error:D,refetch:b,approveDecision:_,rejectDecision:H,approveAllDecisions:A,bulkDecisionAction:O,decisionMutation:se}=du({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...N}),M=t||i,L=o.useMemo(()=>M?k.sessions.nodes:k.sessions.nodes.filter(f=>!mx(f)),[k.sessions.nodes,M]),ae=o.useMemo(()=>k.activity.filter(f=>!(!M&&px(f)||!a&&fx(f))),[k.activity,M,a]),be=k.connection==="connected"||k.decisions.length>0,[ie,P]=o.useState(null),[xe,ne]=o.useState(!1),[K,G]=o.useState(null),[le,Le]=o.useState(null),[Me,me]=o.useState(null),[Ne,E]=o.useState(null),[W,V]=o.useState(null),[Y,Ie]=o.useState("24h"),[De,he]=o.useState({startIso:null,endIso:null}),je=o.useRef(new Set),[R,Ae]=o.useState(null),[Se,Ee]=o.useState(null),[$e,ye]=o.useState(null),[mt,Ce]=o.useState(null),_e=o.useRef(null),ee=o.useCallback(f=>{_e.current&&clearTimeout(_e.current),Ce(f),_e.current=setTimeout(()=>Ce(null),4e3)},[]),[dt,yt]=o.useState(!1),[Be,te]=o.useState(!1),[B,oe]=o.useState([]),pe=o.useRef(null),Pe=o.useRef(null),[We,rt]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[ge,Ve]=o.useState(!1),[ce,X]=o.useState(null),[Te,Ze]=o.useState("activity"),[at,pt]=o.useState("initiatives"),[ct,ht]=o.useState("next_up"),rn=o.useCallback(f=>{if(Ze(f),f==="initiatives"){pt("initiatives"),ht("next_up");return}f==="decisions"&&(pt("initiatives"),ht("in_progress"),ve("needs_attention"))},[]),[Z,ve]=o.useState("all"),Oe=o.useMemo(()=>Array.isArray(k.sliceRuns)?k.sliceRuns:[],[k.sliceRuns]),Ge=o.useMemo(()=>{var m,x,v,I;const f=Oe.filter(S=>{const Q=Lt(S.status);return Q==="completed"||Q==="archived"});if(f.length===0)return[];const j=new Map;for(const S of L){const Q=(m=S.runId)==null?void 0:m.trim();Q&&!j.has(Q)&&j.set(Q,S);const J=(x=S.id)==null?void 0:x.trim();J&&!j.has(J)&&j.set(J,S)}const F=new Map;for(const S of L){const Q=(v=S.initiativeId)==null?void 0:v.trim(),J=(I=S.groupLabel)==null?void 0:I.trim();!Q||!J||F.has(Q)||F.set(Q,J)}const C=[];for(const S of f){const Q=(S.runId??S.sliceRunId??"").trim();if(!Q)continue;const J=j.get(Q)??j.get(S.sliceRunId)??null,ze=S.initiativeId??(J==null?void 0:J.initiativeId)??null,qe=ae.filter(tt=>{const Dt=Dr(tt),cn=Yl(tt);return!!(Dt&&(Dt===Q||Dt===S.sliceRunId)||cn&&cn===S.sliceRunId)}).sort((tt,Dt)=>Zt(tt.timestamp)-Zt(Dt.timestamp)),it=[...qe].reverse().map(tt=>wi(tt)).find(tt=>tt.update||tt.outcomes.length>0||tt.nextUp.length>0)??null,Ke=(it==null?void 0:it.update)??S.statusExplainer??S.lastEventSummary??(J==null?void 0:J.lastEventSummary)??null,Ye=(it==null?void 0:it.outcomes[0])??(S.artifactCount>0?`${S.artifactCount} artifact${S.artifactCount===1?"":"s"} ready for the next step.`:null),ot=Array.from(new Set(qe.flatMap(tt=>wi(tt).nextUp).filter(Boolean))).slice(0,5);C.push({key:`completed:${S.sliceRunId}`,runId:Q,title:S.workstreamTitle??(J==null?void 0:J.title)??`Completed slice ${S.sliceRunId.slice(0,8)}`,statusExplainer:S.statusExplainer??S.lastEventSummary??(J==null?void 0:J.lastEventSummary)??null,whatChanged:Ke,whatThisUnlocked:Ye,nextUp:ot,initiativeTitle:ze?F.get(ze)??ze:null,workstreamTitle:S.workstreamTitle??(J==null?void 0:J.title)??null,scope:S.scope??null,taskIds:Array.isArray(S.taskIds)?S.taskIds:[],milestoneIds:Array.isArray(S.milestoneIds)?S.milestoneIds:[],artifacts:Array.isArray(S.artifacts)?S.artifacts:[],artifactCount:S.artifactCount??0,completedAt:S.completedAt??S.updatedAt??S.lastEventAt??(J==null?void 0:J.updatedAt)??(J==null?void 0:J.lastEventAt)??null,timelineEvents:qe})}return C.sort((S,Q)=>Zt(Q.completedAt)-Zt(S.completedAt)),C},[Oe,ae,L]),Re=Ge.length,[He,Ue]=o.useState(null),ft=o.useCallback(f=>{const j=Oe.find(F=>F.initiativeId===f.initiativeId&&F.workstreamId===f.workstreamId)??null;Ue({source:"queue",item:f,linkedSliceRun:j})},[Oe]),Ht=o.useCallback((f,j)=>{Ue({source:"in_progress",row:f,sliceRun:j})},[]),gt=o.useCallback(f=>{Ue({source:"needs_input",sliceRun:f})},[]),vt=o.useCallback(async(f,j)=>{ee("Slice accepted and marked complete."),b()},[b,ee]),Tt=o.useCallback(async(f,j)=>{ee("Changes requested — feedback posted.")},[ee]),Ut=o.useCallback(async(f,j,F)=>{await _(f,{optionId:j,...F?{note:F}:{}}),ee("Decision resolved.")},[_,ee]),nt=Zu({projectId:u,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:k.snapshotVersion}),et=em({authToken:null,embedMode:!1,projectId:u}),{model:$t,actions:St}=sm({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Mt=o.useMemo(()=>$t.items.filter(f=>f.kind==="failure_diagnostic"),[$t.items]),Ct=o.useMemo(()=>({...$t,items:Mt,total:Mt.length}),[Mt,$t]),[Kt,vn]=o.useState(null),[ys,Kn]=o.useState(0),Vn=o.useCallback(f=>{vn(f);const j=Mt.findIndex(F=>F.id===f.id);Kn(j>=0?j:0)},[Mt]),Gn=o.useCallback(f=>{if(Mt.length===0)return;const j=(ys+f+Mt.length)%Mt.length;Kn(j),vn(Mt[j]??null)},[ys,Mt]),Xn=nt,Es=o.useMemo(()=>{var f;return((f=Xn.summary)==null?void 0:f.visibleTotal)??cx(Xn.items)},[Xn.items,(cr=Xn.summary)==null?void 0:cr.visibleTotal]),wn=o.useMemo(()=>{var m;const f=nt.items.filter(x=>x.autoContinue);if(f.length===0)return null;const j=[...f].sort((x,v)=>sc(v)-sc(x)),F=j.find(x=>{var v,I;return((v=x.autoContinue)==null?void 0:v.status)==="running"||((I=x.autoContinue)==null?void 0:I.status)==="stopping"})??null;if(F)return{item:F,state:((m=F.autoContinue)==null?void 0:m.status)==="stopping"?"stopping":"running"};const C=j.find(x=>{var v,I;return((v=x.autoContinue)==null?void 0:v.stopReason)==="blocked"||((I=x.autoContinue)==null?void 0:I.stopReason)==="error"})??null;return C?{item:C,state:"blocked"}:null},[nt.items]),Qt=(wn==null?void 0:wn.item)??null,an=(wn==null?void 0:wn.state)??"idle",hn=an==="running"||an==="stopping",Rs=an==="blocked"?"blocked":hn?"active":"idle",Qn=an==="blocked"?"Hold":hn?"On":"Off",bs=an==="blocked"?"Resolve blockers, then resume autopilot":hn?"Stop autopilot":"Start autopilot",ti=an==="blocked"?"amber":"teal",Ls=o.useMemo(()=>{var f,j;return Qt?{state:an,reason:((f=Qt.autoContinue)==null?void 0:f.stopReason)??Qt.blockReason??null,activeRunId:((j=Qt.autoContinue)==null?void 0:j.activeRunId)??null,activeWorkstreamTitle:Qt.workstreamTitle??null}:null},[Qt,an]);o.useEffect(()=>{if(!(typeof window>"u"))try{t?(window.localStorage.setItem(Xr,"1"),window.localStorage.removeItem(Qr)):(window.localStorage.removeItem(Xr),window.localStorage.removeItem(Qr))}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{i?window.localStorage.setItem(qr,"1"):window.localStorage.removeItem(qr)}catch{}},[i]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(Na,"1"):window.localStorage.removeItem(Na)}catch{}},[a]),o.useEffect(()=>{a||Ve(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(Ka,u):window.localStorage.removeItem(Ka)}catch{}try{const f=new URL(window.location.href);u?bx(f.searchParams,u):vx(f.searchParams),f.searchParams.delete("initiative"),f.searchParams.delete("initiative_id"),f.searchParams.delete("project"),window.history.replaceState(null,"",`${f.pathname}${f.search}${f.hash}`)}catch{}}},[u]);const Vt=o.useCallback((f,j)=>{rt(F=>({open:!0,tab:f??F.tab,focusAgentDomain:(j==null?void 0:j.focusAgentDomain)??null}))},[]),Cn=o.useCallback(f=>{if(s(f),!(typeof window>"u"))try{const j=new URL(window.location.href);f?(j.searchParams.set("sandbox","1"),j.searchParams.delete("demo")):(j.searchParams.delete("sandbox"),j.searchParams.delete("demo")),window.history.replaceState(null,"",`${j.pathname}${j.search}${j.hash}`)}catch{}},[]),Yn=o.useCallback(()=>{Vt("orgx")},[Vt]),z=o.useCallback(()=>{sn(()=>import("./BIW2kmQr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),we=e.state.connectionVerified&&!t,{data:ke,isLoading:Fe}=Tc(we,u),{data:wt,isLoading:jt}=Hp(we,u),{data:st=[]}=ei({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Yt,At]=o.useState(null),[Jn,Zn]=o.useState(""),[Et,dn]=o.useState(!1),as=o.useCallback((f,j)=>{At({type:f,initiativeId:j}),Zn(""),dn(!1)},[]),es=o.useCallback(()=>{At(null),Zn(""),dn(!1)},[]),Ds=o.useCallback(()=>{Le(null)},[]),$s=o.useCallback(()=>{me(null),E(null)},[]),os=o.useCallback(()=>{ye(null)},[]);o.useEffect(()=>{var F;const f=((F=L[0])==null?void 0:F.id)??null;if(!f){ie!==null&&P(null);return}if(ie===null){P(f);return}L.some(C=>C.id===ie)||P(f)},[L,ie]),o.useEffect(()=>{if(!le)return;L.some(j=>j.id===le)||Le(null)},[le,L]);const kn=o.useCallback(f=>{sn(()=>import("./BGqqzQfq.js"),__vite__mapDeps([14,1,5,2,10,11,12,13])),P(f),ne(!0),G(null),Le(f),me(null),E(null)},[]);o.useEffect(()=>{if(!W)return;const f=L.find(j=>j.id===W||j.runId===W)??null;f&&(kn(f.id),V(null))},[kn,W,L]);const Zi=o.useCallback(f=>{sn(()=>import("./BGqqzQfq.js"),__vite__mapDeps([14,1,5,2,10,11,12,13])),P(f.id),ne(!0),Le(f.id),me(f.workstreamId??null),E(f.title),G({workstreamId:f.workstreamId??null,text:`Intervention requested for "${f.title}". `}),ee(`Opened intervention composer for ${f.title}.`)},[]),ls=o.useCallback(f=>{const j=f.trim();if(!j)return;const F=L.find(C=>C.runId===j||C.id===j)??null;if(!F){ee("Session not found — it may have ended or not started yet.");return}kn(F.id),ee(`Focused session: ${F.title}`)},[L,kn,ee]),da=o.useCallback(f=>{var C;const j=(C=f.id)==null?void 0:C.trim();if(!j)return;const F=Dr(f);if(F){const m=L.find(x=>x.runId===F||x.id===F)??null;m&&(P(m.id),Le(m.id))}h("activity"),Ze("activity"),ne(!1),Ae(j),ee("Opened activity detail from session timeline.")},[L,h]),Pt=o.useMemo(()=>L.find(f=>f.id===le)??null,[le,L]),Pn=o.useMemo(()=>{var F,C;const f=((F=Pt==null?void 0:Pt.runId)==null?void 0:F.trim())??"",j=((C=Pt==null?void 0:Pt.id)==null?void 0:C.trim())??"";return!f||!j?[]:f===j?[f]:[f,j]},[Pt==null?void 0:Pt.id,Pt==null?void 0:Pt.runId]),ni=o.useMemo(()=>{const f=new Set;for(const j of Pn){const F=j.trim();F.length>0&&f.add(F)}return f},[Pn]),Ii=o.useMemo(()=>{const f=new Map;for(const j of L){const F=j.workstreamId??null;j.runId&&f.set(j.runId,F),j.id&&f.set(j.id,F)}return f},[L]),ts=o.useMemo(()=>{const f=Pn.length>0?Pn.join("|"):"*",j=(Me==null?void 0:Me.trim())||"*",F=($e==null?void 0:$e.trim())||"*";return`${f}::${j}::${F}`},[Me,$e,Pn]),ua=o.useCallback(f=>{je.current.add(ts),Ie(f)},[ts]);o.useEffect(()=>{if(je.current.has(ts)||T)return;const f=Date.now(),j=ae.filter(m=>{const x=Dr(m);if(ni.size>0&&(!x||!ni.has(x)))return!1;if(Me){const v=Jl(m);if((Zl(v,["workstreamId","workstream_id"])??(x?Ii.get(x)??null:null))!==Me)return!1}if($e){const v=Jl(m);if((Zl(v,["agentName","agent_name"])??m.agentName)!==$e)return!1}return!0});if(j.length===0)return;const C=["live","24h","7d","all"].find(m=>{const x=Yi(m,f);return j.some(v=>{const I=Zt(v.timestamp);return I?x===null||I>=x:!1})})??"all";je.current.add(ts),C!==Y&&Ie(C)},[Me,ae,ts,Y,Ii,$e,T,ni]);const vs=bu({seed:ae,timeFilterId:Y,customSinceIso:Y==="custom"?De.startIso:null,customUntilIso:Y==="custom"?De.endIso:null,runId:(Pt==null?void 0:Pt.runId)??null,projectId:u,pageSize:50,demoMode:t}),on=o.useMemo(()=>L.find(f=>f.id===ie)??null,[L,ie]),er=o.useMemo(()=>Cc({sessions:L,sliceRuns:Oe}),[Oe,L]),Ps=typeof k.runningWorkSlices=="number"&&Number.isFinite(k.runningWorkSlices)?Math.max(0,Math.floor(k.runningWorkSlices)):er.length,un=o.useMemo(()=>ox(Oe,k.needsInputItems),[Oe,k.needsInputItems]),$=o.useMemo(()=>{const f=Array.isArray(k.needsInputItems)?k.needsInputItems.length:0;return f>0?f:typeof k.needsInputTotal=="number"&&Number.isFinite(k.needsInputTotal)?Math.max(Math.max(0,Math.floor(k.needsInputTotal)),un.length):un.length},[k.needsInputItems,k.needsInputTotal,un.length]),tr=o.useMemo(()=>be?k.decisions.length:0,[k.decisions.length,be]),cs=o.useMemo(()=>be?lx(k.decisions,un.map(f=>f.item)):0,[k.decisions,be,un]),mn=$+cs,On=Ps,Os=o.useMemo(()=>$,[$]);o.useMemo(()=>L.filter(f=>f.status==="failed").length,[L]);const ds=o.useMemo(()=>{if(typeof k.completedTodayTotal=="number"&&Number.isFinite(k.completedTodayTotal))return Math.max(0,Math.floor(k.completedTodayTotal));const f=new Date;return L.filter(j=>j.status==="completed"&&dx(j.updatedAt??j.lastEventAt??j.startedAt,f)).length},[k.completedTodayTotal,L]);o.useMemo(()=>{const f=mn;return[{id:"active",label:"Running",value:On,color:On>0?q.lime:q.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:f,color:f>0?q.amber:q.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:ds,color:q.teal,icon:"session"}]},[On,ds,mn]),o.useMemo(()=>k.decisions.length>0?Math.max(0,...k.decisions.map(f=>f.waitingMinutes)):0,[k.decisions]);const Qe=o.useMemo(()=>D?ax(D):null,[D]),pn=o.useMemo(()=>{const f=[];if(Qe){const j=Qe.action==="refresh"&&typeof b=="function";f.push({id:`stream-error:${D}`,kind:"error",icon:"notification",title:Qe.title,message:Qe.message,actionLabel:j?"Refresh":"Settings",onAction:j?()=>void b():()=>Vt("orgx")})}return k.connection!=="connected"&&f.push({id:`connection:${k.connection}`,kind:k.connection==="disconnected"?"error":"info",icon:"notification",title:k.connection==="disconnected"?"Connection lost":"Reconnecting",message:k.connection==="disconnected"?"Live connection is offline. Initiatives and Next Up may stay stale until reconnect.":"Live connection is recovering. Fresh updates will resume automatically.",actionLabel:"Reconnect",onAction:Yn}),mt&&f.push({id:`ops:${mt}`,kind:"info",icon:/decision/i.test(mt)?"decision":"workstream",title:"Update",message:mt}),f},[k.connection,k.outbox.lastReplayError,k.outbox.pendingTotal,k.outbox.replayStatus,D,Qe,Yn,b,Vt,mt]);o.useEffect(()=>{const f=new Set(pn.map(j=>j.id));oe(j=>j.filter(F=>f.has(F)))},[pn]);const re=o.useMemo(()=>pn.filter(f=>!B.includes(f.id)),[B,pn]),si=tr,ws=mn,In=o.useCallback((f,j)=>{h(f),pt("initiatives"),Ze("initiatives"),ht("in_progress"),ve("needs_attention"),j!=null&&j.closeNotifications&&te(!1)},[h]),Ni=o.useCallback(f=>{In("mission-control",f)},[In]),Ft=o.useCallback(f=>{In("activity",f)},[In]),U=o.useCallback(f=>{oe(j=>j.includes(f)?j:j.concat(f))},[]),_t=o.useCallback(()=>{oe(pn.map(f=>f.id))},[pn]);o.useEffect(()=>{if(!Be)return;const f=F=>{var m,x;const C=F.target;C&&((m=Pe.current)!=null&&m.contains(C)||(x=pe.current)!=null&&x.contains(C)||te(!1))},j=F=>{F.key==="Escape"&&te(!1)};return document.addEventListener("mousedown",f),document.addEventListener("touchstart",f),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("touchstart",f),document.removeEventListener("keydown",j)}},[Be]);const Bt=o.useMemo(()=>{var F;const f=new Map;for(const C of L){const m=C.initiativeId??C.groupId??"unscoped",x=C.groupLabel&&C.groupLabel.trim().length>0?C.groupLabel:C.initiativeId??"Unscoped Initiative",v=Ix(x),I=f.get(m)??{id:m,name:x,category:v,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(C.progress!==null&&(I.progressTotal+=C.progress,I.progressCount+=1),I.statusCounts[C.status]=(I.statusCounts[C.status]??0)+1,C.agentName&&(I.allAgents.add(C.agentName),["running","queued","pending","blocked"].includes(C.status)&&I.activeAgents.add(C.agentName)),C.workstreamId){const S=k.sessions.groups.find(J=>J.id===C.workstreamId),Q=((F=S==null?void 0:S.label)==null?void 0:F.trim())||C.workstreamId;I.workstreams.set(C.workstreamId,Q)}I.latestEpoch=Math.max(I.latestEpoch,Zt(C.updatedAt??C.lastEventAt??C.startedAt)),f.set(m,I)}const j=[];for(const C of f.values()){const m=C.progressCount>0?Math.round(C.progressTotal/C.progressCount):C.statusCounts.completed?100:C.statusCounts.running?55:0,x=C.category,v=Nx(x),I=Math.round(Math.max(0,Math.min(100,m))/100*(v.length-1)),S=(C.statusCounts.blocked??0)>0,Q=(C.statusCounts.completed??0)>0&&(C.statusCounts.running??0)===0&&(C.statusCounts.queued??0)===0&&(C.statusCounts.pending??0)===0&&(C.statusCounts.blocked??0)===0&&(C.statusCounts.paused??0)===0,J=!Q&&!S&&(C.statusCounts.paused??0)>0&&(C.statusCounts.running??0)===0&&(C.statusCounts.queued??0)===0&&(C.statusCounts.pending??0)===0,ze=(C.statusCounts.running??0)+(C.statusCounts.active??0)+(C.statusCounts.in_progress??0),qe=(C.statusCounts.queued??0)+(C.statusCounts.pending??0),it=C.workstreams.size,Ke=`${it} workstream${it===1?"":"s"}`,Ye=it===0?"No workstreams linked yet.":Q?`${Ke} completed.`:S?`${Ke} linked · resolve blockers to continue.`:J?`${Ke} linked · initiative is paused.`:ze>0?`${ze} workstream${ze===1?"":"s"} active right now.`:qe>0?`${qe} workstream${qe===1?"":"s"} queued to start.`:`${Ke} linked · ready to run.`,ot=v.map((tt,Dt)=>{let cn="upcoming";return(Q||Dt<I)&&(cn="completed"),Dt===I&&!Q&&(cn=S?"warning":"current"),{name:tt,status:cn}});j.push({id:C.id,name:C.name,status:Q?"completed":S?"blocked":J?"paused":"active",rawStatus:Q?"completed":S?"blocked":J?"paused":"active",category:x,health:Math.max(0,Math.min(100,m)),phases:ot,currentPhase:Q?v.length-1:I,daysRemaining:0,targetDate:null,createdAt:C.latestEpoch>0?new Date(C.latestEpoch).toISOString():null,updatedAt:C.latestEpoch>0?new Date(C.latestEpoch).toISOString():null,activeAgents:C.activeAgents.size,totalAgents:C.allAgents.size,avatars:Array.from(C.activeAgents).slice(0,3),description:Ye,workstreams:Array.from(C.workstreams.entries()).map(([tt,Dt])=>({id:tt,name:Dt,status:"active"}))})}return j.sort((C,m)=>{const x=C.status==="blocked"?0:C.status==="active"?1:2,v=m.status==="blocked"?0:m.status==="active"?1:2;return x!==v?x-v:m.health-C.health})},[L,k.sessions.groups]),us=o.useMemo(()=>{const f=(C,m)=>{var I,S;const x=typeof m.description=="string"&&m.description.trim().length>0?m.description:null,v=typeof C.description=="string"&&C.description.trim().length>0?C.description:null;return{...C,...m,health:m.health>0?m.health:C.health,activeAgents:Math.max(C.activeAgents,m.activeAgents),totalAgents:Math.max(C.totalAgents,m.totalAgents),avatars:(I=C.avatars)!=null&&I.length?C.avatars:m.avatars,workstreams:(S=C.workstreams)!=null&&S.length?C.workstreams:m.workstreams,description:x??v??void 0,rawStatus:m.rawStatus??C.rawStatus??null,targetDate:m.targetDate??C.targetDate??null,createdAt:m.createdAt??C.createdAt??null,updatedAt:m.updatedAt??C.updatedAt??null}},j=new Map;for(const C of Bt)j.set(C.id,C);for(const C of[...wt??[],...ke??[]]){if(!M&&ki(C.id)){j.delete(C.id);continue}const m=C.rawStatus??C.status;if(!rc(m)){j.delete(C.id);continue}const x=j.get(C.id);j.set(C.id,x?f(x,C):C)}const F=new Set(st);return Array.from(j.values()).filter(C=>!F.has(C.id)).filter(C=>rc(C.rawStatus??C.status)).sort((C,m)=>{const x=J=>J==="blocked"?0:J==="active"?1:J==="paused"?2:3,v=x(C.status)-x(m.status);if(v!==0)return v;const I=ic(C.priority)-ic(m.priority);if(I!==0)return I;const S=Zt(m.updatedAt)-Zt(C.updatedAt);if(S!==0)return S;const Q=m.health-C.health;return Q!==0?Q:C.name.localeCompare(m.name)})},[Bt,ke,M,wt,st]),Jt=o.useMemo(()=>[...L].filter(f=>f.title.trim().length>0).sort((f,j)=>Zt(j.updatedAt??j.lastEventAt??j.startedAt)-Zt(f.updatedAt??f.lastEventAt??f.startedAt))[0]??null,[L]),nr=!t&&e.state.connectionVerified&&!T&&!Fe&&!jt&&us.length===0,gn=o.useMemo(()=>{const f={};for(const j of us)j.id&&j.name&&(f[j.id]=j.name);return f},[us]),ma=o.useMemo(()=>{if(!Pt)return null;const f=Pt.agentName,j=Pt.title;if(f){const F=ae.find(C=>{var m;return C.runId===Pt.runId&&((m=C.summary)==null?void 0:m.trim())});if(F!=null&&F.summary){const C=F.summary.trim().length>40?F.summary.trim().slice(0,40)+"…":F.summary.trim();return`${f}: ${C}`}return f}if(j){const F=j.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(F.length>0)return F}return j??null},[ae,Pt]),sr=o.useMemo(()=>{const f=new Map;for(const j of L){const F=(j.agentId??"").trim()||`name:${(j.agentName??"").trim()}`,C=(j.agentName??"").trim()||(j.agentId??"").trim();if(!C)continue;const m=j.updatedAt??j.lastEventAt??j.startedAt??"unknown",x=Zt(m),v=x?Math.max(0,Math.floor((Date.now()-x)/6e4)):Number.MAX_SAFE_INTEGER,I=f.get(F),S={id:F,name:C,role:"Agent",status:ux(j.status),task:j.title??null,progress:j.progress??null,lastActive:m,lastActiveMinutes:v};(!I||Zt(S.lastActive)>Zt(I.lastActive))&&f.set(F,S)}return Array.from(f.values())},[L]),ns=o.useCallback(async(f,j)=>{const F=await f.json().catch(()=>null),C=typeof(F==null?void 0:F.error)=="string"&&F.error.trim()||typeof(F==null?void 0:F.message)=="string"&&F.message.trim()||`${j} (${f.status})`;return/unknown api endpoint/i.test(C)?`${j}. This route is unavailable in the running plugin build.`:Xt(C)},[]),ir=o.useCallback(async()=>{if(L.length===0){ee("No sessions available to continue.");return}const f=[...L].sort(Ha)[0];if(P(f.id),Le(f.id),me(null),E(null),["blocked","pending","queued"].includes(f.status)){const j=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})});if(!j.ok)throw new Error(await ns(j,`Failed to resume ${f.title}`))}ee(`Focused highest priority session: ${f.title}`),await b()},[ns,b,L]),ms=o.useCallback((f,j)=>!f||f.trim().length===0?j:Xt(f.trim())||j,[]),ut=o.useCallback(async()=>{const f=tc(nt.items);if(!f){ee("No startable Next Up workstream is available."),h("mission-control");return}const j=await nt.playWorkstream({initiativeId:f.initiativeId,workstreamId:f.workstreamId,agentId:f.runnerAgentId});ht("in_progress"),ve("all"),pt("initiatives"),Le(null),me(f.workstreamId),E(f.workstreamTitle),ye(null),typeof j.sessionId=="string"&&j.sessionId.trim().length>0&&V(j.sessionId.trim()),ee(j.dispatchMode==="pending"?`Dispatching ${f.workstreamTitle}…`:`Started ${f.workstreamTitle}.`),await Promise.all([nt.refetch(),b()])},[b,nt,h]),qs=o.useCallback(async(f=null)=>{const j=tc(nt.items,f);if(!j){ee("No startable initiative is ready for Autopilot yet."),h("mission-control");return}await et.move({initiativeId:j.initiativeId,workstreamId:j.workstreamId,placement:"top"});const F=await nt.startWorkstreamAutoContinue({initiativeId:j.initiativeId,workstreamId:j.workstreamId,agentId:j.runnerAgentId,scope:"initiative"});ht("in_progress"),ve("all"),pt("initiatives"),Le(null);const C=nc(F);C?V(C):(me(j.workstreamId),E(j.workstreamTitle)),ee(C?`Autopilot started for ${j.initiativeTitle}.`:`Autopilot started for ${j.initiativeTitle}; dispatching from ${j.workstreamTitle}.`),await Promise.all([nt.refetch(),b()])},[b,et,nt,h]),kt=o.useCallback(async()=>{yt(!0);try{if(!Qt||!hn){const f=an==="blocked"?(Qt==null?void 0:Qt.initiativeId)??null:null;await qs(f);return}await nt.stopInitiativeAutoContinue({initiativeId:Qt.initiativeId}),ee(`Autopilot stopped for ${Qt.initiativeTitle}.`),await Promise.all([nt.refetch(),b()])}finally{yt(!1)}},[hn,Qt,an,b,nt,qs]),ks=o.useCallback(async f=>{const j=(f.initiativeId??"").trim(),F=(f.workstreamId??"").trim();if(!j||!F)throw new Error("Missing initiative/workstream metadata for this session.");const C=await nt.playWorkstream({initiativeId:j,workstreamId:F,agentId:f.agentId??void 0});Le(null),me(F),E(f.title),typeof C.sessionId=="string"&&C.sessionId.trim().length>0&&V(C.sessionId.trim()),ee(C.dispatchMode==="pending"?`Dispatching ${f.title}…`:`Started ${f.title}.`),await Promise.all([nt.refetch(),b()])},[b,nt]),ji=o.useCallback(async f=>{const j=(f.initiativeId??"").trim(),F=(f.workstreamId??"").trim();if(!j||!F)throw new Error("Missing initiative/workstream metadata for this session.");const C=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:j,workstreamId:F,placement:"bottom",resetToTodo:!1})});if(!C.ok){const m=await ns(C,"Failed to pause workstream from In Progress");throw new Error(m)}ee(`Paused ${f.title} and sent it to the bottom of queue.`),await Promise.all([nt.refetch(),b()])},[ns,b,nt]),Ai=o.useCallback(async f=>{const j=(f.workstreamId??"").trim();if(!j)throw new Error("This session is missing a workstream id for intervention notes.");const F=f.text.trim();if(hx(F)){Vt("agents",{focusAgentDomain:"engineering"}),ee("Opened agent settings for engineering runtime configuration.");return}const C=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(j)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:F,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!C.ok)throw new Error(await ns(C,"Failed to submit intervention"));ee(`Intervention sent for ${f.session.title}.`),await b()},[Vt,ns,b]),rr=o.useCallback(async f=>{if(P(f.id),Le(f.id),me(null),E(null),!["running","completed","archived"].includes(f.status)){const j=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})});if(!j.ok)throw new Error(await ns(j,`Failed to dispatch ${f.title}`))}ee(`Dispatch requested: ${f.title}`),await b()},[ns,b]),xn=o.useCallback(async(f,j,F={})=>{const C=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/${j}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!C.ok){const m=await C.json().catch(()=>null);throw new Error((m==null?void 0:m.error)??`${j} failed (${C.status})`)}},[]),Tn=o.useCallback(async f=>{var m;const j=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!j.ok){const x=await j.json().catch(()=>null);throw new Error((x==null?void 0:x.error)??`Checkpoint creation failed (${j.status})`)}const F=await j.json().catch(()=>null),C=F&&"data"in F&&((m=F.data)==null?void 0:m.id)||F&&"id"in F&&F.id||null;ee(C?`Checkpoint created: ${C.slice(0,8)}`:"Checkpoint created."),await b()},[b]),pa=o.useCallback(async f=>{await xn(f,"pause",{reason:"pause_from_dashboard"}),ee(`Pause requested: ${f.title}`),await b()},[b,xn]),ar=o.useCallback(async f=>{await xn(f,"resume",{reason:"resume_from_dashboard"}),ee(`Resume requested: ${f.title}`),await b()},[b,xn]),or=o.useCallback(async f=>{await xn(f,"cancel",{reason:"restart_from_in_progress"}),await ks(f),ee(`Restarted ${f.title}.`),await b()},[ks,b,xn]),_i=o.useCallback(async f=>{await xn(f,"cancel",{reason:"cancel_from_dashboard"}),ee(`Cancel requested: ${f.title}`),await b()},[b,xn]),lr=o.useCallback(async f=>{var v;const j=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/checkpoints`,{method:"GET"});if(!j.ok){const I=await j.json().catch(()=>null);throw new Error((I==null?void 0:I.error)??`Checkpoint list failed (${j.status})`)}const F=await j.json().catch(()=>null),x=(v=(Array.isArray(F)?F:Array.isArray(F==null?void 0:F.data)?F.data:[]).map(I=>({id:typeof I.id=="string"?I.id:"",createdAt:typeof I.createdAt=="string"?I.createdAt:typeof I.created_at=="string"?I.created_at:""})).filter(I=>I.id.length>0).sort((I,S)=>Date.parse(S.createdAt)-Date.parse(I.createdAt))[0])==null?void 0:v.id;if(!x)throw new Error("No checkpoint available for rollback.");await xn(f,"rollback",{checkpointId:x,reason:"rollback_from_dashboard"}),ee(`Rollback requested for ${f.title}.`),await b()},[b,xn]),ln=o.useCallback(async()=>{var F;if(!Yt||Jn.trim().length===0||Et)return;dn(!0);const f=Yt.type,j=Jn.trim();try{const C={type:f,title:j,status:"active"};if(f==="workstream"){const x=Yt.initiativeId??(on==null?void 0:on.initiativeId)??((F=Bt[0])==null?void 0:F.id)??null;if(!x){ee("Select an initiative first to start a workstream."),dn(!1);return}C.initiative_id=x,C.parentId=x}const m=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(!m.ok){const x=await m.json().catch(()=>null);throw new Error((x==null?void 0:x.error)??`Failed to create ${f}.`)}ee(`Created ${f}: ${j}`),es(),await b()}catch(C){ee(ms(C instanceof Error?C.message:"",`Failed to create ${f}.`)),dn(!1)}},[es,Et,Yt,Jn,Bt,b,on==null?void 0:on.initiativeId]),Mn=o.useCallback(f=>{At({type:"initiative"}),Zn((f==null?void 0:f.trim())??""),dn(!1)},[]),ii=o.useCallback(()=>{Mn()},[Mn]),ri=o.useCallback(f=>{as("workstream",f)},[as]);o.useCallback(()=>{var f;return ri((on==null?void 0:on.initiativeId)??((f=Bt[0])==null?void 0:f.id)??null)},[Bt,on==null?void 0:on.initiativeId,ri]);const En=o.useCallback(f=>{const j=[...L].filter(F=>(F.initiativeId??F.groupId)===f.id).sort(Ha)[0];j&&(P(j.id),Le(j.id),me(null),E(null),ee(`Focused initiative: ${f.name}`))},[L]),Is=o.useCallback(f=>{const j=Bt.find(F=>F.id===f)??us.find(F=>F.id===f)??null;j&&En(j)},[En,Bt,us]),qn=o.useCallback(f=>{const j=(f??"").trim();h("activity"),pt("initiatives"),Ze("initiatives"),ht("in_progress"),ve("needs_attention"),Ee(j.length>0?j:null),ee(j.length>0?"Reviewing pending decision.":"Review needs attention.")},[h]),ai=o.useCallback(f=>{const j=new Set,F=(f.runId??"").trim();F.length>0&&j.add(F),j.add(f.sliceRunId);const C=new Map;for(const S of ae){const Q=Dr(S),J=Yl(S);(Q&&j.has(Q)||J&&J===f.sliceRunId)&&C.set(S.id,S)}const m=Array.from(C.values()),x=S=>{const Q=S.type.trim().toLowerCase();let J=0;return(Q==="decision_requested"||Q==="blocker_created")&&(J+=80),(Q==="run_failed"||Q==="autopilot_stopped")&&(J+=70),(Q.includes("slice_completed")||Q.includes("completed"))&&(J+=60),Q.includes("artifact")&&(J+=55),(Q.includes("progress")||Q.includes("update"))&&(J+=35),J+=Math.floor(Zt(S.timestamp)/1e3),J};m.sort((S,Q)=>x(Q)-x(S));const v=m[0]??null;h("activity"),Ze("activity"),pt("initiatives");const I=(F?L.find(S=>S.runId===F||S.id===F)??null:null)??(f.initiativeId&&f.workstreamId?L.find(S=>S.initiativeId===f.initiativeId&&S.workstreamId===f.workstreamId)??null:null);if(I?(P(I.id),Le(I.id),me(null),E(null)):f.workstreamId&&(Le(null),me(f.workstreamId),E(f.workstreamTitle??"Work slice")),v!=null&&v.id){Ae(v.id),ee(`Reviewing activity for ${f.workstreamTitle??"work slice"}.`);return}if(f.primaryAction==="resolve_decision"){qn();return}if(F.length>0){ls(F),ee("Opened the related work session. Timeline details were unavailable.");return}ee("No activity details were found for this slice yet.")},[ae,ls,qn,L,h]);return o.useCallback(f=>{const j=new Set(f),F=[...L].filter(C=>j.has(C.status)).sort(Ha)[0];if(!F){ee("No matching sessions for that metric right now.");return}kn(F.id),Ze("activity")},[L,kn]),o.useCallback(f=>{c==="activity"&&(f==="sessions"||f==="active"||f==="blocked"||f==="failed"||f==="decisions"||f==="outbox"||f==="handoffs")&&X(f)},[c]),T?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:q.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((f,j)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},j))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):nr?n.jsx(Bg,{workspaceLabel:g,suggestedTitle:(Jt==null?void 0:Jt.title)??null,sessionSummary:(Jt==null?void 0:Jt.lastEventSummary)??null,onCreateInitiative:()=>Mn(),onCreateFromSession:()=>Mn((Jt==null?void 0:Jt.title)??null),onOpenSandbox:()=>{Cn(!0),e.skipGate()},onOpenSettings:()=>Vt("orgx"),onRefresh:()=>{e.refreshStatus(),b()}}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor:q.background},children:[typeof window<"u"&&window.location.port==="5173"&&n.jsx("div",{className:"absolute left-1/2 top-4 z-30 -translate-x-1/2",children:n.jsxs("div",{className:"rounded-full border border-strong bg-white/[0.06] px-4 py-2 text-caption text-primary shadow-[0_10px_30px_rgba(0,0,0,0.35)] backdrop-blur",children:["Dev preview on 5173. Installed plugin runs on OpenClaw port"," ",n.jsx("a",{href:"http://127.0.0.1:18789/orgx/live/",className:"text-white underline underline-offset-4 hover:text-secondary",children:"18789"}),"."]})}),n.jsxs("header",{className:"relative z-[180] border-b border-subtle px-4 py-1.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2.5 lg:grid lg:grid-cols-[1fr_auto_1fr]",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(jx,{}),n.jsxs("h1",{className:"text-title font-semibold tracking-tight text-white sm:text-[17px]",children:["OrgX",n.jsx("span",{className:"ml-1.5 text-secondary",children:"Live"})]}),n.jsx(Am,{color:nx[k.connection],pulse:k.connection==="connected",title:[`Status: ${Xl[k.connection]??k.connection}`,k.connection==="connected"?"Meaning: receiving live updates.":k.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${ix(k.lastSnapshotAt)}`,Qe?`Details: ${Qe.message}`:null].filter(Boolean).join(`
|
|
212
|
+
`),children:Xl[k.connection]??"Unknown"}),(On>0||Os>0||si>0||ds>0)&&n.jsx(gl,{className:"hidden md:flex",running:On,blocked:Os,decisionsCount:si,completedToday:ds,onNeedsAttentionClick:()=>Ni(),onDecisionsClick:()=>Ft(),onBlockedClick:()=>{Oe.length>0?(h("mission-control"),ht("in_progress"),ve("needs_attention")):X("blocked")},onNewInitiative:ii})]}),n.jsx("div",{className:"hidden items-center justify-center lg:flex",children:n.jsxs("div",{className:"flex rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>h("activity"),"aria-pressed":c==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>h("mission-control"),onMouseEnter:z,onFocus:z,"aria-pressed":c==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:f=>{const j=f.target.value;p(j==="__all__"?null:j)},className:"control-pill h-8 min-w-[170px] appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${g}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),w.map(f=>n.jsx("option",{value:f.id,children:f.title},f.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),k.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",k.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Cn(!1),Yn()},className:"hidden rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15 sm:inline",title:"Exit guided sandbox",children:"Exit sandbox"}),n.jsxs("button",{type:"button",ref:pe,onClick:()=>te(f=>!f),title:"Notifications","aria-haspopup":"dialog","aria-expanded":Be,"aria-controls":"header-notifications-panel",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:[n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M15 17h5l-1.4-1.4a2 2 0 0 1-.6-1.4V11a6 6 0 1 0-12 0v3.2c0 .53-.21 1.04-.59 1.42L4 17h5"}),n.jsx("path",{d:"M9 17a3 3 0 0 0 6 0"})]}),re.length>0&&n.jsx("span",{className:"absolute -right-1 -top-1 inline-flex min-h-[16px] min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-micro font-semibold text-white",children:re.length})]}),a?n.jsx("button",{type:"button",onClick:()=>Ve(!0),title:"Realtime orchestrator",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 18a2.5 2.5 0 0 0 2.5-2.5v-7a2.5 2.5 0 1 0-5 0v7A2.5 2.5 0 0 0 12 18z"}),n.jsx("path",{d:"M6 12.5v2a6 6 0 0 0 12 0v-2"}),n.jsx("path",{d:"M12 20.5v2"})]})}):null,n.jsx("button",{type:"button",onClick:()=>Vt("orgx"),title:"Settings",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"}),n.jsx("path",{d:"M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.2 2.2 0 0 1-1.56 3.76 2.2 2.2 0 0 1-1.56-.64l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.1 1.63V22a2.2 2.2 0 0 1-4.4 0v-.07a1.8 1.8 0 0 0-1.1-1.63 1.8 1.8 0 0 0-2 .36l-.05.05a2.2 2.2 0 1 1-3.12-3.12l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.63-1.1H2a2.2 2.2 0 0 1 0-4.4h.07a1.8 1.8 0 0 0 1.63-1.1 1.8 1.8 0 0 0-.36-2l-.05-.05a2.2 2.2 0 1 1 3.12-3.12l.05.05a1.8 1.8 0 0 0 2 .36 1.8 1.8 0 0 0 1.1-1.63V2a2.2 2.2 0 0 1 4.4 0v.07a1.8 1.8 0 0 0 1.1 1.63 1.8 1.8 0 0 0 2-.36l.05-.05a2.2 2.2 0 0 1 3.12 3.12l-.05.05a1.8 1.8 0 0 0-.36 2 1.8 1.8 0 0 0 1.63 1.1H22a2.2 2.2 0 0 1 0 4.4h-.07a1.8 1.8 0 0 0-1.63 1.1z"})]})}),n.jsxs("button",{type:"button",onClick:b,className:"group inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-body text-primary transition-colors hover:bg-white/[0.08] sm:w-auto sm:gap-1.5 sm:px-3",title:"Refresh data",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"transition-transform group-hover:rotate-45",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),Be&&n.jsxs("div",{id:"header-notifications-panel",ref:Pe,role:"dialog","aria-label":"Notifications",className:"absolute right-0 top-[calc(100%+8px)] z-[320] w-[min(92vw,380px)] rounded-2xl border border-strong bg-[#070a11]/95 p-2 shadow-[0_20px_50px_rgba(0,0,0,0.45)] backdrop-blur",children:[n.jsxs("div",{className:"mb-1.5 flex items-center justify-between px-2 py-1",children:[n.jsx("p",{className:"text-body font-semibold uppercase tracking-[0.12em] text-secondary",children:"Notifications"}),n.jsxs("div",{className:"flex items-center gap-2",children:[re.length>0&&n.jsx("button",{type:"button",onClick:_t,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>te(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(gl,{className:"max-w-full overflow-hidden",running:On,blocked:Os,decisionsCount:si,completedToday:ds,onNeedsAttentionClick:()=>Ni({closeNotifications:!0}),onDecisionsClick:()=>Ft({closeNotifications:!0}),onBlockedClick:()=>{Oe.length>0?(h("mission-control"),ht("in_progress"),ve("needs_attention")):X("blocked"),te(!1)}})}),re.length===0?n.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-body text-secondary",children:ws>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:re.map(f=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:f.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:f.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:f.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(en,{type:f.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:f.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:f.message}),f.onAction&&n.jsx("button",{type:"button",onClick:()=>{var j;(j=f.onAction)==null||j.call(f),te(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:f.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>U(f.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},f.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:f=>{const j=f.target.value;p(j==="__all__"?null:j)},className:"control-pill h-8 w-full appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${g}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),w.map(f=>n.jsx("option",{value:f.id,children:f.title},f.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>h("activity"),"aria-pressed":c==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>h("mission-control"),"aria-pressed":c==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),c==="mission-control"?n.jsx("div",{className:"relative z-0 flex-1 min-h-0 flex flex-col overflow-hidden",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"flex flex-1 items-center justify-center text-body text-secondary",children:"Loading Mission Control…"}),children:n.jsx(Ug,{initiatives:us,activities:ae,agents:sr,runtimeInstances:k.runtimeInstances??[],workspaceInitiativeId:u,isLoading:T,authToken:null,embedMode:!1,connection:k.connection,lastSnapshotAt:k.lastSnapshotAt,error:D,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>Vt("orgx"),onRefresh:b,onCreateInitiative:ii,onPlayNextUp:ut,onStartAutopilot:qs,nextUpQueueModel:nt,nextUpActionsModel:et,snapshotVersion:k.snapshotVersion})})}):n.jsxs("main",{className:"relative z-0 grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-y-auto p-4 pb-20 sm:p-5 sm:pb-20 lg:grid-cols-12 lg:overflow-hidden lg:pb-5",children:[n.jsx("section",{className:`min-h-0 lg:col-span-3 lg:flex lg:flex-col lg:[&>section]:h-full ${Te!=="agents"?"hidden lg:flex":""}`,children:n.jsx(qf,{sessions:k.sessions,activity:ae,runtimeInstances:k.runtimeInstances??[],showSyntheticEntities:t||i,selectedSessionId:ie,onSelectSession:kn,onAgentFilter:ye,agentFilter:$e,timeFilterId:Y,onReconnect:Yn,onLaunched:b,connectionStatus:k.connection,autopilotState:Ls})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${Te!=="activity"?"hidden lg:flex":""}`,children:n.jsx(Fg,{activity:vs.items,sessions:L,sliceRuns:Oe,initiatives:Bt,timelineNarrative:k.timelineNarrative??[],workspaceId:u,chatSnapshot:k.chat,devMode:a,selectedRunIds:Pn,selectedSessionLabel:ma,selectedWorkstreamId:Me,selectedWorkstreamLabel:Ne,agentFilter:$e,timeFilterId:Y,onTimeFilterChange:ua,customTimeRange:De,onCustomTimeRangeChange:he,hasMore:vs.hasMore,isLoadingMore:vs.isLoadingMore,onLoadMore:vs.loadMore,onClearSelection:Ds,onClearWorkstreamFilter:$s,onClearAgentFilter:os,onFocusRunId:ls,onOpenDecision:qn,onResolveDecision:Ut,requestedActivityItemId:R,onActivityItemRequestHandled:()=>Ae(null),onPlayNextUp:ut,onStartAutopilot:qs,onPauseWorkstream:ji,onCreateInitiative:ii,onOpenMissionControl:()=>h("mission-control"),onOpenNextUp:()=>h("mission-control"),onOpenSettings:()=>Vt("orgx"),onRefreshData:b,isLoading:T})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${Te!=="decisions"&&Te!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${at==="initiatives"?"flex-1":"flex-shrink-0"} `,children:at==="initiatives"?n.jsxs(Ts,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-2.5",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":ct==="in_progress",onClick:f=>{f.stopPropagation(),ht("in_progress")},className:fe("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",ct==="in_progress"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"In Progress"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:Ps}),n.jsx("span",{className:fe("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-lime transition-opacity",ct==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":ct==="next_up",onClick:f=>{f.stopPropagation(),ht("next_up")},className:fe("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",ct==="next_up"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"Next Up"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:Es}),n.jsx("span",{className:fe("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-lime transition-opacity",ct==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{kt().catch(f=>{ee(ms(f instanceof Error?f.message:"","Autopilot action failed."))})},disabled:dt,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":ti,"data-state":Rs,title:bs,"aria-label":bs,children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:fe("h-3.5 w-3.5",hn?"animate-pulse":""),"aria-hidden":!0,children:n.jsx("path",{d:"M6.1 13.25C4.25 13.25 2.8 11.8 2.8 10s1.45-3.25 3.3-3.25c3.15 0 4.35 6.5 8.05 6.5 1.85 0 3.3-1.45 3.3-3.25s-1.45-3.25-3.3-3.25c-3.7 0-4.9 6.5-8.05 6.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n.jsx("span",{className:"text-micro uppercase tracking-[0.12em]",children:"Auto"}),n.jsx("span",{className:fe("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",an==="blocked"?"bg-amber-400/18 text-amber-100":hn?"bg-lime/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:Qn})]})]}),ct==="in_progress"?n.jsxs("div",{className:"border-b border-subtle px-4 py-2",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("button",{type:"button",onClick:()=>ve("all"),className:fe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Z==="all"?"bg-white/[0.09] text-primary":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"All active"}),n.jsx("span",{className:"tabular-nums opacity-75",children:Ps})]}),n.jsxs("button",{type:"button",onClick:()=>ve("needs_attention"),className:fe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Z==="needs_attention"?"bg-[#F5B700]/14 text-[#FFE7A8]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:mn})]}),n.jsxs("button",{type:"button",onClick:()=>ve("completed"),className:fe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Z==="completed"?"bg-[#14B8A6]/16 text-[#A9FFF3]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Completed"}),n.jsx("span",{className:"tabular-nums opacity-80",children:Re})]}),be&&k.decisions.length>0?n.jsxs("div",{className:"ml-auto inline-flex h-6 items-center gap-1 rounded-full border border-[#F5B700]/18 bg-[#F5B700]/10 px-2.5 text-micro font-semibold text-[#FFE7A8]",children:[n.jsx("span",{children:"Decisions"}),n.jsx("span",{className:"tabular-nums",children:k.decisions.length})]}):null]}),be&&k.decisions.length>0?n.jsxs("p",{className:"mt-1.5 pl-1 text-[10px] font-medium uppercase tracking-[0.12em] text-[#FFE7A8]/78",children:[k.decisions.length," ",k.decisions.length===1?"decision needs":"decisions need"," your input."]}):null]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:ct==="in_progress"?Z==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Ct.items.length>0&&n.jsx("div",{className:"min-h-[180px] max-h-[34%]",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading triage…"}),children:n.jsx(Hg,{model:Ct,actions:St,onOpenDetail:Vn})})}),be?n.jsxs("section",{className:fe("flex flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",un.length===0?"flex-1 min-h-[220px]":"min-h-[220px] max-h-[50%]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Decisions"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:k.decisions.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Resolve blockers and approvals to keep dispatch moving."})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden p-2",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"h-full min-h-[160px] rounded-lg border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading decisions…"}),children:n.jsx(Wg,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:k.decisions,focusDecisionId:Se,onFocusDecisionHandled:()=>Ee(null),onApproveDecision:_,onRejectDecision:H,onApproveAll:A,onBulkDecisionAction:O,mutationState:se,initiativeNames:gn})})})]}):n.jsx(Ts,{className:"border border-subtle bg-white/[0.02] px-4 py-3 text-body text-secondary",children:"OrgX is not connected. Decision actions are hidden until connectivity returns."}),n.jsxs("section",{className:fe("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:be?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:un.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Retry, approve, or manually intervene on execution slices."})]}),n.jsx("div",{className:"min-h-0 flex-1 p-2",children:n.jsx(Tp,{className:fe("h-full min-h-0"),title:be?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Oe,initiatives:Bt,onOpenDecisions:qn,onFocusRunId:ls,onReviewActivity:ai,onOpenSliceDetail:gt})})]})]}):Z==="completed"?n.jsx(Lp,{rows:Ge,onFocusRunId:ls,onOpenNextUp:()=>ht("next_up")}):n.jsx(hp,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:L,sliceRuns:Oe,initiatives:Bt,needsAttentionCount:mn,onSwitchToNeedsAttention:()=>ve("needs_attention"),onOpenSession:kn,onFocusRunId:ls,onPlayWorkstream:ks,onPauseWorkstream:ji,onResumeWorkstream:ks,onRestartSession:or,onIntervene:Zi,onOpenSliceDetail:Ht}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Vg,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:nt,queueActions:et,snapshotVersion:k.snapshotVersion,excludeRunning:!0,onOpenInitiative:Is,onOpenSliceDetail:ft})})},`${ct}:${Z}`)]}):n.jsx(Ts,{className:"card-enter",children:n.jsxs("button",{onClick:()=>pt("initiatives"),className:"flex w-full items-center justify-between px-4 py-3 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Initiatives"})}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"-rotate-90 text-muted",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})})})})]}),n.jsx(bt,{children:xe&&on&&n.jsxs(n.Fragment,{children:[n.jsx(ue.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] hidden bg-black/40 backdrop-blur-sm lg:block",onClick:()=>ne(!1)},"session-drawer-backdrop"),n.jsx(ue.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"glass-panel soft-shadow fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:q.cardBg,borderLeft:"1px solid rgba(255,255,255,0.08)"},children:n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(zg,{session:on,activity:ae,initiatives:Bt,sliceRuns:Oe,initialInterventionDraft:K,onSubmitIntervention:Ai,onOpenActivityItem:da,onContinueHighestPriority:ir,onDispatchSession:rr,onPauseSession:pa,onResumeSession:ar,onCancelSession:_i,onCreateCheckpoint:Tn,onRollbackSession:lr,onStartInitiative:ii,onStartWorkstream:ri,onClose:()=>ne(!1)})})})},"session-drawer-panel")]})}),c==="activity"?n.jsx(Sm,{activeTab:Te,onTabChange:rn,pendingDecisionCount:be?k.decisions.length:0}):null,n.jsx(oa,{open:Yt!==null,onClose:es,maxWidth:"max-w-sm",fitContent:!0,children:n.jsxs("div",{className:"flex w-full flex-col",children:[n.jsxs("div",{className:"px-5 pt-5 pb-1",children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:(Yt==null?void 0:Yt.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Yt==null?void 0:Yt.type)==="workstream"?"Create a new workstream under the selected initiative.":"Create a new initiative to organize your work."})]}),n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("label",{className:"mb-1.5 block text-caption uppercase tracking-[0.1em] text-secondary",children:"Name"}),n.jsx("input",{value:Jn,onChange:f=>Zn(f.target.value),onKeyDown:f=>{f.key==="Enter"&&ln()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Yt==null?void 0:Yt.type)==="workstream"?"e.g. User Onboarding Flow":"e.g. Q1 Product Launch",className:"w-full rounded-lg border border-strong bg-black/30 px-3 py-2.5 text-body text-white placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-lime/40"})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-subtle px-5 py-3",children:[n.jsx("button",{onClick:es,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:ln,disabled:Jn.trim().length===0||Et,className:"rounded-md border border-lime/25 bg-lime/10 px-4 py-1.5 text-body font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-45",children:Et?"Creating…":"Create"})]})]})}),We.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Gg,{open:We.open,onClose:()=>rt(f=>({...f,open:!1,focusAgentDomain:null})),activeTab:We.tab,onChangeTab:f=>rt(j=>({...j,tab:f})),agentBehaviorInitialDomain:We.focusAgentDomain,demoMode:t,onToggleDemoMode:f=>{Cn(f),f||Yn()},devMode:a,onToggleDevMode:l,showSyntheticEntities:i,onToggleShowSyntheticEntities:r,workspaceOptions:w,selectedWorkspaceId:u,onSelectWorkspace:p,onboarding:e,authToken:null,embedMode:!1})}),a&&ge&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(tx,{open:ge,selectedWorkspaceId:u,onClose:()=>Ve(!1)})}),(ce==="sessions"||ce==="active"||ce==="blocked"||ce==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Xg,{open:ce==="sessions"||ce==="active"||ce==="blocked"||ce==="failed",onClose:()=>X(null),mode:ce==="active"||ce==="blocked"||ce==="failed"?ce:"sessions",sessions:L,onOpenSession:f=>{kn(f.id),X(null)},onRunAction:async(f,j)=>{await xn(f,j,{reason:`bulk_${j}_from_header`})},onRefetch:async()=>b(),onSetNotice:f=>ee(f)})}),ce==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Qg,{open:ce==="decisions",onClose:()=>X(null),decisions:be?k.decisions:[],onApproveDecision:_,onRejectDecision:H,onApproveAll:A,onBulkDecisionAction:O})}),ce==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Yg,{open:ce==="outbox",onClose:()=>X(null),outbox:k.outbox,onOpenSettings:()=>{X(null),Vt("orgx")},onRefresh:()=>{b()}})}),ce==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Jg,{open:ce==="handoffs",onClose:()=>X(null),handoffs:k.handoffs})}),n.jsx(Ax,{}),Kt&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:n.jsx("div",{className:"relative w-full max-w-lg max-h-[80vh] overflow-hidden rounded-xl border border-subtle bg-[#0E0F11] shadow-2xl",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-8 text-center text-secondary",children:"Loading…"}),children:n.jsx(Kg,{item:Kt,actions:St,onClose:()=>vn(null),onNavigate:Gn,currentIndex:ys,totalCount:Mt.length,decisions:be?k.decisions:void 0,onReviewDecision:qn,onApproveDecision:_,onRejectDecision:H})})})}),He&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ex,{target:He,initiatives:Bt,onClose:()=>Ue(null),onPlayWorkstream:async(f,j,F)=>{try{const C=await nt.playWorkstream({initiativeId:f,workstreamId:j,agentId:F??void 0});await Promise.all([nt.refetch(),b()]),typeof C.sessionId=="string"&&C.sessionId.trim().length>0&&V(C.sessionId.trim()),ee(C.dispatchMode==="pending"?"Dispatching workstream…":"Started workstream.")}catch(C){ee(ms(C instanceof Error?C.message:null,"Failed to dispatch workstream"))}},onStartAutoContinue:async(f,j,F)=>{try{await et.move({initiativeId:f,workstreamId:j,placement:"top"});const C=await nt.startWorkstreamAutoContinue({initiativeId:f,workstreamId:j,agentId:F??void 0,scope:"initiative"}),m=nc(C);await Promise.all([nt.refetch(),b()]),m&&V(m),ee(m?"Auto-continue started.":"Auto-continue is dispatching now.")}catch(C){ee(ms(C instanceof Error?C.message:null,"Failed to start auto-continue"))}},onMoveWorkstream:async(f,j,F)=>{try{await et.move({initiativeId:f,workstreamId:j,placement:F}),ee(`Moved workstream to ${F}.`),b()}catch(C){ee(ms(C instanceof Error?C.message:null,"Move failed"))}},onRemoveFromQueue:async(f,j)=>{try{await et.remove({initiativeId:f,workstreamId:j}),ee("Removed workstream from queue."),b()}catch(F){ee(ms(F instanceof Error?F.message:null,"Remove failed"))}},onOpenSession:kn,onFocusRunId:ls,onOpenInitiative:Is,onReviewActivity:ai,onOpenDecisions:qn,onAcceptSlice:vt,onRejectSlice:Tt})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Su();const Sx=new fd({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});md.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(hd,{client:Sx,children:n.jsx(kx,{})})}));export{fm as $,Gt as A,gs as B,fe as C,It as D,en as E,Wn as F,Ss as G,Zu as H,Hx as I,qx as J,Fx as K,Bx as L,Wi as M,js as N,Cs as O,Ts as P,Qf as Q,Px as R,zn as S,Ln as T,Du as U,Lt as V,kc as W,mo as X,la as Y,Wx as Z,pm as _,$u as a,Ic as a0,wm as a1,Ux as a2,Ed as a3,Ox as a4,_c as a5,zx as a6,yr as a7,Fm as a8,Um as a9,gf as aa,$x as ab,fi as ac,Hm as ad,Kr as ae,Ot as b,Qa as c,Pp as d,fu as e,q as f,Jx as g,Xt as h,Hn as i,Qx as j,uf as k,Ks as l,Kx as m,Wt as n,Ec as o,Sa as p,rs as q,Gx as r,Yx as s,Op as t,em as u,Xx as v,Rt as w,Vx as x,Fi as y,oa as z};
|