@useorgx/openclaw-plugin 0.7.23 → 0.7.25
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/{m2smti3F.js → B6VftyY6.js} +1 -1
- package/dashboard/dist/assets/B6VftyY6.js.br +0 -0
- package/dashboard/dist/assets/B6VftyY6.js.gz +0 -0
- package/dashboard/dist/assets/{D-FuHfT8.js → BANQdlC4.js} +1 -1
- package/dashboard/dist/assets/BANQdlC4.js.br +0 -0
- package/dashboard/dist/assets/BANQdlC4.js.gz +0 -0
- package/dashboard/dist/assets/{DDCPrZRt.js → BPL4CL3c.js} +1 -1
- package/dashboard/dist/assets/BPL4CL3c.js.br +0 -0
- package/dashboard/dist/assets/BPL4CL3c.js.gz +0 -0
- package/dashboard/dist/assets/{D0PN5_vY.js → BZCkOZ20.js} +1 -1
- package/dashboard/dist/assets/BZCkOZ20.js.br +0 -0
- package/dashboard/dist/assets/BZCkOZ20.js.gz +0 -0
- package/dashboard/dist/assets/{DNQ-iFO2.js → B_LdOJUa.js} +1 -1
- 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 +1 -0
- package/dashboard/dist/assets/Bfp-wdwb.css.br +0 -0
- package/dashboard/dist/assets/{C1u2SGin.css.gz → Bfp-wdwb.css.gz} +0 -0
- package/dashboard/dist/assets/{CZXS5i_5.js → BvFcH_Iy.js} +1 -1
- package/dashboard/dist/assets/BvFcH_Iy.js.br +0 -0
- package/dashboard/dist/assets/BvFcH_Iy.js.gz +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js +212 -0
- package/dashboard/dist/assets/C0i7ABUU.js.br +0 -0
- package/dashboard/dist/assets/C0i7ABUU.js.gz +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js +1 -0
- package/dashboard/dist/assets/CFB0MM7j.js.br +0 -0
- package/dashboard/dist/assets/CFB0MM7j.js.gz +0 -0
- package/dashboard/dist/assets/{OlLPtzdz.js → CQSRb1yu.js} +1 -1
- package/dashboard/dist/assets/CQSRb1yu.js.br +0 -0
- package/dashboard/dist/assets/CQSRb1yu.js.gz +0 -0
- package/dashboard/dist/assets/{CbVWL74-.js → CUoQoSm-.js} +1 -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 +1 -0
- package/dashboard/dist/assets/Ckd1R1iE.js.br +0 -0
- package/dashboard/dist/assets/Ckd1R1iE.js.gz +0 -0
- package/dashboard/dist/assets/{DhPuHPK7.js → CqRNb2EL.js} +1 -1
- package/dashboard/dist/assets/CqRNb2EL.js.br +0 -0
- package/dashboard/dist/assets/CqRNb2EL.js.gz +0 -0
- package/dashboard/dist/assets/{CGJiHCIx.js → DClUc9rw.js} +1 -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 +1 -0
- package/dashboard/dist/assets/DF2PMTwT.js.br +0 -0
- package/dashboard/dist/assets/DF2PMTwT.js.gz +0 -0
- package/dashboard/dist/assets/{RN4M9u9W.js → DJYl7gyA.js} +1 -1
- package/dashboard/dist/assets/DJYl7gyA.js.br +0 -0
- package/dashboard/dist/assets/DJYl7gyA.js.gz +0 -0
- package/dashboard/dist/assets/{BrMXbzQ-.js → DZtNMX0t.js} +1 -1
- package/dashboard/dist/assets/DZtNMX0t.js.br +0 -0
- package/dashboard/dist/assets/DZtNMX0t.js.gz +0 -0
- package/dashboard/dist/assets/{LOFrVoPD.js → DlEa8PI0.js} +1 -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 +1 -0
- package/dashboard/dist/assets/M4QxcXjh.js.br +0 -0
- package/dashboard/dist/assets/M4QxcXjh.js.gz +0 -0
- package/dashboard/dist/assets/{nra1yvJX.js → MrW1ixGx.js} +1 -1
- package/dashboard/dist/assets/MrW1ixGx.js.br +0 -0
- package/dashboard/dist/assets/MrW1ixGx.js.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/activity-store.js +68 -8
- package/dist/contracts/shared-types.d.ts +28 -0
- package/dist/http/helpers/auto-continue-engine.js +235 -32
- package/dist/http/helpers/triage-mapper.js +285 -6
- package/dist/http/helpers/value-utils.d.ts +1 -0
- package/dist/http/helpers/value-utils.js +17 -0
- package/dist/http/index.js +89 -3
- package/dist/http/routes/live-triage.js +6 -1
- package/dist/http/routes/mission-control-actions.d.ts +9 -0
- package/dist/http/routes/mission-control-actions.js +157 -7
- package/dist/http/routes/mission-control-read.d.ts +9 -0
- package/dist/http/routes/mission-control-read.js +33 -0
- package/dist/openclaw.plugin.json +1 -1
- package/dist/stores/sqlite-state.d.ts +1 -1
- package/dist/stores/sqlite-state.js +153 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/9gFmK3Kr.js +0 -1
- package/dashboard/dist/assets/9gFmK3Kr.js.br +0 -0
- package/dashboard/dist/assets/9gFmK3Kr.js.gz +0 -0
- package/dashboard/dist/assets/BrMXbzQ-.js.br +0 -0
- package/dashboard/dist/assets/BrMXbzQ-.js.gz +0 -0
- package/dashboard/dist/assets/C1u2SGin.css +0 -1
- package/dashboard/dist/assets/C1u2SGin.css.br +0 -0
- package/dashboard/dist/assets/CGJiHCIx.js.br +0 -0
- package/dashboard/dist/assets/CGJiHCIx.js.gz +0 -0
- package/dashboard/dist/assets/CSd4rSuU.js +0 -212
- package/dashboard/dist/assets/CSd4rSuU.js.br +0 -0
- package/dashboard/dist/assets/CSd4rSuU.js.gz +0 -0
- package/dashboard/dist/assets/CZXS5i_5.js.br +0 -0
- package/dashboard/dist/assets/CZXS5i_5.js.gz +0 -0
- package/dashboard/dist/assets/CbVWL74-.js.br +0 -0
- package/dashboard/dist/assets/CbVWL74-.js.gz +0 -0
- package/dashboard/dist/assets/D-FuHfT8.js.br +0 -0
- package/dashboard/dist/assets/D-FuHfT8.js.gz +0 -0
- package/dashboard/dist/assets/D0PN5_vY.js.br +0 -0
- package/dashboard/dist/assets/D0PN5_vY.js.gz +0 -0
- package/dashboard/dist/assets/DDCPrZRt.js.br +0 -0
- package/dashboard/dist/assets/DDCPrZRt.js.gz +0 -0
- package/dashboard/dist/assets/DNQ-iFO2.js.br +0 -0
- package/dashboard/dist/assets/DNQ-iFO2.js.gz +0 -0
- package/dashboard/dist/assets/DhPuHPK7.js.br +0 -0
- package/dashboard/dist/assets/DhPuHPK7.js.gz +0 -0
- package/dashboard/dist/assets/Dhz7qPtn.js +0 -1
- package/dashboard/dist/assets/Dhz7qPtn.js.br +0 -0
- package/dashboard/dist/assets/Dhz7qPtn.js.gz +0 -0
- package/dashboard/dist/assets/LOFrVoPD.js.br +0 -0
- package/dashboard/dist/assets/LOFrVoPD.js.gz +0 -0
- package/dashboard/dist/assets/OlLPtzdz.js.br +0 -0
- package/dashboard/dist/assets/OlLPtzdz.js.gz +0 -0
- package/dashboard/dist/assets/RN4M9u9W.js.br +0 -0
- package/dashboard/dist/assets/RN4M9u9W.js.gz +0 -0
- package/dashboard/dist/assets/VCHu272d.js +0 -1
- package/dashboard/dist/assets/VCHu272d.js.br +0 -0
- package/dashboard/dist/assets/VCHu272d.js.gz +0 -0
- package/dashboard/dist/assets/m2smti3F.js.br +0 -0
- package/dashboard/dist/assets/m2smti3F.js.gz +0 -0
- package/dashboard/dist/assets/nra1yvJX.js.br +0 -0
- package/dashboard/dist/assets/nra1yvJX.js.gz +0 -0
- package/dashboard/dist/assets/qLX6NZ-J.js +0 -1
- package/dashboard/dist/assets/qLX6NZ-J.js.br +0 -0
- package/dashboard/dist/assets/qLX6NZ-J.js.gz +0 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CQSRb1yu.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/DF2PMTwT.js","assets/BZCkOZ20.js","assets/eeHXe_OQ.js","assets/CUoQoSm-.js","assets/By0MIBj_.js","assets/CqRNb2EL.js","assets/BvFcH_Iy.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/DlEa8PI0.js","assets/DClUc9rw.js","assets/M4QxcXjh.js","assets/CSlBSRyv.js","assets/Ckd1R1iE.js","assets/B6VftyY6.js","assets/DZtNMX0t.js","assets/BPL4CL3c.js","assets/MrW1ixGx.js","assets/DJYl7gyA.js","assets/BANQdlC4.js","assets/CFB0MM7j.js","assets/B_LdOJUa.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var ad=Object.defineProperty;var od=(e,t,s)=>t in e?ad(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var ss=(e,t,s)=>od(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as ld,d as cd}from"./Dj2k1r16.js";import{u as so,a as dd,b as Dn,c as ei,Q as ud,d as md}from"./DMKyYAtD.js";import{m as ce,A as bt,u as xs}from"./eeHXe_OQ.js";import{a7 as pd}from"./cX2e-TLi.js";import{D as vo}from"./BjK42gtU.js";import{T as fd,u as hd}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 gd="modulepreload",xd=function(e){return"/orgx/live/"+e},wo={},sn=function(t,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(m){return Promise.all(m.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};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(m=>{if(m=xd(m),m in wo)return;wo[m]=!0;const p=m.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const y=document.createElement("link");if(y.rel=p?"stylesheet":gd,p||(y.as="script"),y.crossOrigin="",y.href=m,d&&y.setAttribute("nonce",d),document.head.appendChild(y),p)return new Promise((h,I)=>{y.addEventListener("load",h),y.addEventListener("error",()=>I(new Error(`Unable to preload CSS for ${m}`)))})}))}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)})},ko=()=>{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()}}},fa="all";function fs(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function yd(){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",fa),e.set("command_center_id",fa),e.set("center",fa));return}e.set("workspace_id",i),e.set("command_center_id",i),e.set("center",i)}function bd(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??yd();return Object.assign(t,bd(s)),t}const vd=[[/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 Hi(e){if(!e)return"";for(const[s,i]of vd)if(s.test(e))return i;const t=e.split("/");return t[t.length-1]??e}const sc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ic=/^[0-9a-f]{20,}$/i;function Ss(e){return sc.test(e)?`#${e.slice(0,4)}`:ic.test(e)?`#${e.slice(0,4)}`:e}function zn(e){return sc.test(e)||ic.test(e)}function Un(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=>Hi(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Un(s)),t}function Et(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=>Un(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 ha(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 Si(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 wd(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 Io(e){const t=Js(e);if(!t)return null;const s=Js(t.error),i=s??t,r=Si(i,["message","detail","error_description"])??(s?null:Si(t,["error"])),a=Si(i,["code","error_code","type"]),l=wd(i,["status","httpStatusCode"]),c=Si(i,["requestId","request_id"]),d=Si(i,["docsUrl","docs_url"]);return!r&&!a&&l==null&&!c&&!d?null:{code:a,message:r,status:l,requestId:c,docsUrl:d}}function kd(e){var d,m;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),i=Io(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 g=JSON.parse(p),y=Io(g);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:((m=l==null?void 0:l[1])==null?void 0:m.trim())||null,status:null,requestId:null,docsUrl:null}}function No(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=kd(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=No(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.":Et(Xe(a))}function Id(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 Nd(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 Fn(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 jd(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=>Et(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=Et(i),a=r.toLowerCase();t.has(a)||(t.add(a),s.push(r))}return s}function jo(e,t){if(!Array.isArray(e))return[];const s=[];for(const i of e){const r=Js(i);if(!r)continue;const a=Fn(r,[`${t.toLowerCase()}_title`,`${t.toLowerCase()}Title`,"title","name"])??Fn(r,[`${t.toLowerCase()}_id`,`${t.toLowerCase()}Id`]),l=Fn(r,["status","state"]),c=Fn(r,["reason","summary","description","note"]),d=[a?`${t}: ${a}`:t,l?`-> ${Xe(l)}`:null,c?`· ${Et(c)}`:null].filter(Boolean);d.length>0&&s.push(d.join(" "))}return s}function Ad(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?Fn(i,["title","name","artifact_title","artifactTitle"])??Fn(i,["url","path"])??Fn(i,["type","artifact_type","artifactType"]):null})):Ws([Fn(e,["artifact_title","artifactTitle"]),Fn(e,["pr_url","prUrl"])?"Pull request attached":null,Fn(e,["commit_sha","commitSha"])?"Commit attached":null])}function vi(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 E of r){const q=Fn(E,k);if(q)return q}return null},l=k=>{for(const E of r){const q=jd(E,k);if(q.length>0)return q}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,m=Ws([a(["user_summary","userSummary","decision_summary","decisionSummary","summary","description","message"]),e.summary,e.description])[0]??null,p=a(["stop_reason","stopReason"]),g=a(["parsed_status","parsedStatus","current_run_state","currentRunState","runtime_state","runtimeState","status","state"])??p,y=g?Et(pi(g)??Xe(g)):null,h=Ws(r.flatMap(k=>Ad(k))),I=Ws([...r.flatMap(k=>jo(k.task_updates??k.taskUpdates,"Task")),...r.flatMap(k=>jo(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]),b=Ws([a(["next_step","nextStep"]),...l(["next_actions","nextActions"]),a(["required_action","requiredAction"])]);return{update:m,scope:d,status:y,artifacts:h.slice(0,6),outcomes:I.slice(0,6),nextUp:b.slice(0,5)}}const _d={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 pi(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return _d[t]??e.replace(/_/g," ")}const Sd={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function Cx(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Sd[t]??e.replace(/_/g," ")}function Tx(e,t){return e.toLowerCase().includes("path")?Un(t):zn(t)?Ss(t):t.includes(",")?t.split(",").map(i=>{const r=i.trim();return zn(r)?Ss(r):r}).join(", "):Et(t)}function Cd(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 Mx(e){const t=Cd(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Hr(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 Td=8e3,Md=320,Ed=300,Rd=80,Ld=80,Dd=120,Ao=6e4,$d=4e3,Pd=4e3,Od=240,qd=3,Bd=24,_o=24,Ci=new WeakMap,io={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},dr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Zs={threads:[],total:0,updatedAt:null},So={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},rc=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),ur=10*6e4;function Fd(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 Ud(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 zd(e){const t=e.map(s=>Ud(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function It(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Kr(e,t){const s=So[e.status]??99,i=So[t.status]??99;if(s!==i)return s-i;const r=It(e.updatedAt??e.lastEventAt??e.startedAt),a=It(t.updatedAt??t.lastEventAt??t.startedAt);return r!==a?a-r:e.id.localeCompare(t.id)}function Wd(e){return(e??"").trim().toLowerCase()}function Co(e){return rc.has(Wd(e.status))}function ga(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function To(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const h=Date.now(),I=e.nodes.filter(E=>{const q=It(E.updatedAt??E.lastEventAt??E.startedAt);if(Co(E))return!0;const _=["completed","archived","failed"].includes((E.status??"").toLowerCase())?ur/3:ur;return h-q<=_});if(!I.length)return t;const b=new Set(I.map(E=>E.id)),k=new Set(I.map(E=>E.groupId));return{nodes:I.sort(Kr),edges:e.edges.filter(E=>b.has(E.parentId)&&b.has(E.childId)),groups:e.groups.filter(E=>k.has(E.id))}}const s=new Set,i=[...t.nodes];for(const h of t.nodes)for(const I of ga(h))s.add(I);const r=Date.now(),a=[];for(const h of e.nodes){if(ga(h).some(w=>s.has(w)))continue;const b=It(h.updatedAt??h.lastEventAt??h.startedAt),E=["completed","archived","failed"].includes((h.status??"").toLowerCase())?ur/3:ur,q=r-b<=E;if(Co(h)||q){a.push(h),i.push(h);for(const w of ga(h))s.add(w)}}if(!a.length)return t;const l=new Set(i.map(h=>h.id)),c=new Map(e.groups.map(h=>[h.id,h])),d=new Map(t.groups.map(h=>[h.id,h])),m=[...t.groups];for(const h of a){if(d.has(h.groupId))continue;const I=c.get(h.groupId)??{id:h.groupId,label:h.groupLabel||h.agentName||"Ungrouped",status:null};d.set(h.groupId,I),m.push(I)}const p=h=>`${h.parentId}->${h.childId}`,g=new Set,y=[];for(const h of t.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const I=p(h);g.has(I)||(g.add(I),y.push(h))}for(const h of e.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const I=p(h);g.has(I)||(g.add(I),y.push(h))}return{nodes:i.sort(Kr),edges:y,groups:m}}function Ti(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Kr).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 Mo(e,t){return e.length<=t?e:[...e].sort((s,i)=>It(i.updatedAt)-It(s.updatedAt)).slice(0,t)}function Hd(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()-It(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 ac(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 Eo(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 Ro(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 Lo(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 oc(e){if(!e||typeof e!="object")return io;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 Kd(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 Vr(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=Ci.get(i);if(r)return r;if(t>=qd){const g=Array.isArray(e)?"[…]":"{…}";return Ci.set(i,g),g}if(Ci.set(i,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const g=e.slice(0,_o).map(I=>Vr(I,t+1)).join(","),y=e.length>_o?",…":"",h=`[${g}${y}]`;return Ci.set(i,h),h}const a=e,l=Object.keys(a).sort(),c=l.slice(0,Bd),d=c.map(g=>`${g}:${Vr(a[g],t+1)}`).join("|"),m=l.length>c.length?"|…":"",p=`{${d}${m}}`;return Ci.set(i,p),p}function Vd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Bs(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 Gd(e){const t=Vd(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)??Bs(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=Bs(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??Bs(t,["initiative_id","initiativeId"]),c=Bs(t,["workstream_id","workstreamId"]),d=Bs(t,["task_id","taskId"]),m=Bs(t,["stop_reason","stopReason"]),p=Bs(t,["parsed_status","parsedStatus"]),g=(e.title??"").trim().toLowerCase();return!i&&!r&&!a||!r&&!a&&!c&&!d?null:[i,l??"",c??"",d??"",r??"",a??"",m??"",p??"",g].join("|")}function mr(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 lc(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(m=>m.id===l.id);d>=0&&mr(l)>mr(a[d])&&(a[d]=l);continue}s.add(l.id);const c=Gd(l);if(c&&i.has(c)){const d=r.get(c);mr(l)>mr(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 Xd(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,Vr(d.metadata));let a=!1;for(const d of t){const m=i.get(d.id),p=Vr(d.metadata);if(!m){i.set(d.id,d),r.set(d.id,p),a=!0;continue}(m.timestamp!==d.timestamp||m.type!==d.type||m.title!==d.title||m.description!==d.description||m.summary!==d.summary||m.kind!==d.kind||m.agentId!==d.agentId||m.agentName!==d.agentName||m.requesterAgentId!==d.requesterAgentId||m.requesterAgentName!==d.requesterAgentName||m.executorAgentId!==d.executorAgentId||m.executorAgentName!==d.executorAgentName||m.runId!==d.runId||m.initiativeId!==d.initiativeId||m.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,m)=>{const p=It(m.timestamp)-It(d.timestamp);return p!==0?p:m.id.localeCompare(d.id)}),c=lc(l,s);return ac(e,c)?e:c}function xa(e,t){const s=[...e].sort((i,r)=>{const a=It(r.timestamp)-It(i.timestamp);return a!==0?a:r.id.localeCompare(i.id)});return lc(s,t)}function Do(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(Hd).sort((a,l)=>a.waitingMinutes!==l.waitingMinutes?l.waitingMinutes-a.waitingMinutes:It(l.requestedAt??l.updatedAt)-It(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 $o(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 Qd(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 Yd(e,t){return!!(rc.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function pr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function ya(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 Jd(e,t,s){const i=new Map,r=[...e].sort((c,d)=>It(d.timestamp)-It(c.timestamp));for(const c of r){if(!c.runId)continue;const d=c.runId,m=i.get(d),p=c.timestamp;if(!m){const g=c.initiativeId??null;i.set(d,{id:d,parentId:null,runId:d,title:c.title,agentId:c.agentId??null,agentName:c.agentName??null,status:$o(c.type),progress:null,initiativeId:g,workstreamId:null,groupId:g??"unscoped",groupLabel:pr(g),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!m.startedAt||It(p)<It(m.startedAt))&&(m.startedAt=p),It(p)>=It(m.updatedAt??m.lastEventAt)&&(m.updatedAt=p,m.lastEventAt=p,m.lastEventSummary=c.title,m.status=$o(c.type),c.agentName&&(m.agentName=c.agentName),c.agentId&&(m.agentId=c.agentId),c.initiativeId&&(m.initiativeId=c.initiativeId,m.groupId=c.initiativeId,m.groupLabel=pr(c.initiativeId)),(!m.title||m.title.length<4)&&(m.title=c.title)),c.type==="blocker_created"&&c.description&&(m.blockers.includes(c.description)||m.blockers.push(c.description))}for(const c of t??[]){const d=c.runId??`agent:${c.id}`,m=i.get(d),p=Qd(c.status),g=new Date().toISOString(),y=Yd(c,p),h=c.startedAt??(y?g:null),I=c.initiativeId??null,b=c.currentTask&&c.currentTask.trim().length>0?c.currentTask.trim():`${c.name??c.id} ${p==="archived"?"idle":p}`;if(!m){i.set(d,{id:d,parentId:null,runId:d,title:b,agentId:c.id,agentName:c.name??c.id,status:p,progress:null,initiativeId:I,workstreamId:null,groupId:I??"unscoped",groupLabel:pr(I),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:c.currentTask,blockers:ya(c.blockers)});continue}!m.agentName&&c.name&&(m.agentName=c.name),m.agentId||(m.agentId=c.id),(!m.title||m.title===m.runId)&&(m.title=b),y&&(m.updatedAt=h??m.updatedAt??g,m.lastEventAt=h??m.lastEventAt??g),m.status==="archived"&&p!=="archived"&&(m.status=p),ya(c.blockers).length>0&&(m.blockers=ya(c.blockers)),I&&!m.initiativeId&&(m.initiativeId=I,m.groupId=I,m.groupLabel=pr(I))}const a=Array.from(i.values()).sort(Kr).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 Po(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,m=null;if(r){if(a!=null&&a.aborted)r.abort();else if(a){const g=()=>r.abort();a.addEventListener("abort",g,{once:!0}),m=()=>a.removeEventListener("abort",g)}d=setTimeout(()=>r.abort(),i)}try{const g=await fetch(e,c),h=(((p=g.headers.get("content-type"))==null?void 0:p.toLowerCase())??"").includes("application/json");if(!g.ok){let I=`${g.status} ${g.statusText}`;if(h){const b=await g.json().catch(()=>null);b!=null&&b.error&&(I=`${g.status} ${b.error}`)}else{const b=(await g.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);b.length>0&&(I=`${g.status} ${b}`)}return{ok:!1,status:g.status,data:null,error:I}}if(!h){const I=(await g.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:g.status,data:null,error:`Unexpected content type for ${e}${I?`: ${I}`:""}`}}return{ok:!0,status:g.status,data:await g.json(),error:null}}catch(g){const y=g instanceof Error?g.message:"Network error",h=!!(r!=null&&r.signal.aborted)&&!(a!=null&&a.aborted);return g instanceof DOMException&&g.name==="AbortError"||Fd(y)?{ok:!1,status:0,data:null,error:h&&i>0?`request timed out after ${i}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:y}}finally{d&&clearTimeout(d),m&&m()}}function Zd(e,t,s,i,r=[],a=io,l=null,c=1,d=[],m=Zs,p){var I,b,k;const g=((I=t[0])==null?void 0:I.timestamp)??null,y=((b=i[0])==null?void 0:b.requestedAt)??((k=i[0])==null?void 0:k.updatedAt)??null,h=It(g)>=It(y)?g:y;return{connection:"connected",lastActivity:h?Rt(h):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:i,sliceRuns:r,outbox:oc(a),chat:$r(m),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 Oo(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)=>It(i.lastEventAt??i.lastHeartbeatAt)-It(s.lastEventAt??s.lastHeartbeatAt))}function qo(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 eu(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)=>It(i.lastActivityAt??i.updatedAt)-It(s.lastActivityAt??s.updatedAt))}function $r(e){if(!e||typeof e!="object")return Zs;const t=eu(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 tu(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 Pr(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(m=>m.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),m=s(i.iwmtIds,i.iwmtId??null),p=typeof i.initiativeId=="string"&&i.initiativeId.trim().length>0?i.initiativeId.trim():c[0]??null,g=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():m[0]??null;t.set(l,{...i,id:l,sliceRunId:l,sliceKind:a==="work_slice"?"work_slice":void 0,initiativeId:p,initiativeIds:c,workstreamId:g,workstreamIds:d,iwmtId:y,iwmtIds:m,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)=>It(r.updatedAt??r.lastEventAt)-It(i.updatedAt??i.lastEventAt))}function Mi(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)=>It(i.updatedAt??i.completedAt??i.failedAt)-It(s.updatedAt??s.completedAt??s.failedAt))}function ba(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)=>It(i.occurredAt)-It(s.occurredAt))}function va(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 Bo(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,m=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:m,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 Pr(t)}function nu(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 Fo(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 su(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 iu(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 ru(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 au(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 ou(e={}){const{enabled:t=!0,pollInterval:s=Td,useMock:i=!1,enableDecisions:r=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=Md,maxActivityItems:d=Ed,maxHandoffs:m=Rd,maxDecisions:p=Ld,batchWindowMs:g=Dd}=e,y=typeof a=="string"&&a.trim().length>0?a.trim():null,h=typeof l=="string"&&l.trim().length>0?l.trim():null,[I,b]=o.useState(ko()),[k,E]=o.useState(dr),[q,w]=o.useState(!i),[_,W]=o.useState(null),A=o.useRef(),P=o.useRef(null),te=o.useRef(null),[R,$]=o.useState(!1),[ne,xe]=o.useState(typeof document>"u"?!0:document.visibilityState==="visible"),[Te,fe]=o.useState(typeof navigator>"u"?!0:navigator.onLine!==!1),je=o.useRef(0),ae=o.useRef(!1),ie=o.useRef(!1),X=o.useRef(null),oe=o.useRef(`${y??"__all__"}::${h??"__all__"}`),Le=o.useRef(!1),Me=o.useRef(null),de=o.useCallback((pe,Ie)=>{Me.current&&(clearTimeout(Me.current),Me.current=null),E(pe),Ie!=null&&Ie.autoResetMs&&Ie.autoResetMs>0&&(Me.current=setTimeout(()=>{Me.current=null,E(dr)},Ie.autoResetMs))},[]);o.useEffect(()=>()=>{Me.current&&(clearTimeout(Me.current),Me.current=null),X.current&&(clearTimeout(X.current),X.current=null)},[]),o.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const pe=()=>{xe(document.visibilityState==="visible")},Ie=()=>fe(!0),M=()=>fe(!1);return document.addEventListener("visibilitychange",pe),window.addEventListener("online",Ie),window.addEventListener("offline",M),()=>{document.removeEventListener("visibilitychange",pe),window.removeEventListener("online",Ie),window.removeEventListener("offline",M)}},[]),o.useEffect(()=>{const pe=`${y??"__all__"}::${h??"__all__"}`;oe.current!==pe&&(oe.current=pe,Le.current=!0,ie.current=!1,de(dr),b(Ie=>({...Ie,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:(Ie.snapshotVersion??0)+1})),w(!0),W(null))},[y,h,de]);const ke=o.useCallback((pe,Ie,M,Ne=null,_e=null,Ee=null,$e=null,ge=null,mt=null,Se=null)=>{je.current=Date.now(),ae.current=!1,b(Ae=>{const J=Le.current;J&&(Le.current=!1);const dt=Ie===null?J?[]:Ae.activity:xa(Ie,d),yt=M===null?J?[]:Ae.handoffs:Mo(M,m),Fe=Ti(pe===null?J?{nodes:[],edges:[],groups:[]}:Ae.sessions:J?Ti(pe,c):To(Ae.sessions,Ti(pe,c)),c),Z=Ne===null?J?[]:Ae.decisions:Do(Ne,p),B=_e===null?J?[]:Ae.sliceRuns:Pr(_e),se=Ee===null?J?io:Ae.outbox:oc(Ee),ue=ge===null?J?[]:Ae.runtimeInstances??[]:Oo(ge),Pe=mt===null?J?Zs:Ae.chat??Zs:$r(mt),We=(Se==null?void 0:Se.workSliceProjections)==null?J?[]:Ae.workSliceProjections??[]:Mi(Se.workSliceProjections),rt=(Se==null?void 0:Se.needsInputItems)==null?J?[]:Ae.needsInputItems??[]:Mi(Se.needsInputItems),he=(Se==null?void 0:Se.timelineNarrative)==null?J?[]:Ae.timelineNarrative??[]:ba(Se.timelineNarrative),Ve=(Se==null?void 0:Se.nextUpByInitiative)==null?J?[]:Ae.nextUpByInitiative??[]:va(Se.nextUpByInitiative),re=typeof(Se==null?void 0:Se.runningWorkSlices)=="number"&&Number.isFinite(Se.runningWorkSlices)?Math.max(0,Math.floor(Se.runningWorkSlices)):Ae.runningWorkSlices??0,K=typeof(Se==null?void 0:Se.needsInputTotal)=="number"&&Number.isFinite(Se.needsInputTotal)?Math.max(0,Math.floor(Se.needsInputTotal)):Ae.needsInputTotal??0,Ce=typeof(Se==null?void 0:Se.failedActionableTotal)=="number"&&Number.isFinite(Se.failedActionableTotal)?Math.max(0,Math.floor(Se.failedActionableTotal)):Ae.failedActionableTotal??0,Ze=typeof(Se==null?void 0:Se.completedTodayTotal)=="number"&&Number.isFinite(Se.completedTodayTotal)?Math.max(0,Math.floor(Se.completedTodayTotal)):Ae.completedTodayTotal??0,at=(Se==null?void 0:Se.consistencyFlags)==null?Ae.consistencyFlags??[]:Se.consistencyFlags.filter(ht=>typeof ht=="string"),pt=(Se==null?void 0:Se.dataHealth)===void 0||(Se==null?void 0:Se.dataHealth)===null?Ae.dataHealth:Se.dataHealth,ct=(Ae.snapshotVersion??0)+1;return Eo(Ae.sessions,Fe)&&ac(Ae.activity,dt)&&Ro(Ae.handoffs,yt)&&Lo(Ae.decisions,Z)&&nu(Ae.sliceRuns,B)&&Kd(Ae.outbox,se)&&tu(Ae.chat,Pe)&&qo(Ae.runtimeInstances,ue)&&Fo(Ae.workSliceProjections??[],We)&&Fo(Ae.needsInputItems??[],rt)&&su(Ae.timelineNarrative??[],he)&&iu(Ae.nextUpByInitiative??[],Ve)&&(Ae.runningWorkSlices??0)===re&&(Ae.needsInputTotal??0)===K&&(Ae.failedActionableTotal??0)===Ce&&(Ae.completedTodayTotal??0)===Ze&&ru(Ae.consistencyFlags??[],at)&&au(Ae.dataHealth,pt)&&Ae.lastSnapshotAt===$e&&Ae.connection==="connected"?Ae:Zd(Fe,dt,yt,Z,B,se,$e,ct,ue,Pe,{workSliceProjections:We,needsInputItems:rt,timelineNarrative:he,nextUpByInitiative:Ve,runningWorkSlices:re,needsInputTotal:K,failedActionableTotal:Ce,completedTodayTotal:Ze,consistencyFlags:at,dataHealth:pt})}),w(!1)},[d,p,m,c]),T=o.useCallback(async()=>{if(!t){b(M=>M.connection==="disconnected"?M:{...M,connection:"disconnected"}),w(!1),W(null);return}const pe=`${y??"__all__"}::${h??"__all__"}`;if(P.current&&te.current===pe)return P.current;if(i){b(ko()),w(!1);return}const Ie=(async()=>{try{const M=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});h&&gs(M,h),y&&M.set("initiative",y);const Ne=Ot({workspaceId:h}),_e=new URLSearchParams({status:"pending",limit:String(p)});h&&gs(_e,h),y&&_e.set("initiative",y);const[Ee,$e]=await Promise.all([Po(`/orgx/api/live/snapshot-v2?${M.toString()}`,{headers:Ne},{timeoutMs:$d}),r?Po(`/orgx/api/live/decisions?${_e.toString()}`,{headers:Ne},{timeoutMs:Pd}):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 ge=Ee.data;if(oe.current!==pe)return;const mt=Array.isArray(ge.degraded)?ge.degraded.filter(Re=>typeof Re=="string"):[],Se=mt.map(Re=>Re.toLowerCase()),Ae=(...Re)=>Se.some(He=>Re.some(Ue=>He.includes(Ue))),J=Array.isArray(ge.activity)?ge.activity:[],dt=Array.isArray(ge.handoffs)?ge.handoffs:[],yt=Array.isArray(ge.decisions)?ge.decisions:[],Fe=$e!=null&&$e.ok&&$e.data&&Array.isArray($e.data.decisions)?$e.data.decisions:[],Z=r&&Fe.length>0?Fe:yt,B=J.length===0&&Ae("activity unavailable","activity local fallback failed"),se=Ae("sessions unavailable","sessions local fallback failed"),ue=dt.length===0&&Ae("handoffs unavailable"),Pe=Z.length===0&&Ae("decisions unavailable"),We=Mi(Array.isArray(ge.projections)?ge.projections:[]),rt=$r(ge.chat??null),he=ba(Array.isArray(ge.timelineNarrative)?ge.timelineNarrative:[]),Ve=va(Array.isArray(ge.nextUpByInitiative)?ge.nextUpByInitiative:[]),re=We.length>0?Bo(We):Pr(Array.isArray(ge.sliceRuns)?ge.sliceRuns:[]),K=ge.sessions&&Array.isArray(ge.sessions.nodes)&&Array.isArray(ge.sessions.edges)&&Array.isArray(ge.sessions.groups)?ge.sessions:Jd(J,ge.agents,c),Ce=re.length===0&&We.length===0&&Ae("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),Ze=Ve.length===0&&Ae("next-up unavailable","next-up queue"),at=B?null:J,pt=ue?null:dt,ct=Pe?null:Z,ht=se&&K.nodes.length===0?null:K,rn=Ce?null:We,Y=Ce?null:he,ye=Ce?null:re,Oe=Ze?null:Ve;ke(ht,at,pt,ct,ye,ge.outbox??null,ge.generatedAt??null,ge.runtimeInstances??null,rt,{workSliceProjections:rn,needsInputItems:Array.isArray(ge.needsInputItems)?ge.needsInputItems:null,timelineNarrative:Y,nextUpByInitiative:Oe,runningWorkSlices:Ce?null:ge.runningWorkSlices??null,needsInputTotal:Ce?null:ge.needsInput??null,failedActionableTotal:Ce?null:ge.failedActionable??null,completedTodayTotal:Ce?null:ge.completedToday??null,consistencyFlags:Array.isArray(ge.consistencyFlags)?ge.consistencyFlags:null,dataHealth:ge.dataHealth??null});const Ge=mt.length>0?zd(mt):[];Ge.length>0?(W(`Partial live data: ${Ge.join("; ")}`),b(Re=>Re.connection==="connected"?Re:{...Re,connection:"connected"}),$(!1)):(W(null),b(Re=>Re.connection==="connected"?Re:{...Re,connection:"connected"}))}catch(M){if(oe.current!==pe)return;const Ne=M instanceof Error?M.message:"Unknown error",_e=M==null||typeof M!="object"||!("code"in M)?!1:M.code==="ORGX_AUTH";_e&&(ae.current=!0);const Ee=je.current>0&&Date.now()-je.current>Ao;W(Ne),b($e=>{const ge=_e||Ee?"disconnected":"reconnecting";return $e.connection===ge?$e:{...$e,connection:ge}}),$(!_e),w(!1)}finally{te.current===pe&&(P.current=null,te.current=null)}})();return P.current=Ie,te.current=pe,Ie},[ke,t,r,d,p,m,c,h,y,i]),z=o.useCallback(async(pe,Ie,M)=>{var mt,Se,Ae;if(!r)throw new Error("OrgX decisions are unavailable while disconnected.");const Ne=Array.from(new Set(pe.filter(Boolean)));if(Ne.length===0)return{updated:0,failed:0};const _e=((mt=M==null?void 0:M.note)==null?void 0:mt.trim())||void 0,Ee=((Se=M==null?void 0:M.optionId)==null?void 0:Se.trim())||void 0;if(i){const J=new Set(Ne);return b(dt=>{const yt=dt.decisions.filter(se=>J.has(se.id));if(yt.length===0)return dt;const Fe=new Date().toISOString(),Z=yt.map(se=>({id:`decision:${Ie}:${se.id}:${Date.now()}`,type:"decision_resolved",title:Ie==="approve"?`Approved: ${se.title}`:`Rejected: ${se.title}`,description:se.context,agentId:null,agentName:se.agentName,requesterAgentId:null,requesterAgentName:se.agentName??null,executorAgentId:null,executorAgentName:se.agentName??null,runId:null,initiativeId:null,timestamp:Fe,metadata:{decisionId:se.id,action:Ie}})),B=xa(Z.concat(dt.activity),d);return{...dt,decisions:dt.decisions.filter(se=>!J.has(se.id)),activity:B,lastActivity:Rt(Fe)}}),{updated:J.size,failed:0,firstError:void 0}}const $e=new Date().toISOString(),ge=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ot({contentTypeJson:!0,workspaceId:h}),body:JSON.stringify({ids:Ne,action:Ie,..._e?{note:_e}:{},...Ee?{option_id:Ee}:{}})});try{const J=await ge.json().catch(()=>null),dt=Array.isArray(J==null?void 0:J.results)?J.results:[],yt=new Set(dt.filter(ue=>ue.ok).map(ue=>ue.id)),Z=((Ae=dt.filter(ue=>!ue.ok).find(ue=>typeof ue.error=="string"&&ue.error.trim().length>0))==null?void 0:Ae.error)??(typeof(J==null?void 0:J.error)=="string"&&J.error.trim().length>0?J.error:void 0);if(!ge.ok&&ge.status!==207){const ue=Z??`Decision action failed (${ge.status})`;throw new Error(ue)}if(yt.size===0&&ge.ok&&((J==null?void 0:J.failed)??0)===0)for(const ue of Ne)yt.add(ue);yt.size>0?b(ue=>{const Pe=ue.decisions.filter(re=>yt.has(re.id));if(Pe.length===0)return ue;const We=new Date().toISOString(),rt=Pe.map(re=>({id:`decision:${Ie}:${re.id}:${Date.now()}`,type:"decision_resolved",title:Ie==="approve"?`Approved: ${re.title}`:`Rejected: ${re.title}`,description:re.context,agentId:null,agentName:re.agentName,requesterAgentId:null,requesterAgentName:re.agentName??null,executorAgentId:null,executorAgentName:re.agentName??null,runId:null,initiativeId:null,timestamp:We,metadata:{decisionId:re.id,action:Ie}})),he=xa(rt.concat(ue.activity),d);return{...ue,decisions:ue.decisions.filter(re=>!yt.has(re.id)),activity:he,lastActivity:Rt(We)}}):ge.ok&&Ne.length>0&&b(ue=>({...ue,decisions:ue.decisions.filter(Pe=>!Ne.includes(Pe.id))})),T();const B=(J==null?void 0:J.updated)??yt.size,se=(J==null?void 0:J.failed)??Math.max(0,Ne.length-yt.size);return de({phase:se>0?"error":"success",action:Ie,targetCount:Ne.length,message:se>0?`${Ie==="approve"?"Approve":"Reject"} completed with ${se} failure${se===1?"":"s"}.`:Ie==="approve"?`Approved ${B} decision${B===1?"":"s"}.`:`Rejected ${B} decision${B===1?"":"s"}.`,startedAt:$e,completedAt:new Date().toISOString()},{autoResetMs:se>0?8e3:4e3}),{updated:B,failed:se,firstError:Z}}catch(J){throw de({phase:"error",action:Ie,targetCount:Ne.length,message:J instanceof Error?J.message:"Decision update failed.",startedAt:$e,completedAt:new Date().toISOString()}),J}},[r,T,d,h,de,i]),H=o.useCallback(async(pe,Ie)=>z([pe],"approve",Ie),[z]),G=o.useCallback(async(pe,Ie)=>z([pe],"reject",Ie),[z]),we=o.useCallback(async()=>{let pe=[];return b(Ie=>(pe=Ie.decisions.map(M=>M.id),Ie)),pe.length===0?{updated:0,failed:0}:z(pe,"approve")},[z]),De=o.useCallback(async(pe,Ie,M)=>z(pe,Ie,M?{note:M}:void 0),[z]);return o.useEffect(()=>{r||de(dr)},[r,de]),o.useEffect(()=>{if(!t){$(!1),w(!1),W(null);return}if(i){T();return}ie.current=!1;const pe=new URLSearchParams;h&&gs(pe,h),y&&pe.set("initiative",y);const Ie=pe.toString()?`/orgx/api/live/stream-v2?${pe.toString()}`:"/orgx/api/live/stream-v2",M=new EventSource(Ie),Ne=()=>{X.current&&(clearTimeout(X.current),X.current=null),!(!ne||!Te)&&(X.current=setTimeout(()=>{X.current=null,!ie.current&&!ae.current&&T()},Od))};Ne();let _e=null,Ee=null,$e=null,ge=null,mt=[],Se=null,Ae;const J=()=>{if(Ae=void 0,_e){je.current=Date.now(),ae.current=!1;const Fe=_e;_e=null,$e=null,ge=null,mt=[],Se=null,Ee=null,ke(Fe.sessions,Fe.activity,Fe.handoffs,Fe.decisions,Fe.sliceRuns,Fe.outbox,Fe.generatedAt,Fe.runtimeInstances,Fe.chat,Fe.v2);return}!$e&&!ge&&!Se&&!Ee&&mt.length===0||(je.current=Date.now(),ae.current=!1,b(Fe=>{var B;let Z=Fe;if($e){const se=Ti($e,c),ue=Ti(To(Z.sessions,se),c);$e=null,Eo(Z.sessions,ue)||(Z={...Z,sessions:ue})}if(ge){const se=Mo(ge,m);ge=null,Ro(Z.handoffs,se)||(Z={...Z,handoffs:se})}if(Se){const se=Do(Se,p);Se=null,Lo(Z.decisions,se)||(Z={...Z,decisions:se})}if(Ee){const se=Oo(Ee);Ee=null,qo(Z.runtimeInstances,se)||(Z={...Z,runtimeInstances:se})}if(mt.length>0){const se=Xd(Z.activity,mt,d);mt=[],se!==Z.activity&&(Z={...Z,activity:se,lastActivity:(B=se[0])!=null&&B.timestamp?Rt(se[0].timestamp):Z.lastActivity})}return Z===Fe?Fe:Z.connection==="connected"?Z:{...Z,connection:"connected"}}),W(null),w(!1))},dt=()=>{Ae||(Ae=setTimeout(J,g))};M.onopen=()=>{je.current=Date.now(),ae.current=!1,$(!1),b(Fe=>Fe.connection==="connected"?Fe:{...Fe,connection:"connected"}),W(null),Ne()},M.onerror=()=>{if(ae.current){b(Z=>Z.connection==="disconnected"?Z:{...Z,connection:"disconnected"}),$(!1);return}const Fe=je.current>0&&Date.now()-je.current>Ao;b(Z=>Z.connection===(Fe?"disconnected":"reconnecting")?Z:{...Z,connection:Fe?"disconnected":"reconnecting"}),$(!0)},M.addEventListener("snapshot",Fe=>{try{ie.current=!0,X.current&&(clearTimeout(X.current),X.current=null);const Z=JSON.parse(Fe.data),B=typeof Z.generatedAt=="string"&&Z.generatedAt.length>0?Z.generatedAt:new Date().toISOString();_e={sessions:Z.sessions,activity:Z.activity??[],handoffs:Z.handoffs??[],decisions:Z.decisions??null,sliceRuns:Array.isArray(Z.sliceRuns)?Pr(Z.sliceRuns):Array.isArray(Z.projections)?Bo(Mi(Z.projections)):null,outbox:Z.outbox??null,generatedAt:B,runtimeInstances:Array.isArray(Z.runtimeInstances)?Z.runtimeInstances:null,chat:$r(Z.chat??null),v2:{workSliceProjections:Array.isArray(Z.projections)?Mi(Z.projections):null,timelineNarrative:Array.isArray(Z.timelineNarrative)?ba(Z.timelineNarrative):null,nextUpByInitiative:Array.isArray(Z.nextUpByInitiative)?va(Z.nextUpByInitiative):null,runningWorkSlices:typeof Z.runningWorkSlices=="number"?Z.runningWorkSlices:null,needsInputTotal:typeof Z.needsInput=="number"?Z.needsInput:null,needsInputItems:Array.isArray(Z.needsInputItems)?Z.needsInputItems:null,failedActionableTotal:typeof Z.failedActionable=="number"?Z.failedActionable:null,completedTodayTotal:typeof Z.completedToday=="number"?Z.completedToday:null,consistencyFlags:Array.isArray(Z.consistencyFlags)?Z.consistencyFlags:null,dataHealth:Z.dataHealth??null}},dt()}catch(Z){W(Z instanceof Error?Z.message:"Invalid snapshot")}}),M.addEventListener("activity.appended",Fe=>{try{const Z=JSON.parse(Fe.data);if(Z.length===0)return;mt=mt.concat(Z),dt()}catch{}}),M.addEventListener("session.updated",Fe=>{try{$e=JSON.parse(Fe.data),dt()}catch{}});const yt=Fe=>{try{const Z=JSON.parse(Fe.data);Ee=Array.isArray(Z)?Z:[Z],dt()}catch{}};return M.addEventListener("runtime.updated",yt),M.addEventListener("handoff.updated",Fe=>{try{ge=JSON.parse(Fe.data),dt()}catch{}}),M.addEventListener("decision.updated",Fe=>{try{Se=JSON.parse(Fe.data),dt()}catch{}}),()=>{X.current&&(clearTimeout(X.current),X.current=null),Ae&&clearTimeout(Ae),M.close()}},[ke,g,t,r,T,d,p,m,c,y,h,ne,Te,i]),o.useEffect(()=>{if(t&&!i&&(A.current&&clearInterval(A.current),!(!R||!ne||!Te)))return A.current=setInterval(()=>{T()},s),()=>{A.current&&clearInterval(A.current)}},[t,T,ne,Te,h,s,R,i]),o.useEffect(()=>{!t||i||R&&(!ne||!Te||T())},[t,T,ne,Te,R,i]),{data:I,isLoading:q,error:_,refetch:T,approveDecision:H,rejectDecision:G,approveAllDecisions:we,bulkDecisionAction:De,decisionMutation:k}}const Ki=[{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 cc(e){return Ki.find(t=>t.id===e)??Ki[0]}function Qi(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=Ki.find(i=>i.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function lu(e,t=Date.now()){const s=Qi(e,t);return s?new Date(s).toISOString():null}const Gr="orgx.sandbox_mode",Xr="orgx.demo_mode",wa="orgx.dev_mode",Or="orgx.show_synthetic_entities",Ua="orgx.selected_workspace_id",fr="orgx.onboarding.skip",cu=new Set(["ungrouped","unscoped","unknown"]);function wi(e){const t=(e??"").trim().toLowerCase();return!!(!t||cu.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Ui(){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(Gr)==="1"||window.localStorage.getItem(Xr)==="1"}catch{return!1}}function Wn(){return Ui()}function du(){if(typeof window>"u")return!1;if(Wn())return!0;try{return window.localStorage.getItem(Or)==="1"}catch{return!1}}function uu(e){return Wn()?!0:!wi(e)}function za(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function dc(e,t){const s=za(t.timestamp)-za(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function mu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pu(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 uc(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=mu(e.metadata);return pu(s,["initiative_id","initiativeId"])}function ka(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Wa(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(!Wa(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]||!Wa(s[c],i[c]))return!1}return!0}const fu=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function gi(e,...t){}function hu(e,t,s,i){const r=new Map,a=t.sinceEpoch,l=t.untilEpoch;let c=0,d=0,m=0;for(const p of e??[]){if(!p||typeof p.id!="string")continue;if(s&&p.runId!==s){c++;continue}if(i&&uc(p)!==i){d++;continue}const g=za(p.timestamp);if(g){if(a!==null&&g<a){m++;continue}if(l!==null&&g>l){m++;continue}r.set(p.id,p)}}return gi("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:r.size,runId:s,initiativeId:i,skippedRun:c,skippedInitiative:d,skippedTime:m,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:l?new Date(l).toISOString():null}),Array.from(r.values()).sort(dc)}function Uo(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||!Wa(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),a=!0,r++)}return gi("mergeById",{currentCount:e.length,incomingCount:t.length,added:i,updated:r,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(dc):e}function gu(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:m=Wn()}=e,p=o.useMemo(()=>ka(a),[a]),g=o.useMemo(()=>ka(l),[l]),y=o.useMemo(()=>ka(c),[c]),h=o.useMemo(()=>Qi(s),[s]),I=o.useMemo(()=>lu(s),[s]),b=o.useMemo(()=>{if(s==="custom"){const de=(i==null?void 0:i.trim())??"";return de.length>0?de:null}return I},[i,I,s]),k=o.useMemo(()=>{if(s!=="custom")return null;const de=(r==null?void 0:r.trim())??"";return de.length>0?de:null},[r,s]),E=o.useMemo(()=>{if(b){const de=Date.parse(b);if(Number.isFinite(de))return de}return h},[h,b]),q=o.useMemo(()=>{if(!k)return null;const de=Date.parse(k);return Number.isFinite(de)?de:null},[k]),w=o.useMemo(()=>hu(t,{sinceEpoch:E,untilEpoch:q},p,g),[t,E,q,p,g]),_=m?null:"",[W,A]=o.useState(w),[P,te]=o.useState(()=>_),[R,$]=o.useState(!1),[ne,xe]=o.useState(null),[Te,fe]=o.useState(null),je=o.useRef(null),ae=o.useRef(!1),ie=o.useRef(w);ie.current=w;const X=o.useMemo(()=>`${p??""}|${g??""}|${s}|${b??""}|${k??""}|${y??""}|${m?"demo":"live"}`,[p,g,s,b,k,y,m]),oe=o.useRef(X);o.useEffect(()=>{oe.current!==X&&(oe.current=X,gi("RESET",{reason:"filter/run change",runId:p,initiativeId:g,projectId:y,timeFilterId:s,sinceIso:b,untilIso:k,seedCount:ie.current.length}),A(ie.current),te(_),xe(null),fe(null),ae.current=!1)},[X,_,p,g,y,s,b,k]),o.useEffect(()=>{A(de=>{const ke=Uo(de,w);return ke!==de&&gi("SSE_MERGE",{prevCount:de.length,seedCount:w.length,nextCount:ke.length,delta:ke.length-de.length}),ke})},[w]);const Le=o.useCallback(async()=>{if(m){te(null),xe(null);return}if(P===null)return;if(je.current)return je.current;$(!0);const de=(async()=>{try{const ke=new URLSearchParams;ke.set("limit",String(Math.max(1,Math.min(500,d)))),P.trim().length>0&&ke.set("cursor",P),b&&ke.set("since",b),k&&ke.set("until",k),p&&ke.set("run",p),g&&ke.set("initiative",g),y&&gs(ke,y);const T=await fetch(`/orgx/api/live/activity/page?${ke.toString()}`,{headers:Ot({workspaceId:y})}),z=await T.json().catch(()=>null);if(!T.ok||!z){const we=typeof(z==null?void 0:z.error)=="string"&&z.error.trim()||typeof(z==null?void 0:z.message)=="string"&&z.message.trim()||`Activity paging failed (${T.status})`;throw new Error(we)}const H=Array.isArray(z.activities)?z.activities:[],G=H.filter(we=>!g||uc(we)===g);gi("PAGE_FETCH",{cursor:P,rawCount:H.length,afterFilter:G.length,filteredOut:H.length-G.length,initiativeId:g,runId:p,nextCursor:z.nextCursor??null}),A(we=>{const De=Uo(we,G);return gi("PAGE_MERGE",{prevCount:we.length,pageCount:G.length,nextCount:De.length,added:De.length-we.length}),De}),te(z.nextCursor??null),fe(z.storeUpdatedAt??null),xe(null)}catch(ke){const T=ke instanceof Error?ke.message:"";xe(T?Xt(T):"Activity paging failed"),te(z=>z===""?null:z)}finally{$(!1),je.current=null}})();return je.current=de,de},[P,m,g,d,y,p,b,k]);return o.useEffect(()=>{P===""&&(ae.current||(ae.current=!0,Le()))},[P,Le]),{items:W,hasMore:P!==null,isLoadingMore:R,error:ne,storeUpdatedAt:Te,loadMore:Le,cutoffEpoch:E,sinceIso:b,untilIso:k}}const xu="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",yu="".trim().toLowerCase()==="true"||"".trim()==="1",bu="".trim().toLowerCase()==="true"||"".trim()==="1",vu={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Ia=null,zo=!1,Wo=!1,ro=!1;function wu(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function na(){return ro||!yu?!1:bu?!0:!wu()}function ku(){return na()?(Ia||(Ia=sn(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ro=!0,null))),Ia):Promise.resolve(null)}function Iu(e){if(zo)return!0;try{return e.init(xu,vu),zo=!0,!0}catch{return ro=!0,!1}}async function ao(){const e=await ku();return!e||!Iu(e)?null:e}function Nu(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 ju(){!na()||typeof window>"u"||Wo||(Wo=!0,Nu(()=>{ao()}))}function Au(e){if(!na())return;const t=e.trim();t&&ao().then(s=>{if(s)try{s.identify(t)}catch{}})}function js(e,t){na()&&e.trim()&&ao().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",_u=1500,Su=680,Cu=`<!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>`,Ha={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 Tu(e,t){return e.hasApiKey||e.connectionVerified||e.workspaceName?{...e,lastError:t,nextAction:e.nextAction??"connect"}:{...Ha,status:"error",lastError:t,nextAction:"retry"}}function Na(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:Na(s==null?void 0:s.error)??Na(s==null?void 0:s.message)??Na(s)??Xt(`Request failed (${t.status})`)}}function Ei(e){if(e)try{Au(e)}catch{}}function Mu(){const[e,t]=o.useState(Ha),s=o.useRef(e),[i,r]=o.useState(!0),[a,l]=o.useState(!1),[c,d]=o.useState(!1),m=o.useRef(null),[p,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(fr)==="1");o.useEffect(()=>{s.current=e},[e]),o.useEffect(()=>{!Ui()&&p&&g(!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",P=Tu(s.current,A);return t(P),P}const W={...oi(s.current,_.data),docsUrl:_.data.docsUrl??s.current.docsUrl??Us};return Ei(W.installationId??null),t(W),W},[]);o.useEffect(()=>{let _=!1;return(async()=>{r(!0);const W=await y();_||(t(W),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 W=Math.max(900,e.pollIntervalMs??_u),A=window.setInterval(async()=>{const P=await li(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(P.ok&&P.data){const te={...oi(s.current,P.data),docsUrl:P.data.docsUrl??s.current.docsUrl??Us};Ei(te.installationId??null),t(te)}},W);return()=>{window.clearInterval(A)}},[e.connectUrl,e.connectionVerified,e.pairingId,e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(!Ui()){window.localStorage.removeItem(fr);return}if(p){window.localStorage.setItem(fr,"1");return}window.localStorage.removeItem(fr)}},[p]);const h=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(Cu),_.document.close(),_):null}catch{return null}},[]),I=o.useCallback(async()=>{const _=h();m.current=_,l(!0);try{const W=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=W.data;if(!W.ok||!(A!=null&&A.state)){_&&!_.closed&&_.close();const te=W.error??"Could not start pairing";t(R=>({...R,status:"error",lastError:te,nextAction:"enter_manual_key"}));return}t({...oi(s.current,A.state),docsUrl:A.state.docsUrl??s.current.docsUrl??Us});const P=A.connectUrl;if(P){const te=m.current;let R=!1;if(te&&!te.closed)try{window.setTimeout(()=>{if(!te.closed)try{te.location.href=P}catch{}},Su),R=!0}catch{R=!1}R||(R=!!window.open(P,"_blank","noopener,noreferrer")),R||t($=>({...$,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{m.current=null,l(!1)}},[h]),b=o.useCallback(async _=>{d(!0);try{const W=_.trim(),A=W.replace(/^[a-z]+_/i,""),P=Array.from(new Set([W,A?`oxk_${A}`:"",A?`orgx_${A}`:""].map(R=>R.trim()).filter(R=>R.length>0)));let te="Manual key validation failed";for(const R of P){const $={"Content-Type":"application/json","X-OrgX-Api-Key":R,Authorization:`Bearer ${R}`},ne=await li(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:$,body:JSON.stringify({apiKey:R})}));if(ne.ok&&ne.data){const xe={...oi(s.current,ne.data),docsUrl:ne.data.docsUrl??s.current.docsUrl??Us};return Ei(xe.installationId??null),t(xe),xe}te=ne.error??te}throw t(R=>({...R,status:"manual_key",lastError:te,nextAction:"enter_manual_key"})),new Error(te)}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 Ei(A.installationId??null),t(A),A}const W={...Ha,status:"idle"};return t(W),W},[]),E=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 Ei(A.installationId??null),t(A),A}const W=await y();return t(W),W},[y]),q=o.useCallback(()=>{t(_=>({..._,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),w=o.useMemo(()=>e.hasApiKey&&e.connectionVerified&&(e.status==="connected"||e.status==="pairing"||e.status==="awaiting_browser_auth")?!1:!(p&&Ui()),[p,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:w,isLoading:i,isStarting:a,isSubmittingManual:c,refreshStatus:y,startPairing:I,submitManualKey:b,cancelPairing:E,disconnect:k,skipGate:()=>g(!0),resumeGate:()=>g(!1),backToPairing:q,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 Eu 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 Ru(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 Eu(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 Ex(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 mc 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 Lu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Vi(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 Du(e,t){if(e.status!==404)return!1;const s=Vi(t,["error"])??"",i=Vi(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${i}`)}function $u(e,t,s){if(Du(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=Vi(t,["error","message"])??`${s} (${e.status})`;return Xt(i)}function ja(e,t,s){const i=Lu(t),r=$u(e,i,s),a=Vi(i,["code"]),l=Vi(i,["error_location","errorLocation"]),c=i==null?void 0:i.retryable,d=typeof c=="boolean"?c:!1;return new mc({message:r,status:e.status,code:a,errorLocation:l,retryable:d,details:i})}function Rx(e){return e instanceof mc}const pc=750;async function Ka(e,t){const{initiativeId:s=null,projectId:i=null,authToken:r=null,embedMode:a=!1,queueQueryKey:l,includeQueue:c=!0,includeGraph:d=!0,includeSlices:m=!0,includeAutoContinue:p=!0,includeLiveData:g=!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})})),m&&y.push(e.invalidateQueries({queryKey:["mission-control-slices"]})),p&&y.push(e.invalidateQueries({queryKey:rs.autoContinueStatus({initiativeId:s,authToken:r,embedMode:a})})),g&&(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 Pu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ou(e){const t=Pu(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 hr(e,t){return e&&{...e,pages:e.pages.map(s=>({...s,items:s.items.map(i=>t(i))}))}}async function gr(e){return await e.json().catch(()=>null)}function qu(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 Bu(e,t,s){if(qu(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 Fu(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 Uu(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 Va({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 zu(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 Wu(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function fc(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 hc(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 Hu(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=fc(typeof l.id=="string"?l.id:null),d=hc(typeof l.name=="string"?l.name:null,c);if(c==="unassigned"&&d==="Unassigned")continue;const m=c.toLowerCase();r.has(m)||(r.add(m),i.push({id:c,name:d}))}return i.length===0&&t!=="unassigned"?[{id:t,name:s}]:i}function Ku(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Vu(e){const t=fc(e.runnerAgentId),s=hc(e.runnerAgentName,t),i=Hu(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=Ku(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]:[],m=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:Wu(e),autoRuntimeState:zu(e),queueOrigin:e.queueOrigin??"system",sliceScope:m,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 Va(e){var m,p,g,y,h;const t=e.items.map(I=>Vu(I)),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(I=>I.queueState!=="running"&&I.queueState!=="completed").length,stateCounts:{queued:Math.max(0,Math.floor(((m=e.summary.stateCounts)==null?void 0:m.queued)??0)),running:Math.max(0,Math.floor(((p=e.summary.stateCounts)==null?void 0:p.running)??0)),blocked:Math.max(0,Math.floor(((g=e.summary.stateCounts)==null?void 0:g.blocked)??0)),idle:Math.max(0,Math.floor(((y=e.summary.stateCounts)==null?void 0:y.idle)??0)),completed:Math.max(0,Math.floor(((h=e.summary.stateCounts)==null?void 0:h.completed)??0))}}:void 0,pagination:{offset:r,limit:a,total:s,nextCursor:d,hasMore:c}}}function Gu(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 Xu(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 Qu({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 ae,ie,X,oe,Le,Me,de,ke;const m=so(),p=Wn(),g=Math.max(0,s),y=Math.max(1,Math.min(300,i)),h=o.useRef(null);o.useEffect(()=>()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]);const I=o.useMemo(()=>rs.nextUpQueue({initiativeId:e,projectId:t,offset:g,limit:y,authToken:r,embedMode:a}),[e,t,g,y,r,a]),b=o.useCallback((T,z)=>{const H=rs.autoContinueStatus({initiativeId:T,authToken:r,embedMode:a});m.setQueryData(H,G=>{const we=G&&typeof G=="object"?G:null;return{ok:!0,initiativeId:T,run:z,defaults:(we==null?void 0:we.defaults)??{tokenBudget:null,tickMs:0}}})},[r,a,m]),k=o.useRef(c);o.useEffect(()=>{c!==null&&k.current!==null&&c!==k.current&&m.invalidateQueries({queryKey:I}),k.current=c},[c,m,I]);const E=()=>{h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{h.current=null,m.invalidateQueries({queryKey:rs.liveData({authToken:r,embedMode:a,projectId:t})})},pc)},q=async({includeGraph:T=!0,includeLiveData:z=!0}={})=>{await Ka(m,{initiativeId:e,projectId:t,authToken:r,embedMode:a,queueQueryKey:I,includeGraph:T,includeSlices:!1,includeLiveData:!1}),z&&E()},w=async(T,z)=>{if(p)return Uu(e);const H=new URLSearchParams;e&&H.set("initiative_id",e),gs(H,t,{allTokenWhenMissing:!0}),H.set("offset",String(T)),H.set("limit",String(z));let G;try{G=await fetch(`/orgx/api/mission-control/next-up?${H.toString()}`,{headers:Ot({authToken:r,embedMode:a})})}catch(M){throw new Error(Fu(M,"Failed to load next up queue"))}const we=await gr(G);if(!G.ok){const M=Bu(G,we,"Failed to load next up queue");throw new Error(M)}const De=we??null;if(!De||De.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:T,limit:z,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(du())return Va(De);const pe=De.items.filter(M=>!wi(M.initiativeId));return Va({...De,items:pe})},_=dd({queryKey:I,enabled:l,initialPageParam:g,queryFn:async({pageParam:T})=>{const z=typeof T=="number"&&Number.isFinite(T)?Math.max(0,Math.floor(T)):g;return await w(z,y)},getNextPageParam:T=>{const z=T.pagination;if(!(z!=null&&z.hasMore)||!z.nextCursor)return;const H=Number.parseInt(z.nextCursor,10);if(Number.isFinite(H))return Math.max(0,Math.floor(H))},refetchInterval:T=>{var G;const z=(G=T.state.data)==null?void 0:G.pages;return!z||z.length===0?1e4:z.some(we=>Array.isArray(we.items)&&we.items.some(De=>De.queueState==="running"))?2500:8e3}}),W=Dn({mutationFn:async T=>{if(p)return{ok:!0,initiativeId:T.initiativeId,workstreamId:T.workstreamId,dispatchMode:"slice",sessionId:null};const z=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:T.initiativeId,workstreamId:T.workstreamId,workspaceId:t??void 0,agentId:T.agentId??void 0,scope:T.scope??void 0,maxParallelSlices:typeof T.maxParallelSlices=="number"&&Number.isFinite(T.maxParallelSlices)?Math.max(1,Math.floor(T.maxParallelSlices)):void 0,parallelMode:T.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),H=await gr(z);if(!z.ok)throw ja(z,H,"Failed to dispatch queued workstream");return H??{ok:!0,initiativeId:T.initiativeId,workstreamId:T.workstreamId,agentId:T.agentId??void 0,dispatchMode:"none",sessionId:null}},onMutate:async()=>(await m.cancelQueries({queryKey:I}),{previous:m.getQueryData(I)}),onError:(T,z,H)=>{H!=null&&H.previous&&m.setQueryData(I,H.previous)},onSuccess:(T,z)=>{const H=Ou(T),G=T.outcome==="started"||T.outcome==="fallback_started"||T.outcome==="dispatch_pending";z.initiativeId&&b(z.initiativeId,G?{id:H.activeRunId??`${z.initiativeId}:${z.workstreamId}:play`,initiativeId:z.initiativeId,agentId:z.agentId??"auto",agentName:null,tokenBudget:null,tokensUsed:0,status:H.status==="stopping"?"stopping":"running",stopRequested:!1,updatedAt:new Date().toISOString(),startedAt:new Date().toISOString(),stoppedAt:null,lastError:null,lastTaskId:H.activeTaskId,lastRunId:H.activeRunId??null,activeTaskId:H.activeTaskId,activeRunId:H.activeRunId??null,stopReason:H.stopReason,activeSliceRunIds:H.activeRunIds,activeTaskIds:[],maxParallelSlices:z.maxParallelSlices??1,parallelMode:z.parallelMode??"iwmt"}:null),m.setQueryData(I,we=>hr(we,De=>De.initiativeId!==z.initiativeId||De.workstreamId!==z.workstreamId?De:{...De,queueState:T.outcome==="started"||T.outcome==="fallback_started"?"running":T.outcome==="slice_completed"?"completed":T.outcome==="slice_blocked"?"blocked":De.queueState,playbackState:T.outcome==="started"||T.outcome==="fallback_started"?"running":T.outcome==="slice_completed"?"completed":T.outcome==="slice_blocked"?"blocked":De.playbackState})),q({includeGraph:!1})}}),A=Dn({mutationFn:async T=>{if(p)return{ok:!0,initiativeId:T.initiativeId,workstreamIds:[T.workstreamId],run:null};const z={initiativeId:T.initiativeId,workspaceId:t??void 0,agentId:T.agentId??void 0,tokenBudgetTokens:T.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};T.scope==="workstream"&&T.workstreamId&&(z.workstreamIds=[T.workstreamId]),typeof T.maxParallelSlices=="number"&&Number.isFinite(T.maxParallelSlices)&&(z.maxParallelSlices=T.maxParallelSlices),T.parallelMode==="iwmt"&&(z.parallelMode=T.parallelMode);const H=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(z)}),G=await gr(H);if(!H.ok){const we=Ru(G);throw we||ja(H,G,"Failed to start auto-continue")}return G??{ok:!0,initiativeId:T.initiativeId,workstreamIds:[T.workstreamId],run:null}},onMutate:async()=>(await m.cancelQueries({queryKey:I}),{previous:m.getQueryData(I)}),onError:(T,z,H)=>{H!=null&&H.previous&&m.setQueryData(I,H.previous)},onSuccess:(T,z)=>{b(z.initiativeId,T.run??null),m.setQueryData(I,H=>hr(H,G=>{var De;return G.initiativeId!==z.initiativeId||!(G.workstreamId===z.workstreamId||z.scope!=="workstream")?G:{...G,autoContinue:T.run?{status:T.run.status,activeTaskId:T.run.activeTaskId??null,activeRunId:T.run.activeRunId??((De=T.run.activeSliceRunIds)==null?void 0:De[0])??T.run.lastRunId??null,stopReason:T.run.stopReason,maxParallelSlices:T.run.maxParallelSlices,parallelMode:T.run.parallelMode,updatedAt:T.run.updatedAt}:G.autoContinue}})),q({includeGraph:!1})}}),P=Dn({mutationFn:async T=>{if(p)return{ok:!0,initiativeId:T.initiativeId,run:null};const z=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:T.initiativeId})}),H=await gr(z);if(!z.ok)throw ja(z,H,"Failed to stop auto-continue");return H??{ok:!0,initiativeId:T.initiativeId,run:null}},onMutate:async T=>{await m.cancelQueries({queryKey:I});const z=m.getQueryData(I);return m.setQueryData(I,hr(z,H=>H.initiativeId!==T.initiativeId||!H.autoContinue?H:{...H,autoContinue:{...H.autoContinue,status:"stopping",updatedAt:new Date().toISOString()}})),{previous:z}},onError:(T,z,H)=>{H!=null&&H.previous&&m.setQueryData(I,H.previous)},onSuccess:(T,z)=>{b(z.initiativeId,T.run??null),m.setQueryData(I,H=>hr(H,G=>{var we;return G.initiativeId!==z.initiativeId||!G.autoContinue?G:{...G,autoContinue:T.run?{status:T.run.status,activeTaskId:T.run.activeTaskId??null,activeRunId:T.run.activeRunId??((we=T.run.activeSliceRunIds)==null?void 0:we[0])??T.run.lastRunId??null,stopReason:T.run.stopReason,maxParallelSlices:T.run.maxParallelSlices,parallelMode:T.run.parallelMode,updatedAt:T.run.updatedAt}:null}})),q({includeGraph:!1})}}),te=o.useMemo(()=>{var G;const T=((G=_.data)==null?void 0:G.pages)??[];if(T.length===0)return[];const z=new Set,H=[];for(const we of T)for(const De of we.items){const pe=`${De.initiativeId}:${De.workstreamId}`;z.has(pe)||(z.add(pe),H.push(De))}return H},[(ae=_.data)==null?void 0:ae.pages]),R=o.useMemo(()=>{var H;const T=((H=_.data)==null?void 0:H.pages)??[];let z=0;for(const G of T)typeof G.total=="number"&&Number.isFinite(G.total)&&(z=Math.max(z,G.total));return Math.max(z,te.length)},[te.length,(ie=_.data)==null?void 0:ie.pages]),$=o.useMemo(()=>{var pe;const T=((pe=_.data)==null?void 0:pe.pages)??[];if(T.length===0)return null;const z=T[0],H=T[T.length-1],G=z.pagination,we=H.pagination,De=!!_.hasNextPage;return{offset:G&&Number.isFinite(G.offset)?Math.max(0,Math.floor(G.offset)):g,limit:G&&Number.isFinite(G.limit)?Math.max(1,Math.floor(G.limit)):y,total:R,nextCursor:De?(we==null?void 0:we.nextCursor)??String(((we==null?void 0:we.offset)??g)+((we==null?void 0:we.limit)??y)):null,hasMore:De}},[R,y,g,(X=_.data)==null?void 0:X.pages,_.hasNextPage]),ne=((Le=(oe=_.data)==null?void 0:oe.pages[0])==null?void 0:Le.generatedAt)??null,xe=o.useMemo(()=>{var we,De,pe,Ie,M,Ne;const T=((we=_.data)==null?void 0:we.pages)??[];if(T.length===0)return null;let z=0;const H={queued:0,running:0,blocked:0,idle:0,completed:0};let G=!1;for(const _e of T)_e.summary&&(G=!0,z=Math.max(z,_e.summary.visibleTotal??0),H.queued=Math.max(H.queued,((De=_e.summary.stateCounts)==null?void 0:De.queued)??0),H.running=Math.max(H.running,((pe=_e.summary.stateCounts)==null?void 0:pe.running)??0),H.blocked=Math.max(H.blocked,((Ie=_e.summary.stateCounts)==null?void 0:Ie.blocked)??0),H.idle=Math.max(H.idle,((M=_e.summary.stateCounts)==null?void 0:M.idle)??0),H.completed=Math.max(H.completed,((Ne=_e.summary.stateCounts)==null?void 0:Ne.completed)??0));return G?{visibleTotal:z,stateCounts:H}:null},[(Me=_.data)==null?void 0:Me.pages]),Te=o.useMemo(()=>{var H;const T=((H=_.data)==null?void 0:H.pages)??[],z=new Set;for(const G of T)for(const we of G.degraded??[])typeof we=="string"&&we.trim().length>0&&z.add(we);return Array.from(z)},[(de=_.data)==null?void 0:de.pages]),fe=o.useMemo(()=>d==="initiative"?Gu(te):[],[te,d]),je=o.useMemo(()=>d==="milestone"?Xu(te):[],[te,d]);return{items:te,total:R,summary:xe,pagination:$,generatedAt:ne,degraded:Te,isLoading:_.isLoading,isFetching:_.isFetching,isFetchingNextPage:_.isFetchingNextPage,hasNextPage:!!_.hasNextPage,error:((ke=_.error)==null?void 0:ke.message)??null,refetch:_.refetch,fetchNextPage:_.fetchNextPage,playWorkstream:W.mutateAsync,startWorkstreamAutoContinue:A.mutateAsync,stopInitiativeAutoContinue:P.mutateAsync,isPlaying:W.isPending,isStartingAutoContinue:A.isPending,isStoppingAutoContinue:P.isPending,zoomLevel:d,initiativeGroups:fe,milestoneGroups:je}}async function Nn(e){return await e.json().catch(()=>null)}function fi(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(fi(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 Yu(e){const t=e.authToken??null,s=e.embedMode??!1,i=e.projectId??null,r=Wn(),a=so(),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,Ka(a,{projectId:i,authToken:t,embedMode:s,includeQueue:!1,includeGraph:!1,includeSlices:!1,includeAutoContinue:!1})},pc)},d=async()=>{await Ka(a,{projectId:i,authToken:t,embedMode:s}),c()},m=async w=>{if(r)return{ok:!0,demo:!0,initiativeId:w.initiativeId,workstreamId:w.workstreamId,placement:w.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(w)}),W=await Nn(_);if(_.ok)return W;if(!fi(_,W))throw new Error(jn(_,W,"Failed to move Next Up item"));const A=new URLSearchParams;gs(A,i,{allTokenWhenMissing:!0});const P=await fetch(`/orgx/api/mission-control/next-up?${A.toString()}`,{headers:Ot({authToken:t,embedMode:s})}),te=await Nn(P);if(!P.ok)throw new Error(jn(P,te,"Failed to read queue for move fallback"));const $=(Array.isArray(te==null?void 0:te.items)?te.items:[]).map(je=>{const ae=typeof(je==null?void 0:je.initiativeId)=="string"?je.initiativeId:null,ie=typeof(je==null?void 0:je.workstreamId)=="string"?je.workstreamId:null;return!ae||!ie?null:{initiativeId:ae,workstreamId:ie}}).filter(je=>!!je);if($.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const ne=$.findIndex(je=>je.initiativeId===w.initiativeId&&je.workstreamId===w.workstreamId);if(ne===-1)return{ok:!0,fallback:"reorder-move-skip"};const[xe]=$.splice(ne,1);(w.placement??"top")==="bottom"?$.push(xe):$.unshift(xe);const Te=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:$})}),fe=await Nn(Te);if(!Te.ok)throw new Error(jn(Te,fe,"Failed to move Next Up item with reorder fallback"));return fe??{ok:!0,fallback:"reorder-move"}},p=async w=>{if(r)return{ok:!0,demo:!0,initiativeId:w.initiativeId,workstreamId:w.workstreamId};const _=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(w)}),W=await Nn(_);if(_.ok)return W;if(fi(_,W)){const A=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(w)}),P=await Nn(A);if(!A.ok)throw new Error(jn(A,P,"Failed to remove item from queue with legacy fallback"));return P??{ok:!0,fallback:"next-up-unpin"}}throw new Error(jn(_,W,"Failed to remove item from queue"))},g=Dn({mutationFn:async w=>{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(w)}),W=await Nn(_);if(!_.ok)throw new Error(jn(_,W,"Failed to pin Next Up item"))},onSuccess:()=>{d()}}),y=Dn({mutationFn:async w=>{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(w)}),W=await Nn(_);if(!_.ok)throw new Error(jn(_,W,"Failed to unpin Next Up item"))},onSuccess:()=>{d()}}),h=Dn({mutationFn:async w=>{if(r)return{ok:!0,demo:!0,updated:w.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(w)}),W=await Nn(_);if(!_.ok)throw new Error(jn(_,W,"Failed to reorder Next Up queue"))},onSuccess:()=>{d()}}),I=Dn({mutationFn:m,onSuccess:()=>{d()}}),b=Dn({mutationFn:async w=>{if(r)return{ok:!0,demo:!0,initiativeId:w.initiativeId,workstreamId:w.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(w)}),W=await Nn(_);if(!_.ok){if(fi(_,W)){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:w.initiativeId})}),P=await Nn(A);if(!A.ok)throw new Error(jn(A,P,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(jn(_,W,"Failed to stop triage"))}return W},onSuccess:()=>{d()}}),k=Dn({mutationFn:p,onSuccess:()=>{d()}}),E=Dn({mutationFn:async w=>{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(w)}),W=await Nn(_);if(!_.ok){if(fi(_,W)&&w.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:w.initiativeId})}),P=await Nn(A);if(!A.ok)throw new Error(jn(A,P,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(jn(_,W,"Failed to clear Next Up lifecycle state"))}return W},onSuccess:()=>{d()}}),q=Dn({mutationFn:async w=>{if(r)return{ok:!0,demo:!0,updated:w.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(w)}),W=await Nn(_);if(!_.ok){if(!fi(_,W))throw new Error(jn(_,W,"Failed to apply bulk queue action"));const A=await Promise.all(w.items.map(async $=>{try{return w.action==="remove"?await p($):await m({initiativeId:$.initiativeId,workstreamId:$.workstreamId,placement:w.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ne){return{ok:!1,error:ne instanceof Error?ne.message:"Queue action failed"}}})),P=A.filter($=>$.ok).length,te=A.length-P,R=A.filter($=>!$.ok&&$.error).map($=>$.error);return{ok:te===0,updated:P,failed:te,errors:R,fallback:"sequential"}}return W},onSuccess:()=>{d()}});return{pin:g.mutateAsync,unpin:y.mutateAsync,reorder:h.mutateAsync,move:I.mutateAsync,remove:k.mutateAsync,stopTriage:b.mutateAsync,clear:E.mutateAsync,bulk:q.mutateAsync,isPinning:g.isPending,isUnpinning:y.isPending,isReordering:h.isPending,isMoving:I.isPending,isRemoving:k.isPending,isStoppingTriage:b.isPending,isClearing:E.isPending,isBulking:q.isPending}}function gc(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Ju(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:gc(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 Zu(e,t,s,i){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:gc(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 em(e={}){const{enabled:t=!0,workspaceId:s=null,status:i="open",authToken:r=null,embedMode:a=!1}=e,l=so(),c=rs.triageQueue({workspaceId:s,status:i,authToken:r,embedMode:a}),d=ei({queryKey:c,queryFn:()=>Ju(s,i,r,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),m=Dn({mutationFn:async({itemId:h,payload:I})=>Zu(h,I,r,a),onSuccess:()=>{l.invalidateQueries({queryKey:c})}}),p=o.useCallback(async(h,I,b)=>m.mutateAsync({itemId:h,payload:{action:I,note:b==null?void 0:b.note,optionId:b==null?void 0:b.optionId,snoozeDurationMinutes:b==null?void 0:b.snoozeDurationMinutes}}),[m]),g=o.useMemo(()=>{var h,I,b;return{items:((h=d.data)==null?void 0:h.items)??[],total:((I=d.data)==null?void 0:I.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((b=d.data)==null?void 0:b.degraded)??[],refetch:d.refetch}},[d]),y=o.useMemo(()=>({performAction:p,isActing:m.isPending,lastActionError:m.error?m.error.message:null}),[p,m.isPending,m.error]);return{model:g,actions:y}}function me(...e){return e.filter(Boolean).join(" ")}const D={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"},qi={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)"}},xc={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ga={Pace:"Product",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Ho={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 yc(e){if(Ga[e])return{domain:Ga[e],color:xc[e]??"rgba(255,255,255,0.4)"};const t=e.toLowerCase().replace(/[_\s-]+/g,"-");for(const[s,i]of Object.entries(Ho))if(t===s||t===`${s}-agent`||t===`orgx-${s}`||t===`orgx-${s}-agent`)return i;for(const[s,i]of Object.entries(Ho))if(t.includes(s))return i;return null}function oo(e){var t;return xc[e]??((t=yc(e))==null?void 0:t.color)??"rgba(255, 255, 255, 0.4)"}function Gi(e){var t;return Ga[e]??((t=yc(e))==null?void 0:t.domain)??null}function tm(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}},Lx={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}}},xr={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}})},Dx={initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:Wt.easingStandard}},sa="/orgx/live/assets/Fm0FhtnV.png";function bc({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??D.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??D.lime;return n.jsx(bc,{size:s,className:t,stroke:l,strokeWidth:r.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}if(e==="milestone"){const l=i??D.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??D.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??D.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??D.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??D.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??D.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??D.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??D.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??D.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 nm=[{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"}],qr=[{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."}],sm=[{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."}],Ko="openclaw plugins install @useorgx/openclaw-plugin",im=6500;function rm(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 am={hidden:{},visible:{transition:{staggerChildren:.07}}},As={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},om={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 Aa(e){const t=qr.length;return(e+t)%t}function lm({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"),[m,p]=o.useState("idle"),[g,y]=o.useState(0),[h,I]=o.useState(!1),b=e.hasApiKey&&e.keySource&&e.keySource!=="none",k=qr[g];o.useEffect(()=>{if(c==="idle")return;const w=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(w)},[c]),o.useEffect(()=>{if(m==="idle")return;const w=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(w)},[m]),o.useEffect(()=>{if(h)return;const w=window.setInterval(()=>{y(_=>Aa(_+1))},im);return()=>window.clearInterval(w)},[h]);const E=async()=>{try{await navigator.clipboard.writeText(Ko),d("ok")}catch{d("error")}},q=async()=>{try{const w={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(w,null,2)),p("ok")}catch{p("error")}};return n.jsxs(ce.section,{variants:am,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(ce.div,{variants:As,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:sa,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(ce.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(ce.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(ce.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:()=>I(!0),onMouseLeave:()=>I(!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:[g+1,"/",qr.length]})]}),n.jsx(bt,{initial:!1,mode:"wait",children:n.jsxs(ce.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(w=>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:w.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:w.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:w.detail})]},`${k.id}-${w.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:qr.map((w,_)=>{const W=_===g;return n.jsx("button",{type:"button",onClick:()=>y(_),"aria-label":`View slide ${_+1}`,className:`h-1.5 rounded-full transition-all ${W?"w-6 bg-lime":"w-2 bg-white/24 hover:bg-white/38"}`},w.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(w=>Aa(w-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(w=>Aa(w+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:nm.map(w=>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 ${om[w.iconType]}`,children:n.jsx(en,{type:w.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:w.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:w.desc})]},w.label))}),n.jsxs(ce.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(ce.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:Ko}),n.jsx("button",{type:"button",onClick:()=>{E()},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"})]}),b&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",rm(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:sm.map(w=>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:w.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:w.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:w.detail})]},w.label))})]})]})]}),n.jsx(ce.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 q(),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:m==="ok"?"Copied":m==="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(ce.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(Gr,"1"),window.localStorage.removeItem(Xr)}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 cm={hidden:{},visible:{transition:{staggerChildren:.06}}},Fs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function dm({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 g=/^[a-z]+_/i.test(p)?p:`oxk_${p}`;try{await t(g),r("")}catch(y){const h=y instanceof Error?y.message:"Failed to validate API key.";l(Xt(h))}},m=a!==null;return n.jsxs(ce.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-6 sm:px-8 sm:pt-8",children:[n.jsxs(ce.div,{variants:Fs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:sa,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(ce.h3,{variants:Fs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ce.p,{variants:Fs,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(ce.p,{variants:Fs,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(ce.div,{variants:Fs,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(ce.div,{variants:Fs,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 ${m?"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"})]}),m&&n.jsx(ce.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(ce.div,{variants:Fs,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 Vo="orgx.user.display-name",Go="orgx.user.avatar-seed-suffix";function Xo(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Qo(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function um(){const[e,t]=o.useState(()=>Xo(Vo)),[s,i]=o.useState(()=>Xo(Go)),r=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();Qo(Vo,d),t(d)},[]),l=o.useCallback(()=>{const c=String(Date.now());Qo(Go,c),i(c)},[]);return{displayName:e,avatarSeed:r,updateName:a,regenerateAvatar:l}}function mm(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function pm(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 Yo=[D.lime,D.teal,D.iris,D.cyan];function fm(e,t,s,i,r,a){const l=_=>_*Math.PI/180,c=Math.cos,d=Math.sin,m=l(r),p=l(a),g=a-r>180?1:0,y=e+i*c(m),h=t+i*d(m),I=e+i*c(p),b=t+i*d(p),k=e+s*c(p),E=t+s*d(p),q=e+s*c(m),w=t+s*d(m);return[`M ${y} ${h}`,`A ${i} ${i} 0 ${g} 1 ${I} ${b}`,`L ${k} ${E}`,`A ${s} ${s} 0 ${g} 0 ${q} ${w}`,"Z"].join(" ")}function hm(e){const t=pm(mm(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,m=6+Math.floor(t()*6),p=360/m,g=1.5+t()*2;for(let y=0;y<m;y++){if(t()<.15)continue;const h=y*p+g/2,I=(y+1)*p-g/2,b=Yo[Math.floor(t()*Yo.length)],k=.25+t()*.55;i.push({d:fm(r,a,c,d,h,I),fill:b,opacity:k})}}return i}function vc({seed:e,size:t,className:s,animate:i=!0}){const r=o.useMemo(()=>hm(e),[e]);return n.jsxs(ce.svg,{viewBox:"0 0 100 100",width:t,height:t,className:me("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:D.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:D.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:D.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(ce.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 gm({onComplete:e}){const{displayName:t,updateName:s}=um(),[i,r]=o.useState(t),a=o.useCallback(()=>{s(i),e()},[i,s,e]),l=o.useCallback(()=>{e()},[e]),c=o.useCallback(m=>{m.key==="Enter"&&a()},[a]),d=(i.trim()||"orgx-user")+"";return n.jsx(ce.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(vc,{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:m=>r(m.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 xm=[{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 ym({className:e,compact:t=!1}){return n.jsxs("div",{className:me("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"]}),xm.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 Jo="orgx.user.name-asked";function bm(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 vm(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 wm(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Zo={idle:"bg-white/40",active:"bg-lime",error:"bg-red-400"},_a="orgx.onboarding.mc_hint.dismissed",Sa={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 km({state:e,isLoading:t,isStarting:s,isSubmittingManual:i,onRefresh:r,onStartPairing:a,onSubmitManualKey:l,onBackToPairing:c,onUseManualKey:d,onSkip:m}){const[p,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(_a)==="1"),[y,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Jo)!=="1"),I=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Jo,"1"),h(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(_a,"1"):window.localStorage.removeItem(_a))},[p]);const b=e.status==="manual_key",k=e.status==="awaiting_browser_auth"||e.status==="pairing",E=wm(e.status),q=E==="active"&&e.status!=="connected",w=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(ce.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${b?"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(ce.div,{...Sa,children:n.jsx(gm,{onComplete:I})},"welcome-name"):b?n.jsx(ce.div,{...Sa,children:n.jsx(dm,{isSubmitting:i,onSubmit:l,onBack:c})},"manual"):n.jsx(ce.div,{...Sa,children:n.jsx(lm,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:m})},"explainer")}),!t&&(k||e.status==="connected")&&n.jsxs(ce.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:[q&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Zo[E]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Zo[E]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:bm(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:vm(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"})]})]}),w&&n.jsxs(ce.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:()=>g(!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(ym,{compact:!0})})]})})}function Im({children:e,color:t,pulse:s,title:i}){const r=t??D.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 ia({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),m=o.useRef(null);o.useEffect(()=>{if(!e)return;m.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const I=d.current;if(!I)return;const b=I.querySelector('[data-modal-autofocus="true"]');if(b){b.focus();return}const k=I.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():I.focus()})();const y=I=>{if(I.key==="Escape"){if(!l)return;if(!c){const _=I.target;if(_&&(_.tagName==="INPUT"||_.tagName==="TEXTAREA"||_.tagName==="SELECT"||_.isContentEditable))return}I.preventDefault(),t();return}if(I.key!=="Tab")return;const b=d.current;if(!b)return;const k=b.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(k.length===0){I.preventDefault(),b.focus();return}const E=k[0],q=k[k.length-1],w=document.activeElement;!I.shiftKey&&w===q?(I.preventDefault(),E.focus()):I.shiftKey&&w===E&&(I.preventDefault(),q.focus())},h=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",y),()=>{var I;document.body.style.overflow=h,document.removeEventListener("keydown",y),(I=m.current)==null||I.focus()}},[e,t,l,c]);const p=n.jsx(bt,{children:e&&n.jsxs(ce.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(ce.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:D.cardBgElevated,borderColor:D.cardBorderStrong},onClick:g=>g.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:ld.createPortal(p,document.body)}const Nm=[{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 jm({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:Nm.map(i=>{const r=e===i.id;return n.jsxs("button",{type:"button",onClick:()=>t(i.id),"aria-current":r?"page":void 0,className:me("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(ce.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(ce.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:D.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:me("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:D.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:me("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:me("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Am={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"},_m={xs:24,sm:32,md:40,lg:64},Sm="orgx.user.display-name",Cm="orgx.user.avatar-seed-suffix",Tm="/orgx/live/",An=e=>`${Tm.replace(/\/+$/,"/")}${e}`,Mm={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")},Em=[{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 Rm(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of Em)if(s.test.test(t))return Mm[s.key];return null}function Lm(e){return typeof e=="string"?e.trim().toLowerCase():""}function el(e){const t=Lm(e);return t?!!(t==="you"||t==="main"||t==="me"||t==="user"||t==="usr"||t.startsWith("user_")||t.startsWith("usr_")):!1}function Dm(){if(typeof window>"u")return"orgx-user";try{const e=(window.localStorage.getItem(Sm)??"").trim(),t=window.localStorage.getItem(Cm)??"";return`${e||"orgx-user"}${t}`}catch{return"orgx-user"}}function Gt({name:e,size:t="xs",hint:s,src:i}){const r=oo(e),[a,l]=o.useState(!1),c=o.useMemo(()=>el(e)||el(s),[s,e]),d=o.useMemo(()=>c?Dm():null,[c]),m=o.useMemo(()=>i&&i.trim()?i:Rm(e,s),[s,e,i]),p=!!(!c&&m&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Am[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(vc,{seed:d,size:_m[t],animate:!1,className:"h-full w-full"}):p?n.jsx("img",{src:m??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>l(!0),loading:"lazy"}):tm(e)})}Gt.displayName="AgentAvatar";const $m={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:me("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",$m[t],s),...i,children:e})}function Pm(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=wc(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",m={id:c.id,label:c.title||Qs(c.id,"Milestone"),type:"milestone",status:d,progress:{done:c.done,total:c.total}};c.total>0&&(m.children=Array.from({length:c.total},(p,g)=>({id:`${c.id}-task-${g}`,label:`Task ${g+1}`,type:"task",status:g<c.done?"done":"pending"}))),l.children.push(m)}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,m)=>({id:d,label:Qs(d,"Task"),type:"task",status:m<c?"done":"pending"}))}r.children.push(l)}t.push(r)}return t}function $x(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:wc(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 wc(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 Om(e){return e==="done"||e==="completed"?"done":e==="active"||e==="running"||e==="in_progress"?"active":e==="blocked"?"blocked":e==="failed"?"failed":"pending"}function qm(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:Om(s.status)}))}))}function Bm(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 Px=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?D.teal:`${D.lime}99`}})},r.id)})})}),Fm={active:qi.active,done:qi.done,blocked:qi.blocked,planned:qi.planned};function yr({label:e,count:t,tone:s,nodes:i,defaultOpen:r,compact:a}){const[l,c]=o.useState(r),d=Fm[s]??qi.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(m=>!m),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(ce.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(ce.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(Nc,{nodes:i,compact:a})})})})]})}const Um=o.memo(function({nodes:t,compact:s=!1}){const i=Bm(t);return n.jsxs("div",{className:"space-y-2",children:[i.blocked.length>0&&n.jsx(yr,{label:"BLOCKED",count:i.blocked.length,tone:"blocked",nodes:i.blocked,defaultOpen:!0,compact:s}),i.inProgress.length>0&&n.jsx(yr,{label:"IN PROGRESS",count:i.inProgress.length,tone:"active",nodes:i.inProgress,defaultOpen:!0,compact:s}),i.completed.length>0&&n.jsx(yr,{label:"COMPLETED",count:i.completed.length,tone:"done",nodes:i.completed,defaultOpen:!1,compact:s}),i.upcoming.length>0&&n.jsx(yr,{label:"UPCOMING",count:i.upcoming.length,tone:"planned",nodes:i.upcoming,defaultOpen:!1,compact:s})]})});function kc(e){switch(e){case"done":return D.lime;case"active":return D.teal;case"blocked":return D.amber;case"failed":return D.red;default:return"rgba(255,255,255,0.15)"}}function zm(e){const t=kc(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Wm=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(ce.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${r}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Hm=16,Km=14,tl=8,Vm=8,Gm=28,Xm=24,Qm=24,Ym=20,Ca="rgba(255,255,255,0.07)";function Jm(e){const t=e?Km:Hm,s=t+Vm+4;return{iconSz:t,colW:s,rowH:e?Qm:Gm,rowHTask:e?Ym:Xm}}function Ic({node:e,depth:t,isLast:s,activeId:i,compact:r,index:a,taskLimit:l,expanded:c,onToggleExpand:d}){const m=i===e.id||e.highlight,p=e.progress&&e.progress.total>0,g=e.type==="task",{iconSz:y,colW:h,rowH:I,rowHTask:b}=Jm(r),k=g?b:I,E=e.children??[],q=E.filter(R=>R.type==="task"),w=E.filter(R=>R.type!=="task"),_=q.length>l&&!c,W=_?q.slice(0,l):q,A=q.length-W.length,P=[...w,...W],te=P.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:Ca,left:(t-1)*h+h/2,top:0,bottom:s?void 0:0,height:s?k/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:Ca,left:(t-1)*h+h/2,top:k/2,width:h}})]}),n.jsxs(ce.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${m?"rounded-md bg-white/[0.03]":""}`,style:{height:k,paddingLeft:t*h},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:h,height:k},children:g?n.jsx("span",{className:"inline-block rounded-full",style:{...zm(e.status),width:tl,height:tl}}):n.jsx(en,{type:e.type,size:y,accent:m?D.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 ${g?`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"} ${m?"!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&&!g&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Wm,{done:e.progress.done,total:e.progress.total,color:kc(e.status)})})]})]}),te&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Ca,left:t*h+h/2,top:k/2,height:k/2}}),te&&n.jsxs("div",{children:[P.map((R,$)=>n.jsx(Ic,{node:R,depth:t+1,isLast:$===P.length-1&&!_,activeId:i,compact:r,index:a+$+1,taskLimit:l,expanded:c,onToggleExpand:d},R.id)),_&&n.jsxs(ce.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+P.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:b,paddingLeft:(t+1)*h+h},children:["+",A," more · see all"]}),n.jsx(bt,{children:c&&q.length>l&&n.jsx(ce.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:b},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)*h+h},children:"show less"})})]})]})}const Nc=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,m)=>n.jsx(Ic,{node:d,depth:0,isLast:m===t.length-1,activeId:i,compact:r,index:m,taskLimit:a,expanded:l,onToggleExpand:()=>c(p=>!p)},d.id))})}),Xa={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"}},Zm=Object.keys(Xa);function nl(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of Zm)if(t.includes(s))return s;return"engineering"}function sl(e){return Xa[e]??Xa.engineering}const ci={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ri={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},il={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},rl={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 ep(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=rl[i];if(r){const a=Ri[r]??"";return{name:r,domain:a,color:ci[r]??s.color,displayLabel:a?`${r} (${a})`:r}}for(const[a,l]of Object.entries(il))if(i.includes(a)){const c=Ri[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=Ri[i]??"";return{name:i,domain:l,color:ci[i],displayLabel:l?`${i} (${l})`:i}}const r=i.toLowerCase(),a=rl[r];if(a){const l=Ri[a]??"";return{name:a,domain:l,color:ci[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(il))if(r.includes(l)){const d=Ri[c]??"";return{name:c,domain:d,color:ci[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function Ox({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 tp=new Set(["running","in_progress","working","dispatching"]),np=new Set(["running","dispatching"]),sp=3*6e4;function al(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=sp:!1}function ip(e){const t=Lt(e.status??""),s=Lt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:tp.has(t)?!0:t==="active"||s==="active"?al(e.lastHeartbeatAt):t==="queued"||t==="pending"||t==="planning"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?al(e.lastHeartbeatAt):!1}function jc(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function rp(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 ap(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 op(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 Qa(e,t){if(!e)return t;const s=e.trim();return s?zn(s)?`${t} ${Ss(s)}`:s:t}const lp=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),cp=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function dp(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?lp.has(t)||t.startsWith("telegram:"):!1}function up(e){if(!e)return!1;const t=e.trim();return t?cp.some(s=>s.test(t)):!1}function Ac({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var k,E,q,w,_,W;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 P=(k=A.runId)==null?void 0:k.trim();!P||r.has(P)||r.set(P,A)}const a=new Map;for(const A of e){const P=((E=A.initiativeId)==null?void 0:E.trim())??"",te=((q=A.workstreamId)==null?void 0:q.trim())??"";if(!P||!te)continue;const R=`${P}:${te}`;a.has(R)||a.set(R,A)}const l=new Set;for(const A of e){const P=(w=A.runId)==null?void 0:w.trim();P&&l.add(P)}const c=[];for(const A of t){const P=(A.sliceKind??"").trim().toLowerCase();if(P&&P!=="work_slice"||!np.has(A.status))continue;const te=(A.runId??A.sliceRunId??"").trim();if(!te)continue;const R=Hs(A.initiativeIds,A.initiativeId),$=Hs(A.workstreamIds,A.workstreamId),ne=R[0]??null,xe=$[0]??null;if(!ne||!xe)continue;const Te=[];for(const X of R)for(const oe of $)!X||!oe||Te.push(`${X}:${oe}`);if(!(l.has(te)||Te.some(X=>a.has(X))))continue;const je=r.get(te)??(Te.length>0?Te.map(X=>a.get(X)??null).find(X=>!!X)??null:null),ae=ne?i.get(ne)??ne:null,ie=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:je??null,runId:te,status:Lt(A.status),title:A.workstreamTitle??(je==null?void 0:je.title)??`Work slice ${A.sliceRunId.slice(0,8)}`,subtitle:A.statusExplainer??A.lastEventSummary??(je==null?void 0:je.lastEventSummary)??null,progress:ie??(je==null?void 0:je.progress)??null,initiativeId:ne,initiativeIds:R,initiativeTitle:ae,workstreamId:xe,workstreamIds:$,iwmtId:A.iwmtId??null,iwmtIds:Hs(A.iwmtIds,A.iwmtId),workstreamTitle:A.workstreamTitle??(je==null?void 0:je.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??(je==null?void 0:je.updatedAt)??null,scope:A.scope,milestoneProgress:(_=A.scopeProgress)==null?void 0:_.milestones})}c.sort((A,P)=>di(P.updatedAt)-di(A.updatedAt));const d=[],m=new Set,p=new Set,g=new Set;for(const A of c){const P=A.initiativeId??((W=A.initiativeIds)==null?void 0:W[0])??"none",te=A.workstreamId?`scope:${P}:${A.workstreamId}`:null,R=te??(A.runId?`run:${A.runId}`:A.key);m.has(R)||(m.add(R),A.runId&&p.add(A.runId),te&&g.add(te),d.push(A))}const y=e.filter(A=>{if(!ip(A))return!1;const P=(A.initiativeId??"").trim(),te=(A.workstreamId??"").trim();if(P.length===0||te.length===0)return!1;const R=(A.runId??"").trim();return R&&p.has(R)?!1:!g.has(`scope:${P}:${te}`)});y.sort((A,P)=>{const te=di(A.updatedAt??A.lastEventAt??A.startedAt);return di(P.updatedAt??P.lastEventAt??P.startedAt)-te});const h=[],I=new Set;for(const A of y){const P=A.workstreamId&&A.workstreamId.trim().length>0?`${A.initiativeId??"none"}:${A.workstreamId}`:A.runId;I.has(P)||(I.add(P),h.push(A))}const b=h.map(A=>{var P;return{key:`session:${A.id}`,source:"session",session:A,runId:A.runId,status:Lt(A.status??""),title:A.title,subtitle:(P=A.lastEventSummary)!=null&&P.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,...b].sort((A,P)=>di(P.updatedAt)-di(A.updatedAt))}const mp=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:m,onOpenSession:p,onFocusRunId:g,onPlayWorkstream:y,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:b,onIntervene:k,onOpenSliceDetail:E}){const[q,w]=o.useState(null),[_,W]=o.useState(null),[A,P]=o.useState(null),[te,R]=o.useState(null),$=o.useMemo(()=>{const X=new Map;if(!Array.isArray(s))return X;for(const oe of s){const Le=Hs(oe.initiativeIds,oe.initiativeId),Me=Hs(oe.workstreamIds,oe.workstreamId);for(const ke of Le)for(const T of Me){if(!ke||!T)continue;const z=`${ke}:${T}`;X.has(z)||X.set(z,oe)}const de=(oe.runId??oe.sliceRunId??"").trim();de&&!X.has(`run:${de}`)&&X.set(`run:${de}`,oe)}return X},[s]),ne=o.useMemo(()=>Ac({sessions:t,sliceRuns:s,initiatives:i}),[i,t,s]),xe=o.useMemo(()=>{const X=new Map;for(const oe of ne){const Le=Lt(oe.status);X.set(Le,(X.get(Le)??0)+1)}return Array.from(X.entries()).sort((oe,Le)=>Le[1]-oe[1]).map(([oe,Le])=>({status:oe,count:Le}))},[ne]),Te=o.useMemo(()=>q?ne.filter(X=>Lt(X.status)===q):ne,[q,ne]),fe=o.useMemo(()=>{var Me,de;const X=new Map,oe=[];for(const ke of Te){const T=(((Me=ke.initiativeIds)==null?void 0:Me[0])??ke.initiativeId??"").trim(),z=(((de=ke.workstreamIds)==null?void 0:de[0])??ke.workstreamId??"").trim();if(!T){oe.push(ke);continue}let H=X.get(T);H||(H={title:ke.initiativeTitle??T,wsMap:new Map},X.set(T,H));const G=z||"__none__";let we=H.wsMap.get(G);we||(we={title:ke.workstreamTitle??(z||"Unassigned"),rows:[],completedCount:0,lastActivity:null},H.wsMap.set(G,we));const De=Lt(ke.status);if(De==="completed"||De==="done"?we.completedCount+=1:we.rows.push(ke),ke.updatedAt){const pe=Date.parse(ke.updatedAt),Ie=we.lastActivity?Date.parse(we.lastActivity):0;Number.isFinite(pe)&&pe>Ie&&(we.lastActivity=ke.updatedAt)}}const Le=[];for(const[ke,T]of X){const z=[];for(const[H,G]of T.wsMap)z.push({workstreamId:H,workstreamTitle:G.title,rows:G.rows,completedCount:G.completedCount,lastActivityAt:G.lastActivity});z.sort((H,G)=>{const we=H.lastActivityAt?Date.parse(H.lastActivityAt):0;return(G.lastActivityAt?Date.parse(G.lastActivityAt):0)-we}),Le.push({initiativeId:ke,initiativeTitle:T.title,workstreams:z})}return Le.sort((ke,T)=>{const z=Math.max(0,...ke.workstreams.map(G=>G.lastActivityAt?Date.parse(G.lastActivityAt):0));return Math.max(0,...T.workstreams.map(G=>G.lastActivityAt?Date.parse(G.lastActivityAt):0))-z}),{groups:Le,ungrouped:oe}},[Te]),[je,ae]=o.useState(new Set),ie=async(X,oe,Le)=>{if(X.session){R(null),W(X.session.id);try{await oe(X.session),R(Le)}catch(Me){const de=Me instanceof Error?Me.message:"";R(de?Xt(de):"Workstream action failed")}finally{W(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:ne.length})]})}):null,xe.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:()=>w(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${q===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:ne.length})]}),xe.map(({status:X,count:oe})=>n.jsxs("button",{type:"button",onClick:()=>w(Le=>Le===X?null:X),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${q===X?"border-lime/30 bg-lime/12 text-lime":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[jc(X),n.jsx("span",{className:"tabular-nums opacity-70",children:oe})]},X))]}),te&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:te}),Te.length===0?ne.length===0&&d>0&&m?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:"All clear"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active runs right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"item needs":"items need"," your attention."]})]}),n.jsxs("button",{type:"button",onClick:m,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:ne.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(ce.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[fe.groups.map(X=>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:Et(X.initiativeTitle&&!zn(X.initiativeTitle)?X.initiativeTitle:Qa(X.initiativeId,"Initiative"))})]}),X.workstreams.map(oe=>{const Le=`${X.initiativeId}:${oe.workstreamId}`,Me=je.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:oe.rows.map((de,ke)=>n.jsx(ol,{row:de,index:ke,sliceRunByScope:$,busySessionId:_,expandedRowKey:A,setExpandedRowKey:P,onOpenSession:p,onFocusRunId:g,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:b,onPlayWorkstream:y,onIntervene:k,onOpenSliceDetail:E,runWorkstreamAction:ie,showInitiativeLabel:!1},de.key))}),oe.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>ae(de=>{const ke=new Set(de);return ke.has(Le)?ke.delete(Le):ke.add(Le),ke}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:Me?`Hide ${oe.completedCount} completed`:`${oe.completedCount} completed`})})]},oe.workstreamId)})]},X.initiativeId)),fe.ungrouped.length>0&&n.jsxs("div",{children:[fe.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:fe.ungrouped.map((X,oe)=>n.jsx(ol,{row:X,index:oe,sliceRunByScope:$,busySessionId:_,expandedRowKey:A,setExpandedRowKey:P,onOpenSession:p,onFocusRunId:g,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:b,onPlayWorkstream:y,onIntervene:k,onOpenSliceDetail:E,runWorkstreamAction:ie,showInitiativeLabel:!0},X.key))})]})]})})]})});function ol({row:e,index:t,sliceRunByScope:s,busySessionId:i,expandedRowKey:r,setExpandedRowKey:a,onOpenSession:l,onFocusRunId:c,onPauseWorkstream:d,onResumeWorkstream:m,onRestartSession:p,onPlayWorkstream:g,onIntervene:y,onOpenSliceDetail:h,runWorkstreamAction:I,showInitiativeLabel:b=!0}){var Le,Me,de,ke,T,z,H,G,we,De;const k=Lt(e.status??""),E=e.updatedAt,q=e.subtitle?e.subtitle:E?`Updated ${Rt(E)}`:null,w=b&&(e.initiativeTitle||e.initiativeId)?Et(e.initiativeTitle&&!zn(e.initiativeTitle)?e.initiativeTitle:Qa(e.initiativeId,"Initiative")):null,_=(Le=e.title)!=null&&Le.trim()?e.title:"",W=dp(_)&&((Me=e.workstreamTitle)!=null&&Me.trim())?e.workstreamTitle:_||e.workstreamTitle||"",A=Qa(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),P=Et(W&&!zn(W)?W:A),te=q&&!up(q)?Et(q):null,R=op(e.progress),$=["running","active","in_progress","working","planning","dispatching"].includes(k),ne=["paused","blocked","queued","pending"].includes(k),xe=p??g,Te=R===null&&["running","active","in_progress","working","planning","dispatching"].includes(k),fe=e.session?i===e.session.id:!1,je=r===e.key,ae=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),ie=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),X=e.scope==="task"?"task":e.scope==="milestone"?"milestone":e.scope==="workstream"||e.source==="slice"?"workstream":"session",oe=ep((de=e.session)==null?void 0:de.agentId,(ke=e.session)==null?void 0:ke.agentName);return n.jsxs(ce.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:()=>h==null?void 0:h(e,ie),role:"button",tabIndex:0,onKeyDown:pe=>{(pe.key==="Enter"||pe.key===" ")&&(pe.preventDefault(),h==null||h(e,ie))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${ap(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":oe.color}:void 0,children:n.jsx(Gt,{name:((T=e.session)==null?void 0:T.agentName)??"OrgX",hint:((z=e.session)==null?void 0:z.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[w?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:w}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(en,{type:X,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:P,children:P})]}),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] ${rp(k)}`,children:jc(k)}),E&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:pd(new Date(E),{addSuffix:!0})})]}),te?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:te,children:te}):null,null,(R!==null||Te)&&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:R===null?"Live":`${R}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${R===100?" shimmer-on-complete":""}`,children:R===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,R)}%`,background:`linear-gradient(90deg, ${sl(nl((H=e.session)==null?void 0:H.agentId)).gradient[0]}, ${sl(nl((G=e.session)==null?void 0:G.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(Nc,{nodes:Pm({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((pe,Ie)=>pe+Ie.total,0),completedTasks:e.milestoneProgress.reduce((pe,Ie)=>pe+Ie.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((we=e.session)==null?void 0:we.agentName)??null,agentId:((De=e.session)==null?void 0:De.agentId)??null}),activeId:e.workstreamId,compact:!0})}),ae?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:pe=>{pe.stopPropagation(),a(Ie=>Ie===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:je?"Hide details":"Slice details"}),je?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:pe=>pe.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&&$&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:fe,onClick:()=>void I(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&&ne&&m&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:fe,onClick:()=>void I(e,m,`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&&xe&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:fe,onClick:()=>void I(e,xe,`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:fe,onClick:()=>void I(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 pp={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 ra({icon:e="inbox",headline:t,description:s,primaryAction:i,secondaryAction:r,className:a}){return n.jsxs(ce.div,{className:me("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(ce.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:xr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:pp[e]})}),n.jsx(ce.h4,{className:"mt-5 text-heading font-semibold text-white",variants:xr,custom:1,children:t}),n.jsx(ce.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:xr,custom:2,children:s}),(i||r)&&n.jsxs(ce.div,{className:"mt-5 flex items-center gap-2",variants:xr,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 fp=new Set(["awaiting_input","needs_review","failed"]);function ll(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function hp(e){return e.sliceRunId}function Br(e){const t=e.filter(i=>fp.has(i.status)).sort((i,r)=>ll(r.updatedAt??r.lastEventAt??"")-ll(i.updatedAt??i.lastEventAt??"")),s=new Map;for(const i of t){const r=hp(i),a=s.get(r);if(!a){s.set(r,{item:i,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function gp(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 xp(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function yp(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 bp(e){return e.primaryAction==="resolve_decision"?"Review choices":e.primaryAction==="open_artifact"?"Open result":e.primaryAction==="retry_slice"?"Review and retry":e.primaryAction==="review_output"?"Review activity":"Open details"}function vp(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready to review.`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} need${t===1?"s":""} your input.`}return e.status==="failed"?"Execution stopped before finishing.":e.status==="needs_review"?"Output is available and needs a quick review.":"This work needs your attention to continue."}function Ya(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return zn(s)?`${t} ${Ss(s)}`:s}function wp(e){if(!e)return null;const t=Et(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function kp(e,t,s){const i=(t==null?void 0:t.trim())??"";if(i&&!zn(i)){const a=Et(i);if(a!=="Untitled session")return a}const r=wp(e.statusExplainer);return r||(s?Ya(s,"Workstream"):Ya(e.sliceRunId,"Slice"))}const Ip=o.memo(function({sliceRuns:t,initiatives:s=[],title:i="Needs Input",className:r,showHeader:a=!0,panelStyle:l="card",onOpenDecisions:c,onFocusRunId:d,onReviewActivity:m,onOpenSliceDetail:p}){const g=o.useMemo(()=>Br(t),[t]),y=o.useMemo(()=>{const b=new Map;for(const k of s)k.id&&b.set(k.id,k.name??k.id);return b},[s]),h=o.useMemo(()=>{const b=new Map;for(const k of s)for(const E of k.workstreams??[])E.id&&(b.has(E.id)||b.set(E.id,E.name??E.id));return b},[s]),I=b=>{var k;if(b.primaryAction==="resolve_decision"){c==null||c();return}if(b.primaryAction==="review_output"||b.primaryAction==="retry_slice"){m==null||m(b);return}if(b.primaryAction==="open_artifact"){const E=(k=b.artifacts.find(q=>q.url))==null?void 0:k.url;if(E&&typeof window<"u"){window.open(E,"_blank","noopener,noreferrer");return}m==null||m(b);return}if(b.runId){d==null||d(b.runId);return}b.sliceRunId&&(d==null||d(b.sliceRunId))};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.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:i}),n.jsx("span",{className:"chip text-micro",children:g.length})]})}):null,g.length===0?n.jsx(ra,{icon:"inbox",headline:"No slices need attention",description:"All workstreams are running smoothly. Decisions will appear here when agents need your input."}):n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-3 py-2",children:n.jsx(bt,{mode:"popLayout",children:g.map(({item:b,duplicateCount:k},E)=>{var Te;const q=(Array.isArray(b.initiativeIds)&&b.initiativeIds.length>0?b.initiativeIds[0]:b.initiativeId)??null,w=(Array.isArray(b.workstreamIds)&&b.workstreamIds.length>0?b.workstreamIds[0]:b.workstreamId)??null,_=(q?y.get(q):null)??Ya(q,"Initiative"),W=b.workstreamTitle??(w?h.get(w)??null:null),A=kp(b,W,w),P=(Te=b.statusExplainer)!=null&&Te.trim().length?b.statusExplainer:"Review this slice to continue execution.",te=Et(vp(b)),R=Et(P),$=Et(_),ne=b.scope?b.scope.replace(/_/g," "):null,xe=b.updatedAt??b.lastEventAt??null;return n.jsxs(ce.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.97,y:-6},transition:{duration:.24,delay:Math.min(E,7)*.022,ease:[.22,1,.36,1]},layout:!0,className:`group hover-lift relative overflow-visible rounded-2xl border bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14] ${b.status==="failed"?"border-red-400/20":b.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>p==null?void 0:p(b),onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),p==null||p(b))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${yp(b.status)}`,"aria-hidden":!0}),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:$})]}),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:A,children:[n.jsx(en,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:A})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:te,children:te}),R!==te&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:R,children:R})]}),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] ${gp(b.status)}`,children:xp(b.status)}),ne?n.jsx("span",{className:"chip text-micro capitalize",children:ne}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[k>1&&n.jsxs("span",{className:"chip text-micro",children:[k," similar updates"]}),typeof b.blockingDecisionCount=="number"&&b.blockingDecisionCount>0&&n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",b.blockingDecisionCount," task",b.blockingDecisionCount===1?"":"s"]}),typeof b.decisionCount=="number"&&b.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[b.decisionCount," decision",b.decisionCount===1?"":"s"]}),typeof b.artifactCount=="number"&&b.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[b.artifactCount," artifact",b.artifactCount===1?"":"s"]}),xe&&n.jsxs("span",{children:["Updated ",Rt(xe)]})]}),b.decisionOptions&&b.decisionOptions.length>0&&b.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:fe=>fe.stopPropagation(),children:b.decisionOptions.slice(0,3).map(fe=>n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(b),className:"chip text-micro font-medium hover:bg-white/[0.08] transition-colors cursor-pointer",title:fe.description??fe.label,children:fe.label},fe.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:fe=>fe.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(b),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>I(b),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":b.status==="failed"?"teal":void 0,children:bp(b)})]})]},b.sliceRunId)})})})]})});function Np(e){if(!e)return"Unknown";const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toLocaleString():"Unknown"}function cl(e){return e?Rt(e):"unknown"}const jp={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 Ap(e){var i;const t=vi(e);if(t.update)return t.update;const s=(i=e.title)==null?void 0:i.trim();return s||e.type.replace(/_/g," ")}const _p=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(ce.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:Et(a.title)}),n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Completed ",cl(a.completedAt)," · ",Np(a.completedAt)]}),a.statusExplainer?n.jsx("p",{className:"mt-0.5 truncate text-micro text-muted",children:Et(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:Et([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:Et(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: ",Et(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:Et(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:Et(c.title)}),n.jsxs("p",{className:"text-micro text-secondary",children:[c.type??"artifact"," · ",cl(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 m=jp[c.type]??"text-primary",p=vi(c);return n.jsxs(ce.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 ${m}`,children:Et(Ap(c))}),p.nextUp[0]?n.jsx("p",{className:"truncate text-micro text-secondary",children:Et(p.nextUp[0])}):c.description?n.jsx("p",{className:"truncate text-micro text-secondary",children:Et(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 Sp(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Cp(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 Tp(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Mp(e){return{id:e.id,name:e.title,status:Sp(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Cp(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 dl=150,Ep=12;function ul(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Rp(){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 _c(e,t=null){return ei({queryKey:rs.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Wn())return Rp();const s=[],i=(t==null?void 0:t.trim())??"";let r=0;for(let d=0;d<Ep;d+=1){const m=new URLSearchParams({type:"initiative",limit:String(dl),offset:String(r)});i&&gs(m,i);const p=await fetch(`/orgx/api/entities?${m.toString()}`,{headers:Ot({workspaceId:i})});if(!p.ok)break;const g=await p.json(),y=g.data??[];if(s.push(...y),!!!((c=g.pagination)!=null&&c.has_more)||y.length===0)break;r+=dl}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 m=l.get(d.id);if(!m){l.set(d.id,d);continue}ul(d.updated_at??d.created_at)>ul(m.updated_at??m.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=>Tp(d.status)).sort((d,m)=>{const p=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(m.updated_at??m.created_at??"")||0)-p}).map(Mp)},enabled:e,staleTime:6e4})}const br=50,ml=8;function Lp(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Dp(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function $p(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Pp(e){const t=$p(e.sequence);return{id:e.id,name:e.title,status:Lp(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 Op(e,t=null){return ei({queryKey:rs.liveInitiatives({limit:br*ml,projectId:t}),queryFn:async()=>{var l;if(Wn())return[];const s=[];let i=0;for(let c=0;c<ml;c+=1){const d=new URLSearchParams({limit:String(br),offset:String(i)});t&&t.trim().length>0&&gs(d,t);const m=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:Ot({workspaceId:t})});if(!m.ok)break;const p=await m.json(),g=p.initiatives??[];s.push(...g);const y=typeof p.total=="number"?p.total:null,h=(l=p.pagination)==null?void 0:l.has_more;if(!(typeof h=="boolean"?h:y!==null?i+g.length<y:g.length===br)||g.length===0)break;i+=br}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=>Dp(c.status)).map(Pp)},enabled:e,staleTime:3e4})}const Sc=o.createContext(null);function qp({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(Sc.Provider,{value:{state:t,open:i,close:r},children:e})}function Cc(){const e=o.useContext(Sc);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Bp(e){const{running:t,blocked:s,decisionsCount:i,completedToday:r,onNeedsAttentionClick:a,onDecisionsClick:l,onBlockedClick:c,onNewInitiative:d}=e,m=i+s,p=a??l??c;if(t===0&&m===0&&r===0)return{key:"idle-empty",segments:[{text:"All caught up. "},d?{text:"Start something new?",color:D.lime,clickable:!0,onClick:d}:{text:"Nothing running."}]};if(t===0&&m===0)return{key:"idle-done",segments:[{text:`${r} done today`,color:D.teal},{text:" · all caught up"}]};if(m>0){const g=s>0&&i>0?`${s} blocked · ${i} decisions need your input`:s>0?`${s} blocked`:`${i} decisions need your input`;return{key:`needs-attention-${m}-${s}-${i}-${t}`,segments:[...t>0?[{text:`${t} running`,color:D.lime},{text:" · "}]:[],{text:`${m} needs attention`,color:D.amber,clickable:!!p,onClick:p},{text:` · ${g}`}]}}return{key:`running-${t}`,segments:[{text:`${t} running`,color:D.lime},{text:" · all systems go"}]}}function pl(e){const{className:t}=e,{key:s,segments:i}=Bp(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(ce.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 qx={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"},Fp={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"},Bx=e=>Fp[Lt(e)]??"text-white/60 bg-white/5 border-white/10",Fx=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"},Ux=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"},zx=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Wx=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"?D.red:t==="active"||t==="in_progress"||t==="running"?D.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?D.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?D.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Qr={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:D.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:D.teal,tint:"rgba(20, 184, 166, 0.18)"}},Up=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Fr(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)Fr(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"?(Up.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&Fr(a,t,s+1,i):typeof a=="object"&&a!==null&&Fr(a,t,s+1,i)}}}}function zp(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)Fr(i,t,0,s);for(const i of t){const r=zp(i);if(r)return Qr[r]}return Qr.unknown}function Wp(e){return Qr[e]??Qr.unknown}const Hp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]),Kp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Vp=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff","review"]),Gp=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping","stalled","awaiting_input","needs_review","needs_decision","review_required"]);function Hx(e){return Hp.has(Lt(e))}function Xp(e){return Kp.has(Lt(e))}function lo(e){return Vp.has(Lt(e))}function Qp(e){return Gp.has(Lt(e))}const Yp={xs:18,sm:24,md:30};function Jp({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:sa,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 xi({provider:e,size:t="sm",className:s,showRing:i=!0}){const r=Wp(e),a=Yp[t];return n.jsx("span",{className:me("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(Jp,{provider:e})})})}function Tc({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 h=[];return e>0&&h.push({color:D.lime,fraction:e/l}),t>0&&h.push({color:D.red,fraction:t/l}),s>0&&h.push({color:D.amber,fraction:s/l}),h},[e,t,s,l]),d=2.5,m=(i-d)/2,p=2*Math.PI*m,g=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:g,cy:g,r:m,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:g,cy:g,r:m,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),c.map((h,I)=>{const b=h.fraction*p,k=-y;return y+=b,n.jsx(ce.circle,{cx:g,cy:g,r:m,fill:"none",stroke:h.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${b} ${p-b}`,strokeDashoffset:k,initial:a?!1:{strokeDasharray:`0 ${p}`},animate:{strokeDasharray:`${b} ${p-b}`},transition:{duration:.5,delay:I*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},I)})]}),n.jsx("div",{className:"relative z-10",children:r})]})}const vr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function co(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function uo(e,t){if(typeof t=="number")return`${e}${t+1}`}const Zp=(e,t)=>{const s=co(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:uo("W",s)}},ef=(e,t)=>{const s=co(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:uo("M",s)}},tf=(e,t)=>{const s=co(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:uo("T",s)}};function Ta(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 nf(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 sf({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:i=!0}){var c;const r=uu(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 vr;if(Wn())return nf(e);if(!r)return{...vr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const m=Object.keys(d).length?d:void 0,p=async E=>{try{const q=new URLSearchParams({type:E,initiative_id:e,limit:"100"}),w=await fetch(`/orgx/api/entities?${q.toString()}`,{headers:m});return w.ok?await w.json():{data:[]}}catch{return{data:[]}}},[g,y,h]=await Promise.all([p("workstream"),p("milestone"),p("task")]),I=Array.isArray(g.data)?Ta(g.data.map(E=>Zp(E,e))):[],b=Array.isArray(y.data)?Ta(y.data.map(E=>ef(E,e))):[],k=Array.isArray(h.data)?Ta(h.data.map(E=>tf(E,e))):[];return{initiativeId:e,workstreams:I,milestones:b,tasks:k}}});return{details:(r?l.data:null)??(e?{...vr,initiativeId:e}:vr),isLoading:r?l.isLoading:!1,error:r?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function rf(){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 mo({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return ei({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Wn())return rf();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 Li(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:D.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:D.iris,bg:"rgba(124,124,255,0.10)"}}function af(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function of(e,t){return[...t?e.tasks.filter(i=>i.workstreamId===t):e.tasks].sort((i,r)=>i.title.localeCompare(r.title))}function lf({open:e,onClose:t,onLaunched:s}){var H,G,we,De,pe,Ie;const i=mo({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:r}=_c(e),[a,l]=o.useState(""),[c,d]=o.useState(""),[m,p]=o.useState(""),[g,y]=o.useState(""),[h,I]=o.useState("auto"),[b,k]=o.useState(""),[E,q]=o.useState(null),[w,_]=o.useState(null),[W,A]=o.useState("starter"),[P,te]=o.useState(!1),[R,$]=o.useState(1),ne=Wn(),xe=o.useMemo(()=>{const M=c.trim();return M?(r==null?void 0:r.find(Ne=>Ne.id===M))??null:null},[r,c]),{details:Te}=sf({initiativeId:xe?xe.id:null,enabled:e&&!!xe}),fe=o.useMemo(()=>af(Te),[Te]),je=o.useMemo(()=>of(Te,m||null),[Te,m]),ae=((H=i.data)==null?void 0:H.agents)??[],ie=o.useMemo(()=>{const M=a.trim();return M?ae.find(Ne=>Ne.id===M)??null:null},[ae,a]);o.useEffect(()=>{var Ne,_e;if(!e)return;const M=((Ne=ae.find(Ee=>Ee.isDefault))==null?void 0:Ne.id)??((_e=ae[0])==null?void 0:_e.id)??"";!a&&M&&l(M)},[ae,e,a]),o.useEffect(()=>{if(!e||c.trim())return;const M=r??[],Ne=M.length===1?M[0]:null;Ne&&d(Ne.id)},[r,e,c]),o.useEffect(()=>{if(!e)return;const M=(ie==null?void 0:ie.model)??"",Ne=M.includes("openrouter")?"openrouter":M.includes("anthropic")?"anthropic":M.includes("openai")?"openai":"auto";I(Ne)},[e,ie==null?void 0:ie.model,a]),o.useEffect(()=>{e&&(q(null),_(null),A("starter"),$(1))},[e]),o.useEffect(()=>{p(""),y("")},[c]),o.useEffect(()=>{y("")},[m]),o.useEffect(()=>{e&&(b.trim().length>0||xe&&k(`Kick off: ${xe.name}`))},[b,e,xe]);const X=!!a.trim()&&!!c.trim(),oe=R===1?!!a.trim():R===2?!!c.trim():X,Le=async()=>{var ge;const M=(w==null?void 0:w.checkout)??"/orgx/api/billing/checkout",Ne=W&&W.trim().length>0?W.trim():"starter",Ee=await(await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:Ne,billingCycle:"monthly"})})).json().catch(()=>null),$e=((ge=Ee==null?void 0:Ee.data)==null?void 0:ge.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 M=(w==null?void 0:w.portal)??"/orgx/api/billing/portal",_e=await(await fetch(M,{method:"POST"})).json().catch(()=>null),Ee=(($e=_e==null?void 0:_e.data)==null?void 0:$e.url)??(_e==null?void 0:_e.url)??null;if(!Ee)throw new Error((_e==null?void 0:_e.error)??"Billing portal unavailable");window.open(Ee,"_blank","noopener,noreferrer")},de=async()=>{if(!(!X||P)){if(ne){t(),s==null||s();return}q(null),_(null),te(!0);try{const M={agentId:a.trim(),message:b.trim()?b.trim():void 0,initiativeId:c.trim(),initiativeTitle:(xe==null?void 0:xe.name)??null,workstreamId:m.trim()?m.trim():null,taskId:g.trim()?g.trim():null,provider:h!=="auto"?h:null},Ne=new URLSearchParams;Ne.set("agentId",M.agentId),Ne.set("initiativeId",M.initiativeId),M.initiativeTitle&&Ne.set("initiativeTitle",M.initiativeTitle),M.workstreamId&&Ne.set("workstreamId",M.workstreamId),M.taskId&&Ne.set("taskId",M.taskId),M.message&&Ne.set("message",M.message),M.provider&&Ne.set("provider",M.provider);const _e=await fetch(`/orgx/api/agents/launch?${Ne.toString()}`,{method:"POST"}),Ee=await _e.json().catch(()=>null);if(!_e.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 (${_e.status})`);t(),s==null||s()}catch(M){q(M instanceof Error?M.message:"Launch failed")}finally{te(!1)}}},ke=!!((G=ie==null?void 0:ie.run)!=null&&G.runId)&&!!((we=ie==null?void 0:ie.run)!=null&&we.pid),T=async()=>{var M;if(!(!((M=ie==null?void 0:ie.run)!=null&&M.runId)||!ke||P)&&!ne){q(null),te(!0);try{const Ne=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(ie.run.runId)}`,{method:"POST"}),_e=await Ne.json().catch(()=>null);if(!Ne.ok||!(_e!=null&&_e.ok))throw new Error((_e==null?void 0:_e.error)??`Stop failed (${Ne.status})`);await i.refetch()}catch(Ne){q(Ne instanceof Error?Ne.message:"Stop failed")}finally{te(!1)}}},z=async()=>{var M;if(!(!((M=ie==null?void 0:ie.run)!=null&&M.runId)||P)){if(ne){t(),s==null||s();return}q(null),te(!0);try{const Ne=new URLSearchParams;Ne.set("runId",ie.run.runId),b.trim()&&Ne.set("message",b.trim()),h&&h!=="auto"&&Ne.set("provider",h);const _e=await fetch(`/orgx/api/agents/restart?${Ne.toString()}`,{method:"POST"}),Ee=await _e.json().catch(()=>null);if(!_e.ok||!(Ee!=null&&Ee.ok))throw new Error((Ee==null?void 0:Ee.error)??`Restart failed (${_e.status})`);t(),s==null||s()}catch(Ne){q(Ne instanceof Error?Ne.message:"Restart failed")}finally{te(!1)}}};return e?n.jsx(ia,{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(([M,Ne])=>n.jsxs("button",{type:"button",onClick:()=>$(M),className:me("rounded-full px-3 py-1 transition-colors",R===M?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[M,". ",Ne]},M))})]}),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(ce.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:[R===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:M=>l(M.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:ae.map(M=>{const Ne=Li(M.status);return n.jsxs("option",{value:M.id,children:[M.name," (",M.id,") · ",Ne.label]},M.id)})})]}),ie&&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:ie.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${Li(ie.status).color}55`,color:Li(ie.status).color,backgroundColor:Li(ie.status).bg},children:Li(ie.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:"})," ",ie.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",ie.workspace??"unknown"]}),((De=ie.context)==null?void 0:De.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",ie.context.initiativeTitle??ie.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:h,onChange:M=>I(M.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."})]}),ie.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",ie.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",ie.run.status,")"]})]}),ie.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:T,disabled:!ke||P,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:z,disabled:P,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"})]})]})]})]}),R===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:M=>d(M.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(M=>n.jsx("option",{value:M.id,children:M.name},M.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:m,onChange:M=>p(M.target.value),disabled:!xe,className:me("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",!xe&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),fe.map(M=>n.jsx("option",{value:M.id,children:M.name},M.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:g,onChange:M=>y(M.target.value),disabled:!xe,className:me("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",!xe&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),je.slice(0,80).map(M=>n.jsx("option",{value:M.id,children:M.title},M.id))]}),je.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),R===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:b,onChange:M=>k(M.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:((ie==null?void 0:ie.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:((xe==null?void 0:xe.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:m.trim()?((pe=fe.find(M=>M.id===m))==null?void 0:pe.name)??m:"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:g.trim()?((Ie=je.find(M=>M.id===g))==null?void 0:Ie.title)??g:"Any"})]})]})]})]})]},R)}),E&&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:E}),w&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Le().catch(M=>q(M instanceof Error?M.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(M=>q(M instanceof Error?M.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"}),w.pricing&&n.jsx("a",{href:w.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:R===1?"Pick an agent to configure.":R===2?"Select an initiative scope (required).":X?"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:[R>1&&n.jsx("button",{type:"button",onClick:()=>$(M=>M>1?M-1:M),disabled:P,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"}),R<3?n.jsx("button",{type:"button",onClick:()=>$(M=>M<3?M+1:M),disabled:!oe||P,className:me("rounded-xl px-4 py-2 text-body font-semibold transition-colors",oe&&!P?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:oe&&!P?{backgroundColor:D.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:de,disabled:!X||P,className:me("rounded-xl px-4 py-2 text-body font-semibold transition-colors",X&&!P?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:X&&!P?{backgroundColor:D.lime}:void 0,children:P?"Launching…":"Launch"})]})]})]})}):null}function cf({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(ce.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 Ma=10,df=20;function uf(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:D.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:D.iris,bg:"rgba(124,124,255,0.10)"}}function mf(e){return e?e.includes("error")||e.includes("fail")?D.red:e.includes("decision")||e.includes("block")?D.amber:e.includes("complete")||e.includes("success")?D.teal:e.includes("start")||e.includes("launch")?D.lime:D.iris:D.iris}const pf={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},wr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function ff(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function hf({open:e,onClose:t,agentName:s,catalogAgent:i,sessions:r,activity:a,onSelectSession:l,onRefresh:c}){var $,ne,xe,Te,fe,je;const[d,m]=o.useState(!1),[p,g]=o.useState(!1),[y,h]=o.useState(null),I=Gi(s),b=uf((i==null?void 0:i.status)??null),k=oo(s),E=o.useMemo(()=>{let ae=0,ie=0,X=0,oe=0;for(const Le of r)Le.status==="running"||Le.status==="queued"||Le.status==="pending"?ae++:Le.status==="blocked"?ie++:Le.status==="failed"||Le.status==="cancelled"?X++:(Le.status==="completed"||Le.status==="archived")&&oe++;return{running:ae,blocked:ie,failed:X,completed:oe}},[r]),q=o.useMemo(()=>[...r].sort((ae,ie)=>Date.parse(ie.updatedAt??ie.lastEventAt??ie.startedAt??"")-Date.parse(ae.updatedAt??ae.lastEventAt??ae.startedAt??"")),[r]),w=d?q:q.slice(0,Ma),_=q.length>Ma,W=o.useMemo(()=>[...a].sort((ae,ie)=>Date.parse(ie.timestamp)-Date.parse(ae.timestamp)).slice(0,df),[a]),A=!!(($=i==null?void 0:i.run)!=null&&$.runId)&&!!((ne=i==null?void 0:i.run)!=null&&ne.pid),P=async()=>{var ae;if(!(!((ae=i==null?void 0:i.run)!=null&&ae.runId)||!A||p)){h(null),g(!0);try{const ie=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(i.run.runId)}`,{method:"POST"}),X=await ie.json().catch(()=>null);if(!ie.ok||!(X!=null&&X.ok))throw new Error((X==null?void 0:X.error)??`Stop failed (${ie.status})`);c==null||c()}catch(ie){h(ie instanceof Error?ie.message:"Stop failed")}finally{g(!1)}}},te=async()=>{var ae;if(!(!((ae=i==null?void 0:i.run)!=null&&ae.runId)||p)){h(null),g(!0);try{const ie=new URLSearchParams;ie.set("runId",i.run.runId);const X=await fetch(`/orgx/api/agents/restart?${ie.toString()}`,{method:"POST"}),oe=await X.json().catch(()=>null);if(!X.ok||!(oe!=null&&oe.ok))throw new Error((oe==null?void 0:oe.error)??`Restart failed (${X.status})`);c==null||c()}catch(ie){h(ie instanceof Error?ie.message:"Restart failed")}finally{g(!1)}}};if(!e)return null;const R=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:P,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:te,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(ia,{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(cf,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:R,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(ce.div,{className:"flex items-start gap-5",variants:pf,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(Tc,{running:E.running,blocked:E.blocked+E.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:b.color,backgroundColor:b.bg,borderColor:`${b.color}30`},children:b.label})]}),I&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:I})]})]}),n.jsx(ce.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:wr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:E.running,color:D.lime},{label:"Blocked",value:E.blocked,color:D.red},{label:"Failed",value:E.failed,color:D.amber},{label:"Completed",value:E.completed,color:D.teal}].map(ae=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:ae.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:ae.value>0?ae.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:ae.value})]},ae.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(ce.div,{variants:wr,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:[w.map(ae=>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(ae.status)}}),n.jsxs("button",{onClick:()=>{l(ae.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:ae.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:Rt(ae.updatedAt??ae.lastEventAt??ae.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:ae.status}),ae.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(ae.progress),"%"]})]})]})]})]},ae.id)),_&&n.jsx("button",{type:"button",onClick:()=>m(ae=>!ae),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${q.length-Ma} older sessions`})]})]}),n.jsxs(ce.div,{variants:wr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),W.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:W.map((ae,ie)=>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:mf(ae.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:ae.title??ae.summary??ae.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:Rt(ae.timestamp)})]})]},ae.id??ie))})]})]}),n.jsx(ff,{}),i&&n.jsxs(ce.div,{variants:wr,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:(xe=i.model)!=null&&xe.includes("openrouter")?"OpenRouter":(Te=i.model)!=null&&Te.includes("anthropic")?"Anthropic":(fe=i.model)!=null&&fe.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:me("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})]}),((je=i.context)==null?void 0:je.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 kr=120,fl=10,gf=24,hl=520,xf=58,yf=56,bf=20,vf=8,wf=10,kf=[{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"}],If=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ja=[{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 Ja)if(a.aliases.some(l=>l.test(r)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Nf(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 jf(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 Mc(e){const t=Nf(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=jf(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 Af(e){const t=Mc(e),s=xt(t.agentId);if(s)return`id:${s}`;const i=xt(t.agentName);return i?`name:${i}`:"unassigned"}function _f(e){const t=e.trim();return t?If.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function Yr(e){const t=(e??"").trim();return t?wi(t):!1}function Sf(e){var t,s;return!!(Yr((t=e.context)==null?void 0:t.initiativeId)||Yr(((s=e.run)==null?void 0:s.initiativeId)??null))}function Ir(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":lo(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function Za(e){const t=Lt(e??"");return!!t&&(lo(t)||Qp(t)||Xp(t))}function gl(e){const t=Lt(e??"");return!!t&&lo(t)}function ui(e){return e?!!(Za(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function Cf(e){return e?e.state==="active":!1}function Tf(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 Nr(e,t){return Bn(t.updatedAt??t.lastEventAt??t.startedAt)-Bn(e.updatedAt??e.lastEventAt??e.startedAt)}function Mf({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(ce.span,{animate:{rotate:r?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(bt,{children:r&&n.jsx(ce.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,m)=>{const p=i===d.id,g=Cs(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(ce.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(m*.02,.1)},className:me("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(xi,{provider:g.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 Ef=o.memo(function({sessions:t,activity:s,selectedSessionId:i,onSelectSession:r,timeFilterId:a,onAgentFilter:l,agentFilter:c,onReconnect:d,onLaunched:m,connectionStatus:p,runtimeInstances:g=[],showSyntheticEntities:y=!1,autopilotState:h=null}){var Z;const[I,b]=o.useState(new Set),[k,E]=o.useState(!1),[q,w]=o.useState(!1),[_,W]=o.useState(0),[A,P]=o.useState(null),[te,R]=o.useState(!1),$=mo({enabled:!0}),ne=((Z=$.data)==null?void 0:Z.agents)??[],xe=o.useMemo(()=>Qi(a),[a]),Te=o.useMemo(()=>xe===null?s:s.filter(B=>Bn(B.timestamp)>=xe),[s,xe]);o.useMemo(()=>{var ue,Pe,We;const B=new Map,se=[...Te].sort((rt,he)=>Bn(he.timestamp)-Bn(rt.timestamp));for(const rt of se){const he=rt.runId;if(!he||B.has(he))continue;const Ve=((ue=rt.summary)==null?void 0:ue.trim())??((Pe=rt.description)==null?void 0:Pe.trim())??((We=rt.title)==null?void 0:We.trim())??"";Ve.length>0&&B.set(he,Ve)}return B},[Te]);const{agents:fe,hiddenGroupCount:je,filteredOutGroupsByDate:ae,filteredOutSessionsByDate:ie,visibleSessionCount:X,archivedGroups:oe,sessionCountInScope:Le}=o.useMemo(()=>{var rn;const B=y?t.nodes:t.nodes.filter(Y=>!Yr(Y.initiativeId)),se=y?ne:ne.filter(Y=>!Sf(Y)),ue=y?g:g.filter(Y=>!Yr(Y.initiativeId)),Pe=new Map,We=new Map,rt=[...ue].sort((Y,ye)=>Bn(ye.lastEventAt??ye.lastHeartbeatAt)-Bn(Y.lastEventAt??Y.lastHeartbeatAt));for(const Y of rt){Y.runId&&!Pe.has(Y.runId)&&Pe.set(Y.runId,Y);const ye=Sn(Y.agentId,Y.agentName??Y.displayName),Oe=xt((ye==null?void 0:ye.agentId)??Y.agentId);if(Oe){const Ge=We.get(Oe)??[];Ge.push(Y),We.set(Oe,Ge)}}const he=new Map;for(const Y of B){const ye=Mc(Y),Oe=Af(Y),Ge=xt(ye.agentId),Re=xt(ye.agentName);let He=he.get(Oe)??null;if(!He&&Ge&&Re){const Ue=`name:${Re}`,ft=he.get(Ue);ft&&(he.delete(Ue),ft.groupKey=Oe,he.set(Oe,ft),He=ft)}if(!He&&Re){const Ue=Array.from(he.values()).find(ft=>xt(ft.agentName)===Re);Ue&&(He=Ue)}He?(He.nodes.push(Y),!He.agentId&&ye.agentId&&(He.agentId=ye.agentId),(He.agentName==="OrgX"||!He.agentName)&&ye.agentName&&(He.agentName=ye.agentName)):he.set(Oe,{groupKey:Oe,agentId:ye.agentId,agentName:ye.agentName??ye.agentId??"OrgX",nodes:[Y],latest:Y,runtime:null,runtimeActiveCount:0})}for(const Y of se){const ye=Sn(Y.id,Y.name),Oe=(ye==null?void 0:ye.agentId)??Y.id,Ge=(ye==null?void 0:ye.agentName)??Y.name,Re=xt(Oe),He=xt(Ge),Ue=Re?`id:${Re}`:null,ft=He?`name:${He}`:null;let Ht=null;if(Ue&&he.has(Ue))Ht=Ue;else if(ft&&he.has(ft))Ht=ft;else{const gt=Array.from(he.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=he.get(Ht);gt.catalogAgent=Y,!gt.agentId&&Oe&&(gt.agentId=Oe),(gt.agentName==="OrgX"||!gt.agentName)&&Ge&&(gt.agentName=Ge),Ue&>.groupKey!==Ue&&!he.has(Ue)&&(he.delete(gt.groupKey),gt.groupKey=Ue,he.set(Ue,gt))}else{const gt=Ue??ft??`catalog:${Ge.toLowerCase()}`;he.set(gt,{groupKey:gt,agentId:Oe,agentName:Ge,nodes:[],latest:null,catalogAgent:Y,runtime:null,runtimeActiveCount:0})}}for(const Y of Ja){const ye=`orgx:${Y.id}`,Oe=`id:${ye}`;let Ge=he.get(Oe)??null;if(!Ge){const Re=Array.from(he.entries()).find(([,He])=>{const Ue=Sn(He.agentId,He.agentName);return xt(Ue==null?void 0:Ue.agentId)===xt(ye)});Re&&(he.delete(Re[0]),Ge=Re[1],Ge.groupKey=Oe,he.set(Oe,Ge))}if(Ge||(Ge={groupKey:Oe,agentId:ye,agentName:Y.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},he.set(Oe,Ge)),Ge.agentId=ye,Ge.agentName=Y.name,!Ge.catalogAgent){const Re=se.find(He=>{const Ue=Sn(He.id,He.name);return xt(Ue==null?void 0:Ue.agentId)===xt(ye)});Re&&(Ge.catalogAgent=Re)}}const Ve=new Map(Ja.map((Y,ye)=>[xt(`orgx:${Y.id}`),ye]));for(const Y of he.values()){Y.nodes.length>0&&(Y.nodes.sort(Nr),Y.latest=Y.nodes[0]);const ye=[],Oe=new Set;if((rn=Y.latest)!=null&&rn.runId){const Re=Pe.get(Y.latest.runId);Re&&!Oe.has(Re.id)&&(ye.push(Re),Oe.add(Re.id))}for(const Re of Y.nodes){if(!Re.runId)continue;const He=Pe.get(Re.runId);He&&!Oe.has(He.id)&&(ye.push(He),Oe.add(He.id))}const Ge=xt(Y.agentId);if(Ge)for(const Re of We.get(Ge)??[])Oe.has(Re.id)||(ye.push(Re),Oe.add(Re.id));ye.sort((Re,He)=>Bn(He.lastEventAt??He.lastHeartbeatAt)-Bn(Re.lastEventAt??Re.lastHeartbeatAt)),Y.runtime=ye[0]??null,Y.runtimeActiveCount=ye.filter(Re=>Cf(Re)).length}const re=Array.from(he.values()).sort((Y,ye)=>{const Oe=Ir(Y),Ge=Ir(ye);if(Oe!==Ge)return Oe?-1:1;if(Oe&&Ge){const Re=Y.nodes.length>0||(Y.runtimeActiveCount??0)>0,He=ye.nodes.length>0||(ye.runtimeActiveCount??0)>0;if(Re!==He)return Re?-1:1;if(Re&&He){if(Y.latest&&ye.latest)return Nr(Y.latest,ye.latest);if(Y.latest&&!ye.latest)return-1;if(!Y.latest&&ye.latest)return 1}const Ue=Sn(Y.agentId,Y.agentName),ft=Sn(ye.agentId,ye.agentName),Ht=Ve.get(xt((Ue==null?void 0:Ue.agentId)??Y.agentId))??999,gt=Ve.get(xt((ft==null?void 0:ft.agentId)??ye.agentId))??999;if(Ht!==gt)return Ht-gt}return Y.latest&&ye.latest?Nr(Y.latest,ye.latest):Y.latest&&!ye.latest?-1:!Y.latest&&ye.latest?1:Y.agentName.localeCompare(ye.agentName)}),K=cc(a),Ce=K.id==="live",Ze=K.minutes===null||Ce?null:Date.now()-K.minutes*6e4,at=[],pt=[];let ct=0,ht=0;for(const Y of re){const ye=(Y.runtimeActiveCount??0)>0,Oe=Ir(Y);if(Y.nodes.length===0){const Ue=ui(Y.catalogAgent);(Oe||Ce&&(Ue||ye))&&at.push(Y);continue}if(Ce){const Ue=Y.nodes.filter(gt=>Za(_n(gt))),ft=Y.nodes.filter(gt=>!Za(_n(gt))),Ht=ui(Y.catalogAgent);if(Ue.length===0){Oe||Ht||ye?at.push({...Y,nodes:[],latest:null}):(ct+=1,ht+=Y.nodes.length,pt.push(Y));continue}ht+=ft.length,ft.length>0&&pt.push({...Y,nodes:ft,latest:ft[0]??null}),at.push({...Y,nodes:Ue,latest:Ue[0]??null});continue}if(Ze===null){at.push(Y);continue}const Ge=Y.nodes.filter(Ue=>gl(_n(Ue))?!0:Bn(Ue.updatedAt??Ue.lastEventAt??Ue.startedAt)>=Ze),Re=ui(Y.catalogAgent);if(Ge.length===0){Oe||Re||ye?at.push({...Y,nodes:[],latest:null}):(ct+=1,ht+=Y.nodes.length,pt.push(Y));continue}const He=Y.nodes.filter(Ue=>gl(_n(Ue))?!1:Bn(Ue.updatedAt??Ue.lastEventAt??Ue.startedAt)<Ze);ht+=He.length,He.length>0&&pt.push({...Y,nodes:He,latest:He[0]}),at.push({...Y,nodes:Ge,latest:Ge[0]})}return{agents:at.slice(0,kr),hiddenGroupCount:Math.max(0,at.length-kr),filteredOutGroupsByDate:ct,filteredOutSessionsByDate:ht,visibleSessionCount:at.slice(0,kr).reduce((Y,ye)=>Y+ye.nodes.length,0),archivedGroups:pt,sessionCountInScope:B.length}},[a,t.nodes,ne,g,y]);o.useEffect(()=>{w(!1),W(0)},[a]);const Me=o.useMemo(()=>oe.reduce((B,se)=>B+se.nodes.length,0),[oe]),de=o.useMemo(()=>fe.filter(B=>B.nodes.length>0).map(B=>B.groupKey),[fe]),{activeAgents:ke,idleOrgxAgents:T,activeAgentCount:z}=o.useMemo(()=>{const B=[],se=[];for(const ue of fe)ue.nodes.length>0||(ue.runtimeActiveCount??0)>0||ui(ue.catalogAgent)?B.push(ue):Ir(ue)?se.push(ue):B.push(ue);return{activeAgents:B,idleOrgxAgents:se,activeAgentCount:B.filter(ue=>ue.nodes.length>0||(ue.runtimeActiveCount??0)>0||ui(ue.catalogAgent)).length}},[fe]),H=o.useMemo(()=>{if(de.length===0)return{allCollapsed:!1,allExpanded:!0};let B=0;for(const se of de)I.has(se)&&(B+=1);return{allCollapsed:B===de.length,allExpanded:B===0}},[I,de]),G=o.useMemo(()=>{const B=[];for(const se of oe)for(const ue of se.nodes)B.push({node:ue,agentName:se.agentName});return B.sort((se,ue)=>Nr(se.node,ue.node)),B.slice(0,(_+1)*wf)},[oe,_]),we=B=>{b(se=>{const ue=new Set(se);return ue.has(B)?ue.delete(B):ue.add(B),ue})},De=()=>{b(()=>H.allCollapsed?new Set:new Set(de))},pe=o.useMemo(()=>A?fe.find(B=>B.groupKey===A)??null:null,[fe,A]),Ie=o.useMemo(()=>(pe==null?void 0:pe.nodes)??[],[pe]),M=o.useMemo(()=>{if(!pe)return[];const B=xt(pe.agentName),se=xt(pe.agentId),ue=Sn(pe.agentId,pe.agentName);return Te.filter(Pe=>{const We=xt(Pe.agentName),rt=xt(Pe.agentId),he=Sn(Pe.agentId,Pe.agentName);return B!==null&&We===B||se!==null&&rt===se||ue!==null&&he!==null&&xt(ue.agentId)===xt(he.agentId)})},[Te,pe]),Ne=Le===0,_e=ne.length>0,Ee=o.useRef(null),[$e,ge]=o.useState(0),[mt,Se]=o.useState(0),Ae=o.useCallback(B=>{const se=B.currentTarget.scrollTop;ge(ue=>Math.abs(ue-se)<1?ue:se)},[]);o.useEffect(()=>{const B=Ee.current;if(!B)return;const se=()=>{const ue=B.clientHeight,Pe=B.scrollTop;Se(We=>We===ue?We:ue),ge(We=>Math.abs(We-Pe)<1?We:Pe)};if(se(),typeof ResizeObserver<"u"){const ue=new ResizeObserver(()=>se());return ue.observe(B),()=>ue.disconnect()}return window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[ke.length]);const{visibleAgentGroups:J,topVirtualSpacerPx:dt,bottomVirtualSpacerPx:yt,virtualizationEnabled:Fe}=o.useMemo(()=>{if(!(ke.length>gf&&mt>0))return{visibleAgentGroups:ke,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const se=ke.map(re=>{const Ce=I.has(re.groupKey)?0:Math.min(re.nodes.length,fl);let Ze=xf;return Ce>0&&(Ze+=bf+Ce*yf,re.nodes.length>Ce&&(Ze+=20)),Ze+vf}),ue=new Array(se.length+1).fill(0);for(let re=0;re<se.length;re+=1)ue[re+1]=ue[re]+se[re];const Pe=ue[ue.length-1],We=Math.max(0,$e-hl),rt=$e+mt+hl;let he=0;for(;he<ke.length&&ue[he+1]<We;)he+=1;let Ve=he;for(;Ve<ke.length&&ue[Ve]<rt;)Ve+=1;return Ve<=he&&(Ve=Math.min(ke.length,he+1)),{visibleAgentGroups:ke.slice(he,Ve),topVirtualSpacerPx:ue[he],bottomVirtualSpacerPx:Math.max(0,Pe-ue[Ve]),virtualizationEnabled:!0}},[ke,I,$e,mt]);return n.jsxs(Ts,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(lf,{open:k,onClose:()=>E(!1),onLaunched:()=>{$.refetch(),m==null||m()}}),n.jsx(hf,{open:A!==null,onClose:()=>P(null),agentName:(pe==null?void 0:pe.agentName)??"",catalogAgent:(pe==null?void 0:pe.catalogAgent)??null,sessions:Ie,activity:M,onSelectSession:r,onRefresh:()=>$.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:[z," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:De,disabled:de.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:H.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:H.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>E(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:Ee,onScroll:Ae,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[fe.length===0&&!Ne&&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."})]}),fe.length===0&&Ne&&!d&&n.jsx(ra,{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:[Fe&&dt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:dt}}),J.map(B=>{var gt;const se=B.groupKey,ue=I.has(se),Pe=B.latest,We=Pe?_n(Pe):null,rt=(h==null?void 0:h.activeRunId)!=null&&(Pe==null?void 0:Pe.runId)!=null&&h.activeRunId===Pe.runId,he=rt&&(h==null?void 0:h.state)==="running"?"running":We,Ve=rt&&(h==null?void 0:h.state)==="running"&&h.activeWorkstreamTitle?`Working on ${h.activeWorkstreamTitle}`:null,re=B.nodes.length>0,K=B.nodes.length===1,Ce=ui(B.catalogAgent),Ze=B.runtime??null,at=(B.runtimeActiveCount??0)>0,pt=!re&&at&&Ze!==null,ct=re||pt,ht=Pe?i===Pe.id:!1,rn=B.agentName||((gt=B.catalogAgent)==null?void 0:gt.name)||B.agentId||"OrgX",Y=Sn(B.agentId,rn),ye=(Y==null?void 0:Y.agentName)??_f(rn),Oe=(Y==null?void 0:Y.role)??Gi(ye),Ge=Cs(B.agentId,ye,Ze==null?void 0:Ze.displayName,Pe==null?void 0:Pe.runtimeProvider,Pe==null?void 0:Pe.runtimeClient),Re=Y===null&&(Ge.id==="codex"||Ge.id==="openai"||Ge.id==="anthropic"||Ge.id==="openclaw"),He=Oe?`${rn} — ${Oe}`:rn,Ue=ue?[]:re?B.nodes.slice(0,fl):[],ft=Math.max(0,re?B.nodes.length-Ue.length:0),Ht=xt(c)===xt(ye)||xt(c)===xt(He);return n.jsxs(ce.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:me("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",!re&&!Ce&&!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:()=>{K?r(B.nodes[0].id):pt?we(se):!re&&Ce?P(se):l?l(Ht?null:ye):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(xi,{provider:Ge.id,size:"sm",showRing:!1})}):n.jsx(Tc,{running:B.nodes.filter(vt=>{const Ct=_n(vt);return Ct==="running"||Ct==="handoff"||Ct==="review"}).length,blocked:B.nodes.filter(vt=>{const Ct=_n(vt);return Ct==="blocked"||Ct==="failed"}).length,paused:B.nodes.filter(vt=>{const Ct=_n(vt);return Ct==="paused"||Ct==="cancelled"}).length,size:36,children:n.jsx(Gt,{name:ye,size:"sm",hint:`${B.agentId??""} ${ye}`})}),Y&&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(he??Pe.status),borderColor:D.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:Ce?Ks("running"):"rgba(255,255,255,0.2)",borderColor:D.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:[ye,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:re?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const vt={};for(const Ct of B.nodes){const Ut=_n(Ct);vt[Ut]=(vt[Ut]??0)+1}return Object.entries(vt).map(([Ct,Ut])=>`${Ut} ${Ct}`).join(" · ")})(),children:(()=>{const vt={};for(const Ut of B.nodes){const nt=_n(Ut);vt[nt]=(vt[nt]??0)+1}const Ct=B.nodes.length;return Object.entries(vt).map(([Ut,nt])=>n.jsx("span",{style:{width:`${nt/Ct*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})]}):Ce||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:()=>P(se),"aria-label":`View ${ye} 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&&we(se)},disabled:!ct,"aria-label":ct?ue?"Expand sessions":"Collapse sessions":"No sessions to expand",className:me("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:me("transition-transform",ct&&!ue?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(bt,{initial:!1,children:ct&&!ue&&n.jsx(ce.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,Ct=[];for(const et of Ue){const $t=_n(et);if($t==="blocked"||$t==="paused"||$t==="failed"){const _t=`${$t}:${et.blockerReason??""}`,Tt=vt.get(_t)??[];Tt.push(et),vt.set(_t,Tt)}else Ct.push(et)}const Ut=[];for(const[et,$t]of vt)$t.length>3?Ut.push({status:et.split(":")[0],nodes:$t}):Ct.push(...$t);const nt=(et,$t)=>{const _t=i===et.id,Tt=_n(et),St=Cs(et.agentName,et.title,et.lastEventSummary,et);return n.jsx(ce.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:me("w-full rounded-lg px-2.5 py-2 text-left transition-colors",_t?"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(xi,{provider:St.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:St.accent},children:St.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Tt}),n.jsx("span",{title:Hr(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, ${D.lime}, ${D.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:Ks(Tt)},"aria-label":Tt,title:Tt})]})},et.id)};return n.jsxs(n.Fragment,{children:[Ct.map((et,$t)=>nt(et,$t)),Ut.map(et=>n.jsx(Mf,{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"]})]})})})]},se)}),Fe&&yt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:yt}})]}),T.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>R(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:me("transition-transform",te?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[T.length," idle agent",T.length===1?"":"s"]})]}),n.jsx(bt,{initial:!1,children:te&&n.jsx(ce.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:T.map(B=>{const se=Sn(B.agentId,B.agentName),ue=(se==null?void 0:se.agentName)??B.agentName,Pe=(se==null?void 0:se.role)??Gi(ue);return n.jsxs("button",{type:"button",onClick:()=>P(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:ue,size:"sm",hint:`${B.agentId??""} ${ue}`}),se&&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:[ue,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)})})})})]}),je>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",kr," most recent agent groups (",je," older groups omitted)."]}),d&&p!=="connected"&&!_e&&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:kf.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))})]}),ie>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{w(B=>!B),q&&W(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:me("transition-transform",q?"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",ae>0?` across ${ae} agent${ae===1?"":"s"}`:""]})]}),n.jsx(bt,{initial:!1,children:q&&n.jsx(ce.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:[G.map(({node:B,agentName:se})=>{const ue=_n(B),Pe=B.runtimeProvider?{id:Tf(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(xi,{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:se}),n.jsx("span",{className:"text-micro text-muted",title:Hr(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:ue})]})]},B.id)}),G.length<Me&&n.jsxs("button",{onClick:()=>W(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-G.length," remaining)"]})]})})})]})]})]})}),Rf=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Lf=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),Df=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),$f=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Pf=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function mi(e){return e?Lt(e):""}function Ea(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Of(e){return e.some(t=>Rf.has(t))}function qf(e){return e.some(t=>Lf.has(t))}function Bf(e){return e.some(t=>Df.has(t))}function Ff(e){return e.some(t=>$f.has(t))}function Uf(e){return e.some(t=>Pf.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 zf(e){const t=mi(e.sessionStatus),s=mi(e.sessionPhase),i=mi(e.sessionState),r=mi(e.sliceStatus),a=mi(e.activityStatus),l=mi(e.stopReason),c=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,i,r,a,l].filter(_=>_.length>0),m=Ea(e.blockingDecisionCount),p=Ea(e.nonBlockingDecisionCount),g=Ea(e.blockerCount),y=c==="run_failed",h=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",I=y||Of(d),b=qf(d)||c==="decision_requested"||m>0||e.decisionRequired===!0,k=Bf(d)||g>0,E=h||Ff(d),q=Uf(d)||c==="run_started";if(I)return ps("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(E&&!b&&!I&&g===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(b||k)return m>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(E)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(q){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 Ra=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Wf(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;Ra.lastIndex=0;for(let a=Ra.exec(e);a;a=Ra.exec(e)){const[l]=a,c=a.index;c>i&&s.push(e.slice(i,c));const d=`${t}-${r++}`,m=a[1],p=a[2],g=a[3],y=a[4],h=a[5],I=a[6],b=a[7];m&&p&&Wf(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:m},d)):g?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:g},d)):y||h?s.push(n.jsx("strong",{className:"font-semibold text-white",children:y??h},d)):I||b?s.push(n.jsx("em",{className:"italic text-bright",children:I??b},d)):s.push(l),i=c+l.length}return i<e.length&&s.push(e.slice(i)),s}function Hf(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 Ur(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Kf(e){const t=Ur(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Vf(e){const t=e.trim(),s=t.startsWith(":"),i=t.endsWith(":");return s&&i?"center":i?"right":"left"}function Gf(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("|")&&Kf(c)){const y=Ur(r),I=Ur(c).map(k=>Vf(k));i+=2;const b=[];for(;i<t.length;){const k=t[i]??"";if(!k.trim()||!k.includes("|"))break;b.push(Ur(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,E)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:I[E]??"left"},children:Vs(k,`tbl-h-${i}-${E}`)},`tbl-h-${E}`))})}),n.jsx("tbody",{children:b.map((k,E)=>n.jsx("tr",{className:E<b.length-1?"border-b border-subtle":void 0,children:y.map((q,w)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:I[w]??"left"},children:Vs(k[w]??"",`tbl-r-${i}-${E}-${w}`)},`tbl-r-${E}-c-${w}`))},`tbl-r-${E}`))})]})},`tbl-${i}`));continue}if(a.startsWith("```")){const y=a.slice(3).trim(),h=[];for(i+=1;i<t.length&&!(t[i]??"").trim().startsWith("```");)h.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:h.join(`
|
|
207
|
+
`)})})]},`code-${i}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const y=d[1].length,h=d[2],I=y===1?"text-title font-semibold":y===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:me("tracking-[-0.01em] text-white",I),children:Vs(h,`h-${i}`)},`h-${i}`)),i+=1;continue}if(r.match(/^\s*[-*]\s+(.+)$/)){const y=[];for(;i<t.length;){const I=(t[i]??"").match(/^\s*[-*]\s+(.+)$/);if(!I)break;y.push(I[1]),i+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:y.map((h,I)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Vs(h,`ul-${i}-${I}`)},`ul-${i}-${I}`))},`ul-${i}`));continue}if(r.match(/^\s*\d+\.\s+(.+)$/)){const y=[];for(;i<t.length;){const I=(t[i]??"").match(/^\s*\d+\.\s+(.+)$/);if(!I)break;y.push(I[1]),i+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:y.map((h,I)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Vs(h,`ol-${i}-${I}`)},`ol-${i}-${I}`))},`ol-${i}`));continue}const g=[];for(;i<t.length;){const y=t[i]??"",h=y.trim();if(!h||/^(#{1,3})\s+/.test(h)||/^\s*[-*]\s+/.test(y)||/^\s*\d+\.\s+/.test(y)||h.startsWith("```"))break;g.push(y),i+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Hf(g.join(`
|
|
208
|
+
`),`p-${i}`)},`p-${i}`))}return s}function zi({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:me("space-y-2",s),children:Gf(i)}):null}function Ec(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Xf(e){if(!e)return;const t=Ec(e.metadata);return t?{...e,...t}:e}const Rc={run_started:{icon:"play",label:"Run started",color:D.teal},run_completed:{icon:"check_circle",label:"Run completed",color:D.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:D.red},artifact_created:{icon:"file",label:"Artifact",color:D.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:D.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:D.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:D.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:D.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:D.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:D.red},milestone_completed:{icon:"flag",label:"Milestone",color:D.cyan},delegation:{icon:"workflow",label:"Delegation",color:D.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 eo(e){return e?e.toLowerCase():""}function Qf(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 Yf(e,t){const s=eo(is(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:D.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:D.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:D.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:D.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:D.cyan}:Rc.artifact_created}function Jf(e){const t=Xf(Ec(e.metadata)),s=Qf(e,t),i=eo(is(t,["source"])),r=eo(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:D.teal};if(a==="auto_continue_stopped"){const c=is(t,["stop_reason"]);return c==="error"||c==="blocked"?{icon:"infinity",label:"Needs attention",color:D.red}:c==="budget_exhausted"?{icon:"infinity",label:"Paused",color:D.amber}:{icon:"infinity",label:"Paused",color:D.amber}}if(a==="autopilot_transition"){const c=is(t,["new_state"]);return c==="blocked"||c==="error"?{icon:"infinity",label:"Needs attention",color:D.red}:{icon:"infinity",label:"In progress",color:D.teal}}const l=is(t,["parsed_status","status"]);return l==="completed"||l==="success"?{icon:"check_circle",label:"Completed",color:D.lime}:l==="blocked"||l==="needs_decision"?{icon:"infinity",label:"Needs attention",color:D.amber}:{icon:"infinity",label:"In progress",color:D.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:D.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:D.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:D.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:D.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:D.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:D.iris};if(i==="local_openclaw")return{icon:"terminal",label:"Local",color:D.teal};if(e.type==="artifact_created")return Yf(t,s);if(e.type==="decision_resolved")return r==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:D.red}:{icon:"shield_check",label:"Decision approved",color:D.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:D.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:D.teal}}return Rc[e.type]??{icon:"message",label:"Activity",color:D.textMuted}}function Zf({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(bc,{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 Jr(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function to(e){if(!e)return;const t=Jr(e.metadata);return t?{...e,...t}:e}function eh(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function th(e){let t=0;for(const s of e){const i=to(Jr(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 nh=o.memo(function({items:t,session:s,agentName:i,onBack:r,onOpenItem:a}){const[l,c]=o.useState(!1),d=o.useMemo(()=>[...t].sort((h,I)=>Date.parse(h.timestamp)-Date.parse(I.timestamp)),[t]),m=o.useMemo(()=>th(d),[d]),p=o.useMemo(()=>{if(d.length<2)return null;const h=Date.parse(d[0].timestamp),b=Date.parse(d[d.length-1].timestamp)-h;return b<6e4?`${Math.round(b/1e3)}s`:b<36e5?`${Math.round(b/6e4)}m`:`${(b/36e5).toFixed(1)}h`},[d]),g=o.useMemo(()=>{let h=null,I=null,b=null,k=null,E=null;for(const w of d){const _=to(Jr(w.metadata));if(_&&(!h&&typeof _.domain=="string"&&(h=_.domain),!I&&typeof _.provider=="string"&&(I=_.provider),!b&&typeof _.model=="string"&&(b=_.model),!k&&typeof _.spawn_guard_model_tier=="string"&&(k=_.spawn_guard_model_tier),!E&&typeof _.kickoff_context_hash=="string"&&(E=_.kickoff_context_hash),h&&(I||b)&&k&&E))break}return!(h||I||b||k||E)?null:{domain:h,provider:I,model:b,modelTier:k,kickoffContextHash:E}},[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:D.lime,boxShadow:`0 0 12px ${D.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}),m&&n.jsx("span",{className:"text-muted",children:m}),(g==null?void 0:g.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:Xe(g.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"?`${D.lime}20`:s.status==="failed"?`${D.red}20`:`${D.teal}20`,color:s.status==="running"?D.lime:s.status==="failed"?D.red:D.teal},children:s.status}),g&&(g.provider||g.model||g.modelTier||g.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>c(h=>!h),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&&g&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(g.provider||g.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[g.provider?`${Xe(g.provider)} · `:"",g.model?Hi(g.model):"—"]}),g.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",Xe(g.modelTier)]}),g.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 ",g.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:`${D.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((h,I)=>{var P;const b=Jf(h),k=b.color,E=(P=to(Jr(h.metadata)))==null?void 0:P.model,q=typeof E=="string"?Hi(E):null,w=Xe(h.title??""),_=h.type==="run_failed",W=h.type==="artifact_created",A=h.type==="decision_requested"||h.type==="decision_resolved";return n.jsxs(ce.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:I*.02},onClick:()=>a==null?void 0:a(h),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(Zf,{icon:b.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":W?"text-cyan-300":"text-bright"}`,children:w}),h.summary&&h.summary!==w&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:Xe(h.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:Hr(h.timestamp),children:eh(h.timestamp)}),q&&n.jsx("span",{className:"text-micro text-faint",children:q})]})]},h.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}`:"",m?` · ${m}`:""," · ",n.jsx("span",{title:Hr(d[d.length-1].timestamp),children:Rt(d[d.length-1].timestamp)})]})]})]})});function sh({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(ce.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:`${D.teal}08`,border:`1px solid ${D.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 ih={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 xl(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 rh={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 ah({renderKey:e,displayTitle:t,headline:s,contextLabel:i,detailText:r,displayAgentName:a,railColor:l,statusColor:c,userStateLabel:d,userStateWhy:m,relativeTime:p,timeLabel:g,isRecent:y,enableMotion:h,onOpen:I,ariaLabel:b,artifactSnippet:k,evidenceChips:E,actorCategory:q,queuePosition:w}){const _=(E==null?void 0:E.slice(0,2))??[],W=((E==null?void 0:E.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",P=q==="system",te=n.jsxs("div",{className:me("flex items-start gap-3",P&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Gt,{name:q==="user"?"You":a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:me("absolute inset-y-0 left-0 w-[2px] rounded-full",y&&!P&&"pulse-soft"),style:{backgroundColor:l,boxShadow:P?"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:me("truncate text-caption",P?"text-muted italic":"text-secondary"),title:i,children:P?`OrgX · ${i}`:i}),n.jsx("p",{className:me("mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug",P?"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:g}),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:`${xl(k.typeBadge)}33`,backgroundColor:`${xl(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(zi,{mode:"inline",text:r})}):null,_.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[_.map(R=>{const $=Bi[R.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:$,backgroundColor:`${$}14`,border:`1px solid ${$}30`},children:[R.kind==="pr"&&"PR",R.kind==="commit"&&"Commit",R.kind==="test"&&"Tests",R.kind==="doc"&&"Doc",R.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${$}CC`},children:R.label})]},`${R.kind}-${R.label}`)}),W>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",W," 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:m,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})}),w&&(()=>{const R=rh[w.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:`${R}55`,backgroundColor:`${R}1A`,color:R},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:R}}),w.state==="running"?"Active":`#${w.rank}`]})})()]})]})]});return h?n.jsx(ce.button,{type:"button",variants:ih,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:I,className:A,"aria-label":b,children:te},e):n.jsx("button",{type:"button",onClick:I,className:me(A,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":b,children:te},e)}function oh({open:e,onClose:t,children:s}){return n.jsx(ia,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function lh(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 ch={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 dh({item:e,className:t}){var p,g,y;const s=o.useMemo(()=>vi(e),[e]),i=lh(e),r=ch[i],a=typeof((p=e.metadata)==null?void 0:p.agent_name)=="string"?e.metadata.agent_name:typeof((g=e.metadata)==null?void 0:g.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}`,m=[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(ce.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:m.map((h,I)=>n.jsx(ce.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{duration:.25,delay:.08+I*.06,ease:[.22,1,.36,1]},children:n.jsx(uh,{label:h.label,value:h.value,values:h.values,styles:r})},h.label))})}function uh({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 yl=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),mh=[{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"}],Di=[{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"}],bl={type:"spring",stiffness:400,damping:25},vl={scale:.985};function fn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ph(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 $i(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?Et(Xt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function fh(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function hh(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 Zr(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function yi(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 Lc(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function gh(e){return e==="agent"?"assistant":e}function xh(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function yh(e,t){return t.map(s=>({id:s.id,role:gh(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function Dc(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function bi(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function zr(e){const t=bi(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const i=bi(t.latestMessage),r=bi(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 bh(e){const t=bi(e);if(!t)return null;const s=zr({...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=>bi(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=>bi(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 vh(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=Qi(t,Date.now());return r?i>=r:!0}async function Pi(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 La(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 wh(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 $c=o.createContext(null),Pc=o.createContext(null);function po(){const e=o.useContext($c);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function fo(){const e=o.useContext(Pc);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function kh({children:e,sessions:t,initiatives:s,workspaceId:i,query:r,statusFilter:a,sortOrder:l,timeFilterId:c,customTimeRange:d,snapshot:m,onRequestRefresh:p}){const[g,y]=o.useState((m==null?void 0:m.threads)??[]),[h,I]=o.useState(null),[b,k]=o.useState(null),[E,q]=o.useState(!1),[w,_]=o.useState(null),[W,A]=o.useState("resting"),[P,te]=o.useState(""),[R,$]=o.useState(!1),[ne,xe]=o.useState(!1),[Te,fe]=o.useState(null),[je,ae]=o.useState(null),[ie,X]=o.useState([]),[oe,Le]=o.useState(""),[Me,de]=o.useState([]),[ke,T]=o.useState(""),[z,H]=o.useState(null),[G,we]=o.useState(""),[De,pe]=o.useState(!1),[Ie,M]=o.useState(""),[Ne,_e]=o.useState([]),[Ee,$e]=o.useState(!1),[ge,mt]=o.useState("auto"),[Se,Ae]=o.useState(!1),[J,dt]=o.useState(!1),[yt,Fe]=o.useState(!1),Z=o.useRef(null),B=o.useRef(null),se=o.useRef(null),ue=o.useRef(null);o.useEffect(()=>{m!=null&&m.threads&&y(U=>wh(U,m.threads))},[m==null?void 0:m.threads,m==null?void 0:m.updatedAt]),o.useEffect(()=>{h&&y(U=>U.sort((be,ve)=>fn(ve.lastActivityAt)-fn(be.lastActivityAt)))},[h]);const{data:Pe}=mo({enabled:!0,refetchInterval:8e3}),We=o.useMemo(()=>{var be,ve;const U=new Map;for(const Be of mh)U.set(Be.id,{id:Be.id,name:Be.name,handle:Be.handle,domain:Be.domain,domainLabel:Be.domainLabel,role:Be.role,status:"idle",currentTask:null,isSystem:!1});if(Pe!=null&&Pe.agents)for(const Be of Pe.agents){const wt=U.get(Be.id);wt?(wt.status=Be.status==="running"?"running":(be=Be.blockers)!=null&&be.length?"blocked":"idle",wt.currentTask=Be.currentTask??null):U.set(Be.id,{id:Be.id,name:Be.name,handle:Be.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Be.status==="running"?"running":(ve=Be.blockers)!=null&&ve.length?"blocked":"idle",currentTask:Be.currentTask??null,isSystem:yl.has(Be.id)})}for(const Be of t){const wt=(Be.agentId??"").trim(),Nt=(Be.agentName??"").trim();!wt||!Nt||U.has(wt)||U.set(wt,{id:wt,name:Nt,handle:wt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:yl.has(wt)})}return Array.from(U.values()).filter(Be=>!Be.isSystem).sort((Be,wt)=>Be.name.localeCompare(wt.name))},[Pe,t]),rt=o.useMemo(()=>s.map(U=>({id:U.id,name:U.name})).sort((U,be)=>U.name.localeCompare(be.name)),[s]),he=o.useMemo(()=>We.find(U=>U.id===oe)??null,[We,oe]),Ve=o.useMemo(()=>{const U=new Set(Me);return We.filter(be=>U.has(be.id))},[We,Me]),re=o.useMemo(()=>rt.find(U=>U.id===ke)??null,[rt,ke]);o.useEffect(()=>{oe&&de(U=>U.filter(be=>be!==oe))},[oe]);const K=o.useMemo(()=>We.slice(0,8),[We]),Ce=o.useMemo(()=>{const U=G.trim().toLowerCase();return U?We.filter(be=>be.name.toLowerCase().includes(U)||be.handle.toLowerCase().includes(U)||be.domain.toLowerCase().includes(U)||be.role.toLowerCase().includes(U)):We},[We,G]),Ze=o.useMemo(()=>{const U=Ie.trim().toLowerCase();return U?rt.filter(be=>be.name.toLowerCase().includes(U)):rt},[rt,Ie]),at=o.useMemo(()=>{const U=r.trim().toLowerCase(),be=g.filter(ve=>!hh(ve,a)||!vh(ve,c,d)?!1:U.length===0?!0:fh(ve).includes(U));return be.sort((ve,Be)=>{const wt=fn(Be.lastActivityAt)-fn(ve.lastActivityAt);return l==="newest"?wt:-wt}),be},[d,r,l,a,g,c]),pt=o.useMemo(()=>{if(!h||at.some(be=>be.id===h))return at;const U=g.find(be=>be.id===h);return U?[U,...at]:at},[h,at,g]),ct=o.useMemo(()=>g.find(U=>U.id===h)??null,[h,g]),ht=o.useMemo(()=>ie.filter(U=>U.status!=="ready").length,[ie]),Y=P.trim().length>0&&!R,ye=o.useMemo(()=>ht>0?`${ht} attachment(s) still processing.`:"Press Enter to send.",[ht]),Oe=o.useMemo(()=>R?"Sending…":ne?"Launching…":"Send",[ne,R]),Ge=o.useMemo(()=>new fd({api:"/orgx/api/chat/usechat"}),[]),{messages:Re,setMessages:He,sendMessage:Ue,status:ft,error:Ht,clearError:gt}=hd({id:`orgx-chat-guidance-${i??"global"}`,transport:Ge,onError:U=>{fe($i((U==null?void 0:U.message)??null,"send"))}});o.useEffect(()=>{if(!b){He([]);return}He(yh(b.id,b.messages))},[b,He]);const vt=o.useMemo(()=>{const U=[...Re].reverse().find(ve=>ve.role==="assistant");if(!U)return null;const be=xh(U);return be.length>0?be:null},[Re]),Ct=o.useRef(null);o.useEffect(()=>{if(ft!=="ready"&&ft!=="error"||!vt)return;const U=[...Re].reverse().find(be=>be.role==="assistant");!U||U.id===Ct.current||(Ct.current=U.id,_e(be=>[...be,{id:`guidance_${U.id}`,role:"agent",body:vt,timestamp:new Date().toISOString()}]))},[ft,vt,Re]);const Ut=o.useCallback(()=>{te(""),X([]),dt(!1),Fe(!1),fe(null),ae(null)},[]),nt=o.useCallback(U=>{_e(be=>[...be,{...U,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),et=o.useCallback(()=>_e([]),[]),$t=o.useCallback(()=>$e(U=>!U),[]),_t=o.useMemo(()=>Di.find(U=>U.id===ge)??Di[0],[ge]),Tt=o.useCallback(()=>{mt(U=>{const be=Di.findIndex(ve=>ve.id===U);return Di[(be+1)%Di.length].id})},[]),St=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),Kt=o.useCallback(async U=>{var Be;q(!0),_(null);const be=await Pi(`/orgx/api/chat/threads/${encodeURIComponent(U)}`);if(!be.ok||!((Be=be.data)!=null&&Be.thread))return q(!1),_($i(be.error,"load")),null;const ve=bh(be.data.thread);return ve?(k(ve),q(!1),ve):(q(!1),_("Thread detail payload was invalid."),null)},[]),vn=o.useCallback(async(U,be)=>{be&&(se.current=be),I(U),await Kt(U),requestAnimationFrame(()=>{var ve;return(ve=B.current)==null?void 0:ve.focus()})},[Kt]),ys=o.useCallback(()=>{var U;I(null),k(null),_(null),q(!1),(U=se.current)==null||U.focus()},[]),Hn=o.useCallback(U=>{window.setTimeout(()=>{X(be=>be.map(ve=>ve.id===U?{...ve,status:"indexing",updatedAt:new Date().toISOString()}:ve))},80),window.setTimeout(()=>{X(be=>be.map(ve=>{var Nt;if(ve.id!==U)return ve;const Be=((Nt=ve.mimeType)==null?void 0:Nt.toLowerCase())==="application/x-msdownload"||ve.name.toLowerCase().endsWith(".exe"),wt=(ve.sizeBytes??0)>25*1024*1024;return Be?{...ve,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:wt?{...ve,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...ve,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Kn=o.useCallback(U=>{if(!U||U.length===0)return;const be=new Date().toISOString(),ve=Array.from(U).map(Be=>({id:`draft_att_${crypto.randomUUID()}`,name:Be.name,mimeType:Be.type||null,sizeBytes:Number.isFinite(Be.size)?Be.size:null,status:"preparing",error:null,masked:!1,createdAt:be,updatedAt:be}));X(Be=>Be.concat(ve)),ve.forEach(Be=>Hn(Be.id)),js("chat_attachment_state_changed",{count:ve.length,state:"preparing"})},[Hn]),Vn=o.useCallback(U=>{X(be=>be.map(ve=>ve.id===U?{...ve,status:"preparing",error:null,updatedAt:new Date().toISOString()}:ve)),Hn(U),js("chat_attachment_state_changed",{state:"retry"})},[Hn]),Gn=o.useCallback(U=>{Le(be=>be===U?"":U),de(be=>be.filter(ve=>ve!==U)),H(null),we("")},[]),Es=o.useCallback(U=>{de(be=>be.includes(U)?be.filter(ve=>ve!==U):be.concat(U))},[]),wn=o.useCallback(()=>{pe(!1),M(""),H(U=>U==="assignee"?null:"assignee"),we("")},[]),Qt=o.useCallback(()=>{pe(!1),M(""),H(U=>U==="watcher"?null:"watcher"),we("")},[]),an=o.useCallback(()=>{H(null),we(""),pe(U=>!U),M("")},[]),hn=o.useCallback(async(U,be)=>{var Nt;Ae(!0);const ve=rt.find(st=>st.id===be)??null,Be=await Pi("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:U,project_id:i??void 0,initiativeId:(ve==null?void 0:ve.id)??null,initiativeTitle:(ve==null?void 0:ve.name)??null,relinked:!0})});if(Ae(!1),!Be.ok||!((Nt=Be.data)!=null&&Nt.thread)){_(Be.error??"Scope link failed.");return}const wt=zr(Be.data.thread);wt&&y(st=>La(st,wt)),await Kt(U),await St(),js("chat_thread_linked_initiative",{threadId:U,initiativeId:(ve==null?void 0:ve.id)??null})},[rt,Kt,St,i]),Rs=o.useCallback(async U=>{gt(),await Ue({text:U.prompt},{body:{threadId:U.thread.id,project_id:i??void 0,initiativeId:U.thread.initiativeId??(re==null?void 0:re.id)??void 0,initiativeTitle:U.thread.initiativeTitle??(re==null?void 0:re.name)??void 0,assigneeId:(he==null?void 0:he.id)??U.thread.assigneeId??void 0,assigneeName:(he==null?void 0:he.name)??U.thread.assigneeName??void 0,watcherIds:Ve.map(be=>be.id),watcherNames:Ve.map(be=>be.name)}}),await St(),await Kt(U.thread.id)},[gt,Kt,St,he==null?void 0:he.id,he==null?void 0:he.name,re==null?void 0:re.id,re==null?void 0:re.name,Ve,Ue,i]),Xn=o.useCallback(async()=>{var wt,Nt;const U=P.trim();if(!U)return fe("Write a message before sending."),{thread:null,messageId:null};fe(null),ae(null),$(!0);const be=await Pi("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:h??void 0,project_id:i??void 0,initiativeId:(re==null?void 0:re.id)??(b==null?void 0:b.initiativeId)??void 0,initiativeTitle:(re==null?void 0:re.name)??(b==null?void 0:b.initiativeTitle)??void 0,assigneeId:(he==null?void 0:he.id)??(b==null?void 0:b.assigneeId)??void 0,assigneeName:(he==null?void 0:he.name)??(b==null?void 0:b.assigneeName)??void 0,watcherIds:Ve.map(st=>st.id),watcherNames:Ve.map(st=>st.name),body:U,attachments:ie.map(st=>({id:st.id,name:st.name,mimeType:st.mimeType,sizeBytes:st.sizeBytes,status:st.status,error:st.error,masked:st.masked}))})});if($(!1),!be.ok||!((wt=be.data)!=null&&wt.thread))return fe($i(be.error,"send")),js("chat_message_send_failed",{reason:be.error??"unknown"}),{thread:null,messageId:null};const ve=zr(be.data.thread);if(!ve)return fe("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};y(st=>La(st,ve)),nt({role:"user",body:U}),ge!=="auto"&&he&&nt({role:"system",body:`Routing to ${he.name} via ${_t.label}`}),js("chat_message_sent",{threadId:ve.id,watcherCount:ve.watcherIds.length}),await St();const Be=be.data.message&&typeof be.data.message.id=="string"?be.data.message.id:((Nt=ve.latestMessage)==null?void 0:Nt.id)??null;return I(ve.id),await Kt(ve.id),Rs({thread:ve,prompt:U}).catch(st=>{nt({role:"error",body:$i(st instanceof Error?st.message:String(st??""),"send")})}),Ut(),A("reviewing"),{thread:ve,messageId:Be}},[b==null?void 0:b.assigneeId,b==null?void 0:b.assigneeName,b==null?void 0:b.initiativeId,b==null?void 0:b.initiativeTitle,h,P,ie,Kt,St,Ut,Rs,he==null?void 0:he.id,he==null?void 0:he.name,re==null?void 0:re.id,re==null?void 0:re.name,ge,_t,Ve,i]),bs=o.useCallback(async(U,be)=>{var Jn,Mt,dn,as,Zn,Ds,$s;if(!be){nt({role:"error",body:"Send a message first to launch."});return}if(!he){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}xe(!0),fe(null),ae(null);const ve=await Pi("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:he.id,message:P.trim().length>0?P.trim():U.lastSnippet??U.title,initiativeId:U.initiativeId??(re==null?void 0:re.id)??void 0,initiativeTitle:U.initiativeTitle??(re==null?void 0:re.name)??void 0,workstreamId:U.workstreamId??void 0,taskId:U.taskId??void 0,provider:ge!=="auto"?ge:void 0})}),Be=((Jn=ve.data)==null?void 0:Jn.sessionId)??((Mt=ve.data)==null?void 0:Mt.runId)??null,wt=ve.ok&&Be?"running":ve.ok?"queued":"blocked",Nt=ve.ok?null:ve.error??"Launch request failed before queueing.",st=await Pi("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:U.id,messageId:be,assigneeId:he.id,assigneeName:he.name,watcherIds:Ve.map(os=>os.id),watcherNames:Ve.map(os=>os.name),executionMode:"local_queue",provider:((dn=ve.data)==null?void 0:dn.provider)??(ge!=="auto"?ge:"openclaw"),runId:Be??void 0,status:wt,blockedReason:Nt??void 0,warnings:ht>0?[`${ht} attachment(s) were not ready at launch.`]:[]})});if(xe(!1),Fe(!1),dt(!1),!st.ok||!((as=st.data)!=null&&as.thread)){fe(st.error?$i(st.error,"launch"):Nt??"Launch state could not be persisted. Message remained saved."),js("chat_launch_failed",{threadId:U.id,reason:st.error??Nt??"unknown"});return}const Yt=zr(st.data.thread);if(Yt&&y(os=>La(os,Yt)),await Kt(U.id),await St(),!ve.ok){fe(`Launch blocked: ${Nt??"Set assignee and retry."}`),js("chat_launch_blocked",{threadId:U.id,reason:Nt??"unknown"});return}const jt=((Zn=ve.data)==null?void 0:Zn.provider)==="anthropic"?"Claude Code":((Ds=ve.data)==null?void 0:Ds.provider)==="openai"?"Codex":_t.shortLabel,Yn=($s=ve.data)!=null&&$s.model?` (${ve.data.model})`:"";ae(Be?`Launch started via ${jt}${Yn}. Thread timeline now tracks execution state.`:`Launch queued locally via ${jt}. Run starts when a worker is available.`),js(Be?"chat_launch_started":"chat_launch_queued",{threadId:U.id,runId:Be,assigneeId:he.id})},[P,yt,Kt,St,he,re==null?void 0:re.id,re==null?void 0:re.name,ge,_t,Ve,ht]),ti=o.useCallback(async()=>{var be;const U=await Xn();(be=U.thread)!=null&&be.id&&await vn(U.thread.id)},[vn,Xn]),Ls=o.useCallback(async()=>{const U=await Xn();U.thread&&(await bs(U.thread,U.messageId),await vn(U.thread.id))},[bs,vn,Xn]),Vt=o.useCallback(async()=>{if(Y){if(he){await Ls();return}await ti()}},[Y,Ls,ti,he]),Cn=o.useMemo(()=>({threads:g,activeThreadId:h,activeThread:b,activeThreadSummary:ct,displayedThreads:pt,composerMode:W,draft:P,draftAttachments:ie,sending:R,launching:ne,composerError:Te,composerNotice:je,selectedAssigneeId:oe,selectedAssignee:he,selectedWatcherIds:Me,selectedWatchers:Ve,selectedInitiativeId:ke,selectedInitiative:re,agentOptions:We,quickAssigneeOptions:K,initiativeOptions:rt,agentPickerMode:z,agentPickerQuery:G,filteredAgentOptions:Ce,scopePickerOpen:De,scopePickerQuery:Ie,filteredInitiativeOptions:Ze,panelLoading:E,panelError:w,scopeSaving:Se,launchWarningOpen:J,launchWarningAccepted:yt,unresolvedAttachmentCount:ht,canSend:Y,composerGuidance:ye,primaryActionLabel:Oe,guidanceStatus:ft,guidancePreview:vt,guidanceError:Ht??null,inlineMessages:Ne,threadSidebarOpen:Ee,workspaceId:i,selectedProvider:ge,selectedProviderDef:_t}),[g,h,b,ct,pt,W,P,ie,R,ne,Te,je,oe,he,Me,Ve,ke,re,We,K,rt,z,G,Ce,De,Ie,Ze,E,w,Se,J,yt,ht,Y,ye,Oe,ft,vt,Ht,Ne,Ee,i,ge,_t]),Qn=o.useMemo(()=>({setDraft:te,setComposerMode:A,setDraftAttachments:X,selectAssignee:Gn,toggleWatcher:Es,setSelectedInitiativeId:T,toggleAssigneePicker:wn,toggleWatcherPicker:Qt,toggleScopePicker:an,setAgentPickerQuery:we,setScopePickerQuery:M,setAgentPickerMode:H,setScopePickerOpen:pe,handlePrimaryAction:Vt,handleFilesAdded:Kn,handleRetryAttachment:Vn,openThreadPanel:vn,closeThreadPanel:ys,loadThreadDetail:Kt,applyScopeLink:hn,resetComposer:Ut,setComposerError:fe,setComposerNotice:ae,setLaunchWarningAccepted:Fe,pushInlineMessage:nt,clearInlineMessages:et,toggleThreadSidebar:$t,setSelectedProvider:mt,cycleProvider:Tt,fileInputRef:Z,panelHeadingRef:B,composerShellRef:ue}),[Gn,Es,wn,Qt,an,Vt,Kn,Vn,vn,ys,Kt,hn,Ut,nt,et,$t,Tt]);return n.jsx($c.Provider,{value:Cn,children:n.jsx(Pc.Provider,{value:Qn,children:e})})}const Ih={type:"spring",stiffness:500,damping:35,mass:.5};function Nh({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(ce.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:me("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(ce.div,{initial:r?!1:{opacity:0,y:8,scale:.97},animate:r?{}:{opacity:1,y:0,scale:1},transition:r?void 0:Ih,className:me("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:me("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:me("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:me("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 wl({open:e,onClose:t}){const s=xs(),{displayedThreads:i,activeThreadId:r,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:m,initiativeOptions:p}=po(),{openThreadPanel:g,closeThreadPanel:y,loadThreadDetail:h,applyScopeLink:I,panelHeadingRef:b}=fo(),k=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,E=o.useCallback((w,_)=>{g(w,_)},[g]),q=o.useCallback(()=>{y(),t()},[y,t]);return n.jsx(bt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:q,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(ce.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:q,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:me("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(ra,{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(w=>n.jsxs("button",{type:"button",onClick:_=>E(w.id,_.currentTarget),className:me("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",r===w.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:w.lastSnippet?`"${w.lastSnippet.length>40?w.lastSnippet.slice(0,40)+"...":w.lastSnippet}"`:w.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:w.lastActivityAt,children:Rt(w.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[w.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",w.assigneeName]}),n.jsx("span",{children:w.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",yi(w.status)),children:Zr(w.status)})]})]},w.id))})}),n.jsx(bt,{initial:!1,children:r&&n.jsxs(ce.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:b,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:me("rounded-full border px-2 py-0.5 text-micro font-semibold",yi((l==null?void 0:l.status)??"message_only")),children:Zr((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 h(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(w=>n.jsx("article",{className:me("flex",w.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:me("max-w-[90%] rounded-xl border px-2.5 py-1.5",w.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":w.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:w.senderName??Lc(w.role)}),n.jsx("time",{dateTime:w.createdAt,children:Rt(w.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:w.body})]})},w.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(w=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",yi(Dc(w.status))),children:w.status}),n.jsx("span",{children:w.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:w.requestedAt,children:Rt(w.requestedAt)})]},w.id))]})]})})]})]})]})})}function kl(){const e=xs(),{displayedThreads:t,activeThreadId:s,activeThread:i,activeThreadSummary:r,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:m}=po(),{openThreadPanel:p,closeThreadPanel:g,loadThreadDetail:y,applyScopeLink:h,setComposerMode:I,toggleThreadSidebar:b,panelHeadingRef:k}=fo(),E=(i==null?void 0:i.id)??(r==null?void 0:r.id)??null,q=o.useCallback(()=>{b()},[b]);return m?n.jsx(bt,{children:m&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:q,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(ce.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:q,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(ce.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:vl,transition:bl,onClick:()=>{q(),I("focused"),requestAnimationFrame(()=>{const w=document.getElementById("chat-dock-input");w instanceof HTMLTextAreaElement&&w.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((w,_)=>n.jsxs(ce.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:bl,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:vl,onClick:W=>void p(w.id,W.currentTarget),className:me("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===w.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:w.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:w.lastActivityAt,children:Rt(w.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:w.lastSnippet??w.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[w.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Gt,{name:w.assigneeName,hint:w.assigneeName,size:"xs"}),n.jsx("span",{children:w.assigneeName})]}),n.jsx("span",{children:w.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",yi(w.status)),children:Zr(w.status)})]})]},w.id))})}),n.jsx(bt,{initial:!1,children:s&&n.jsxs(ce.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:me("rounded-full border px-2 py-0.5 text-micro font-semibold",yi((r==null?void 0:r.status)??"message_only")),children:Zr((r==null?void 0:r.status)??"message_only")}),n.jsx("button",{type:"button",onClick:g,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}),E&&n.jsx("button",{type:"button",onClick:()=>void y(E),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(w=>n.jsx("article",{className:me("flex",w.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:me("max-w-[90%] rounded-xl border px-2.5 py-1.5",w.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":w.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:w.senderName??Lc(w.role)}),n.jsx("time",{dateTime:w.createdAt,children:Rt(w.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:w.body})]})},w.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(w=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",yi(Dc(w.status))),children:w.status}),n.jsx("span",{children:w.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:w.requestedAt,children:Rt(w.requestedAt)})]},w.id))]})]})})]},"sidebar-panel")]})}):null}const jh={type:"spring",stiffness:500,damping:30,mass:.5};function Ah({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 m=l.current.querySelector('[data-active="true"]');m&&m.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(m=>{const p=s.toLowerCase();return m.name.toLowerCase().includes(p)||m.handle.toLowerCase().includes(p)||m.domain.toLowerCase().includes(p)||m.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(ce.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:jh,className:me("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((m,p)=>{const g=p===i;return n.jsxs("button",{type:"button",role:"option","aria-selected":g,"data-active":g,onClick:()=>r(m),onMouseDown:y=>y.preventDefault(),className:me("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",g?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Gt,{name:m.name,hint:m.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:m.name}),m.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:m.domainLabel})]})]},m.id)})})})})}const _h={type:"spring",stiffness:500,damping:30,mass:.5};function Sh({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 m=l.current.querySelector('[data-active="true"]');m&&m.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(m=>m.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=c.slice(0,6);return n.jsx(bt,{children:n.jsx(ce.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:_h,className:me("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:m=>m.preventDefault(),className:me("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((m,p)=>{const g=p+1===i;return n.jsx("button",{type:"button",role:"option","aria-selected":g,"data-active":g,onClick:()=>r(m),onMouseDown:y=>y.preventDefault(),className:me("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",g?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:m.name})},m.id)})]})})})}function Ch({open:e,mode:t,agents:s,quickAgents:i,query:r,selectedAssigneeId:a,selectedWatcherIds:l,onQueryChange:c,onSelectAssignee:d,onToggleWatcher:m,onClose:p,onSwitchMode:g,anchorRef:y}){const h=xs();return n.jsx(bt,{children:e&&n.jsxs(ce.div,{initial:h?!1:{opacity:0,scale:.95,y:8},animate:h?{}:{opacity:1,scale:1,y:0},exit:h?{}:{opacity:0,scale:.95,y:8},transition:h?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:()=>g("assignee"),className:me("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:()=>g("watcher"),className:me("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(I=>{const b=a===I.id;return n.jsx("button",{type:"button",onClick:()=>d(I.id),title:I.name,className:me("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",b?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":b,"aria-label":`Select ${I.name} as assignee`,children:n.jsx(Gt,{name:I.name,hint:I.name,size:"xs"})},I.id)})}),n.jsx("input",{value:r,onChange:I=>c(I.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(I=>{const b=a===I.id,k=l.includes(I.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(I.id);return}b||m(I.id)},className:me("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",b?"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:I.name,hint:I.name,size:"xs"}),n.jsx("span",{children:I.name})]}),n.jsx("span",{className:"text-micro",children:b?"Assignee":k?"Watcher":"Select"})]},I.id)})})]})})}const Il=24,Nl=200;function jl(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 Th(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 Al({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 no="orgx-chat-dock-collapsed";function Mh(){try{return localStorage.getItem(no)==="1"}catch{return!1}}function Eh(){const e=po(),t=fo(),s=xs(),i=o.useRef(null),r=o.useRef(null),[a,l]=o.useState(Mh),c=o.useCallback(()=>{l(K=>{const Ce=!K;try{localStorage.setItem(no,Ce?"1":"0")}catch{}return Ce})},[]),[d,m]=o.useState(!1),[p,g]=o.useState(!1),y=o.useRef(null),[h,I]=o.useState(!1),[b,k]=o.useState(""),[E,q]=o.useState(0),[w,_]=o.useState(-1),[W,A]=o.useState(!1),[P,te]=o.useState(""),[R,$]=o.useState(0),[ne,xe]=o.useState(-1),{composerMode:Te,draft:fe,draftAttachments:je,sending:ae,launching:ie,selectedAssigneeId:X,selectedAssignee:oe,selectedWatcherIds:Le,selectedInitiative:Me,agentOptions:de,quickAssigneeOptions:ke,agentPickerMode:T,agentPickerQuery:z,filteredAgentOptions:H,initiativeOptions:G,canSend:we,activeThreadId:De,guidanceStatus:pe,inlineMessages:Ie,displayedThreads:M,launchWarningOpen:Ne,launchWarningAccepted:_e,selectedProvider:Ee,selectedProviderDef:$e}=e,ge=fe.trim(),mt=Ie.length>0;ge.length>0;const Se=o.useCallback(()=>{const K=i.current;if(!K)return;K.style.height="0";const Ce=Math.min(Math.max(K.scrollHeight,Il),Nl);K.style.height=`${Ce}px`},[]);o.useLayoutEffect(()=>{Se()},[fe,Se]);const Ae=o.useMemo(()=>{if(!h)return de;const K=b.toLowerCase();return K?de.filter(Ce=>Ce.name.toLowerCase().includes(K)||Ce.handle.toLowerCase().includes(K)||Ce.domain.toLowerCase().includes(K)||Ce.role.toLowerCase().includes(K)):de},[de,h,b]),J=o.useMemo(()=>{if(!W)return G;const K=P.toLowerCase();return K?G.filter(Ce=>Ce.name.toLowerCase().includes(K)):G},[G,W,P]);o.useEffect(()=>{if(y.current&&clearTimeout(y.current),Ie.length<=2){g(!1);return}return g(!1),y.current=window.setTimeout(()=>{g(!0)},5e3),()=>{y.current&&clearTimeout(y.current)}},[Ie.length]),o.useEffect(()=>{const K=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="k"){if(Ce.preventDefault(),a){l(!1);try{localStorage.setItem(no,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var Ze;return(Ze=i.current)==null?void 0:Ze.focus()})}};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[t,a]);const dt=o.useCallback(()=>{Te==="resting"&&t.setComposerMode("focused")},[Te,t]),yt=o.useCallback(()=>{window.setTimeout(()=>{ge.length===0&&!mt&&!h&&!W&&je.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),I(!1),A(!1))},100)},[ge,mt,h,W,je.length,t]),Fe=o.useCallback(K=>{const Ce=K.target.value,Ze=K.target.selectionStart??Ce.length;t.setDraft(Ce),(Te==="resting"||Te==="focused")&&t.setComposerMode("composing");const at=Ce.slice(0,Ze),pt=at.match(/@(\w*)$/);if(pt){I(!0),k(pt[1]),q(0),_(Ze-pt[0].length),A(!1);return}const ct=at.match(/#(\w*)$/);if(ct){A(!0),te(ct[1]),$(0),xe(Ze-ct[0].length),I(!1);return}h&&I(!1),W&&A(!1)},[Te,t,h,W]),Z=o.useCallback(K=>{var pt;const Ce=fe.slice(0,w),Ze=fe.slice(((pt=i.current)==null?void 0:pt.selectionStart)??fe.length),at=`${Ce}@${K.name} ${Ze}`;t.setDraft(at),t.selectAssignee(K.id),I(!1),k(""),requestAnimationFrame(()=>{if(i.current){const ct=Ce.length+K.name.length+2;i.current.setSelectionRange(ct,ct),i.current.focus()}})},[fe,w,t]),B=o.useCallback(K=>{var at;const Ce=fe.slice(0,ne),Ze=fe.slice(((at=i.current)==null?void 0:at.selectionStart)??fe.length);if(K){const pt=`${Ce}#${K.name} ${Ze}`;t.setDraft(pt),t.setSelectedInitiativeId(K.id),requestAnimationFrame(()=>{if(i.current){const ct=Ce.length+K.name.length+2;i.current.setSelectionRange(ct,ct),i.current.focus()}})}else{const pt=`${Ce}${Ze}`;t.setDraft(pt),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{i.current&&(i.current.setSelectionRange(Ce.length,Ce.length),i.current.focus())})}A(!1),te("")},[fe,ne,t]),se=o.useCallback(K=>{if(h&&Ae.length>0){if(K.key==="ArrowDown"){K.preventDefault(),q(Ce=>(Ce+1)%Ae.length);return}if(K.key==="ArrowUp"){K.preventDefault(),q(Ce=>(Ce-1+Ae.length)%Ae.length);return}if(K.key==="Enter"||K.key==="Tab"){K.preventDefault(),Z(Ae[E]);return}if(K.key==="Escape"){K.preventDefault(),I(!1);return}}if(W){const Ce=J.length+1;if(K.key==="ArrowDown"){K.preventDefault(),$(Ze=>(Ze+1)%Ce);return}if(K.key==="ArrowUp"){K.preventDefault(),$(Ze=>(Ze-1+Ce)%Ce);return}if(K.key==="Enter"||K.key==="Tab"){K.preventDefault(),B(R===0?null:J[R-1]);return}if(K.key==="Escape"){K.preventDefault(),A(!1);return}}if(K.key==="Enter"&&!K.shiftKey){K.preventDefault(),t.handlePrimaryAction();return}K.key==="Escape"&&(K.preventDefault(),T?t.setAgentPickerMode(null):mt?t.clearInlineMessages():(t.setComposerMode("resting"),K.target.blur()))},[t,T,mt,h,Ae,E,Z,W,J,R,B]),ue=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),Pe=ae||ie?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=(Te==="reviewing"||mt)&&Ie.length>0,rt=pe==="submitted"||pe==="streaming",he=o.useRef(Ie.length),[Ve,re]=o.useState(0);return o.useEffect(()=>{if(!a){he.current=Ie.length,re(0);return}const K=Ie.length-he.current;K>0&&re(K)},[a,Ie.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(wl,{open:d,onClose:()=>m(!1)}),n.jsx(kl,{}),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(ce.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var K;return(K=i.current)==null?void 0:K.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:me("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(ce.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:me("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(wl,{open:d,onClose:()=>m(!1)}),n.jsx(kl,{}),n.jsxs("div",{ref:K=>{t.composerShellRef.current=K},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:Ne&&n.jsxs(ce.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:_e,onChange:K=>t.setLaunchWarningAccepted(K.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(Ch,{open:T!==null,mode:T??"assignee",agents:H,quickAgents:ke,query:z,selectedAssigneeId:X,selectedWatcherIds:Le,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:r})}),n.jsxs(ce.section,{"data-testid":"chat-dock","data-state":Te,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:me("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",Te!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:c,className:me("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:K=>{t.fileInputRef.current=K},type:"file",multiple:!0,className:"hidden",onChange:K=>{t.handleFilesAdded(K.target.files),K.currentTarget.value=""}}),n.jsx(bt,{children:We&&n.jsx(Nh,{messages:Ie,isStreaming:rt,collapsed:p,onClick:ue})}),n.jsxs("div",{className:"relative",children:[n.jsx(Ah,{open:h,agents:Ae,query:b,activeIndex:E,anchorRect:null,onSelect:Z,onClose:()=>I(!1)}),n.jsx(Sh,{open:W,initiatives:J,query:P,activeIndex:R,onSelect:B,onClose:()=>A(!1)})]}),n.jsx(bt,{initial:!1,children:je.length>0&&n.jsx(ce.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:je.map(K=>n.jsxs("div",{className:me("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",K.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:`${jl(K.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:jl(K.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:K.name}),n.jsxs("p",{className:"text-micro text-muted",children:[Th(K.mimeType,K.name),K.sizeBytes?` · ${ph(K.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Ce=>Ce.filter(Ze=>Ze.id!==K.id)),className:me("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 ${K.name}`,children:"×"}),K.status!=="ready"&&K.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]"})}),K.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(K.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"})]},K.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var K;return(K=t.fileInputRef.current)==null?void 0:K.click()},className:me("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(ce.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:me("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(Al,{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:fe,onFocus:dt,onBlur:yt,onChange:Fe,onKeyDown:se,placeholder:"Ask anything",rows:1,className:me("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:Il,maxHeight:Nl,overflowY:"auto"},"aria-expanded":Te!=="resting"})]}),M.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():m(!0)},className:me("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":`${M.length} thread${M.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"})}),M.length]}),n.jsx(ce.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!we,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:me("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",we?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:oe?`Send to ${oe.name} via ${$e.shortLabel}`:`Send via ${$e.shortLabel}`,"aria-label":oe?`Send to ${oe.name} via ${$e.shortLabel}`:`Send message via ${$e.shortLabel}`,children:Pe})]}),n.jsx(bt,{children:(oe||Me)&&Te!=="resting"&&n.jsxs(ce.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:[oe&&n.jsxs("button",{ref:K=>{r.current=K},type:"button",onClick:t.toggleWatcherPicker,className:me("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:oe.name,hint:oe.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",oe.name]}),oe.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(Al,{icon:$e.icon}),$e.shortLabel]})]})})]})]})]})}const _l={completed:D.lime,needs_attention:D.amber,in_progress:D.teal,blocked:D.red,unknown:"rgba(255,255,255,0.4)"};function Sl({workstreamTitle:e,items:t,firstTimestamp:s,lastTimestamp:i,onExpandItem:r}){const[a,l]=o.useState(!1),c=t.reduce((p,g)=>(p[g.status]=(p[g.status]??0)+1,p),{}),d=new Date(s).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),m=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:D.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:D.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:D.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:D.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:D.red}}),c.blocked," blocked"]})]}),n.jsxs("p",{className:"mt-1 text-micro text-muted tabular-nums",children:[d," — ",m]})]}),n.jsx("span",{className:"mt-1.5 text-micro text-muted",children:a?"Hide":"Show details"})]}),n.jsx(bt,{children:a&&n.jsx(ce.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,g)=>n.jsxs(ce.button,{type:"button",initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:g*.04,duration:.15},onClick:()=>r==null?void 0:r(g),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:_l[p.status]??_l.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-${g}`))})})})]})}const Da=50,Rh=50,Oi=20,Cl=3600,Tl=12e3,Lh=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 jr(e,t,s){if(!t)return;const i=e.get(t);if(i){i.push(s);return}e.set(t,[s])}function Dh(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 Ar={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},Ml=["live","24h","7d","all"];function El(e){if(e==="custom"||e==="all")return null;const t=Ml.indexOf(e);return t<0?null:Ml[t+1]??null}function Rl(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 $h(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Ll(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 _r(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Sr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function $a(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function Dl(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 ho(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 ho(t)}function Ph(e){const t=ho(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 hi(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 $l(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Oh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qh=/^[0-9a-f]{20,}$/i,Oc=/^\d+$/,qc=/^(user|usr|clerk)_[a-z0-9]+$/i;function yn(e){if(!e)return null;const t=e.trim();return!t||Oh.test(t)||qh.test(t)||Oc.test(t)||qc.test(t)?null:t}const Bh=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Fh(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Bh.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Pl(e,t,s){if(!e)return null;let i=null;for(const a of t){const l=yn($l(e[a]));if(l){i=l;break}}let r=null;for(const a of s){const l=yn($l(e[a]));if(l){r=l;break}}return!i&&!r?null:{id:i,name:r,label:r??i??"OrgX"}}function Uh(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 Ol(e){const t=lt(e),s=Gs(e),i=Xi(e),r=yn(s.agentId),a=yn(s.agentName),l=yn(e.requesterAgentId??null),c=yn(e.requesterAgentName??null),m=(l||c?{id:l,name:c,label:c??l??"OrgX"}:null)??Pl(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),g=yn(e.executorAgentName??null),h=(p||g?{id:p,name:g,label:g??p??"Agent"}:null)??Pl(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 m&&h?Uh(m,h)?{requester:m,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.label}:{requester:m,executor:h,mode:"handoff",primaryLabel:h.label,subtitle:`${m.label} handed off to ${h.label}`}:m&&!h?{requester:m,executor:null,mode:"requested",primaryLabel:m.label,subtitle:`${m.label} requested a run`}:!m&&h?{requester:null,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.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 ql(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const zh=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Wh=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Hh(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=lt(e),i=le(s,["event","event_name","eventName"])??"";return(le(s,["source"])??"")==="user"?"user":zh.has(i)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Wh.has(i)?"system":"agent"}const Kh={user:D.lime,system:"rgba(255,255,255,0.15)",orchestrator:D.iris,agent:""};function Vh(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 Cr(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 Bl=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 Tr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Bc(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 Gh(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 Xh(e){const t=lt(e),s=Tr(e.kind)??Tr(t==null?void 0:t.activity_bucket)??Tr(t==null?void 0:t.activityBucket)??Tr(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=Gh(t),r=e.decisionRequired===!0||Bc(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(le(t,["stop_reason","stopReason"])??"");if(p==="blocked"||p==="error")return"decision"}return i&&Bl.has(i)?Bl.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 Qh(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=le(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if(Yi(s))return!0;const i=le(t,["stop_reason","stopReason"]);if($n(i)==="completed")return!0;const r=t?Fc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||Bc(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 Yh(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 Jh(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 Pa(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function Oa(e){return e==="completed"?D.lime:e==="needs_input"?D.amber:e==="issue"?D.red:D.teal}function Zh(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 Fl(e){let t="Workstream";const s=e.allItems.map(i=>{const r=lt(i.item),a=le(r,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const c=le(r,["task_title","taskTitle","dispatch_task_title"])??Xi(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 Ul(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 eg(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 Fc(e,t){for(const s of t){const i=eg(e[s]);if(i!==null)return i}return null}function Mr(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 Uc(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Mr(e,["blocking_decision_ids","blockingDecisionIds"]),s=Mr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),i=Mr(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=Mr(c,["id","decision_id","decisionId"]),m=c.blocking!==!1;for(const p of d)r.add(p),m?t.includes(p)||t.push(p):s.includes(p)||s.push(p)}return{decisionIds:Array.from(r),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function zc(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),m=t.required_skills??t.requiredSkills,p=Array.isArray(m)?m.filter(_e=>typeof _e=="string"&&_e.trim().length>0):[],g=ug(p),y=t.task_ids??t.taskIds,h=Array.isArray(y)?y.filter(_e=>typeof _e=="string"&&_e.trim().length>0):[],I=t.milestone_ids??t.milestoneIds,b=Array.isArray(I)?I.filter(_e=>typeof _e=="string"&&_e.trim().length>0):[],k=le(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),E=le(t,["initiative_title","initiativeTitle"]),q=le(t,["initiative_status","initiativeStatus"]),w=zs(e),_=le(t,["workstream_title","workstreamTitle"]),W=le(t,["workstream_status","workstreamStatus"]),A=le(t,["task_title","taskTitle"]),P=le(t,["milestone_title","milestoneTitle"]),te=le(t,["domain"]),R=le(t,["phase","slice_phase","slicePhase"]),$=le(t,["next_step","nextStep"]),ne=Fc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),xe=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,Te=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,fe=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,je=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,ae=typeof t.error=="string"?t.error:null,ie=bn(t.artifacts??t.artifact_count??t.artifactCount),X=bn(t.decisions??t.decision_count??t.decisionCount),oe=Uc(t),Le=t.decisions_needed??t.decisionsNeeded;let Me=bn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),de=bn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((Me===null||de===null)&&Array.isArray(Le)){let _e=0,Ee=0;for(const $e of Le){if(!$e||typeof $e!="object"||Array.isArray($e))continue;$e.blocking===!1?Ee+=1:_e+=1}Me===null&&(Me=_e),de===null&&(de=Ee)}Me===null&&X!==null&&e.decisionRequired===!0&&(Me=X>0?X:1),de===null&&X!==null&&Me!==null&&(de=Math.max(0,X-Me)),Me===null&&X!==null&&de!==null&&(Me=Math.max(0,X-de));const ke=bn(t.status_updates_applied??t.statusUpdatesApplied),T=bn(t.task_updates??t.taskUpdates),z=bn(t.milestone_updates??t.milestoneUpdates),H=ke??(T!==null||z!==null?(T??0)+(z??0):null),G=bn(t.status_updates_buffered??t.statusUpdatesBuffered),we=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,De=Ms(t.token_budget??t.tokenBudget),pe=Ms(t.tokens_used??t.tokensUsed),Ie=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),M=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)??g,Ne=g&&!a.agentName?null:Ie;return{event:s,agentId:Ne,agentName:M,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:k,domain:te,phase:R,progressPct:ne,nextStep:$,requiredSkills:p,initiativeStatus:q,initiativeTitle:E,workstreamId:w,workstreamStatus:W,workstreamTitle:_,taskTitle:A,milestoneTitle:P,taskIds:h,milestoneIds:b,parsedStatus:xe,hasOutput:Te,artifacts:ie,decisions:X,blockingDecisions:Me,nonBlockingDecisions:de,decisionIds:oe.decisionIds,blockingDecisionIds:oe.blockingDecisionIds,nonBlockingDecisionIds:oe.nonBlockingDecisionIds,statusUpdatesApplied:H,statusUpdatesBuffered:G,stopReason:we,tokenBudget:De,tokensUsed:pe,logPath:fe,outputPath:je,error:ae}}function Wr(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function tg(e){const t=ho(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),m=(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),g=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,y=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,h=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,I=typeof s.provider=="string"?s.provider:null,b=typeof s.model=="string"?s.model:null,k=typeof s.domain=="string"?s.domain:null,E=s.required_skills??s.requiredSkills,q=Array.isArray(E)?E.filter(_=>typeof _=="string"&&_.trim().length>0):[];return!!l||!!(c||d||m)||!!g||!!(h||I||b||k)||q.length>0?{pluginVersion:l,skillPack:c||d||m||p?{name:c,version:d,checksum:m,source:p}:null,kickoffContextHash:g,kickoffContextSource:y,modelTier:h,provider:I,model:b,domain:k,requiredSkills:q}:null}function Wc(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 ea(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 ng(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=Wc(e);if(!i&&!s)return null;const r=le(t,["artifact_type","artifactType","atomic_unit_type"]),a=le(t,["artifact_title","title","name"]),l=le(t,["url","pr_url","commit_url"]),c=ea(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 m="";if(a)m=a;else if(i){const g=i.value;if(typeof g=="string")m=g.length>80?g.slice(0,80)+"…":g;else if(Array.isArray(g))m=`${g.length} item${g.length===1?"":"s"}`;else if(g&&typeof g=="object"){const y=Qc(g);y!=null&&y.summary?m=y.summary:(p=y==null?void 0:y.artifactsCreated[0])!=null&&p.title?m=y.artifactsCreated[0].title:y!=null&&y.updatesApplied[0]?m=y.updatesApplied[0]:m="Structured artifact details attached"}}return{label:d,preview:m,hasRegisteredId:s,title:a,typeBadge:c,url:l}}function sg(e){const t=lt(e);if(!t)return[];const s=[],i=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,r=le(t,["pr_url"])??(i?le(i,["pr_url"]):null),a=le(t,["pr_number"])??(i?le(i,["pr_number"]):null);(a||r)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:r});const l=le(t,["commit_sha"])??(i?le(i,["commit_sha"]):null),c=le(t,["commit_url"])??(i?le(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 g=d,y=typeof g.passed=="number"?g.passed:null,h=typeof g.failed=="number"?g.failed:null;if(y!==null||h!==null){const I=[];y!==null&&I.push(`${y} passed`),h!==null&&h>0&&I.push(`${h} failed`),s.push({kind:"test",label:I.join(", ")})}}const m=typeof t.task_updates=="number"?t.task_updates:i&&typeof i.task_updates=="number"?i.task_updates:null;m&&m>0&&s.push({kind:"artifact",label:`${m} task${m===1?"":"s"} updated`});const p=Array.isArray(t.artifacts)?t.artifacts:null;if(p&&p.length>0&&s.length<2){const g=p[0],y=g&&typeof g=="object"&&typeof g.title=="string"?g.title:null;s.push({kind:"doc",label:y??`${p.length} artifact${p.length===1?"":"s"}`})}return s}function aa(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 m=zt(d);if(!m)continue;const p=l==="Task"?["task_id","taskId","id"]:["milestone_id","milestoneId","id"],g=l==="Task"?["task_title","taskTitle","title","name"]:["milestone_title","milestoneTitle","title","name"],y=le(m,p),h=le(m,g)??(y&&!zn(y)?y:null)??l,I=_s(h,y)??Xe(h),b=le(m,["status","state"]),k=qt(le(m,["reason","summary","description","note"])),E=`${l}|${I.toLowerCase()}|${(b??"").toLowerCase()}|${(k??"").toLowerCase()}`;r.has(E)||(r.add(E),i.push({scope:l,label:I,status:b?Xe(b):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 ig(e){var c;const t=lt(e);if(!t)return null;const s=((c=le(t,["event","event_name","eventName"]))==null?void 0:c.toLowerCase())??"",i=aa(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 rg(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=aa(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 Hc(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 Kc(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||!Hc(d))return;const m=`${l}:${d}`;i.has(m)||(i.add(m),s.push({key:l,path:d}))},a=(l,c="",d=0)=>{if(!(d>2))for(const[m,p]of Object.entries(l)){const g=c?`${c}.${m}`:m,y=m.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 I of p)r(g,I);else r(g,p);p&&typeof p=="object"&&!Array.isArray(p)&&a(p,g,d+1)}};return a(t),s}function le(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 ag=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,og=/\b[0-9a-f]{20,}\b/gi;function Vc(e){let t=e.replace(ag,"").replace(og,"").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 lg(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=Vc(e.trim());if(!s)return null;const i=typeof t=="string"?t.trim().toLowerCase():"";if(i&&s.toLowerCase()===i||zn(s))return null;const r=Xe(s).trim();return r.length>0?r:null}function Er(e){for(const t of e){const s=_s(t.value,t.idHint);if(s)return s}return null}function cg(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 dg(e,t){if(!e)return null;const s=lt(e);if(!s)return null;const i=le(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=le(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=cg(c),m=Ms(l==null?void 0:l.current)??d.domainCurrent,p=Ms(l==null?void 0:l.max)??d.domainMax,g=d.totalCurrent,y=d.totalMax,h=typeof(l==null?void 0:l.passed)=="boolean"?l.passed:null,I=((i==null?void 0:i.includes("rate_limited"))??!1)||!!(c&&/rate limit/i.test(c))||h===!1;return!((i==null?void 0:i.includes("spawn_guard"))??!1)&&!I&&!r&&!c?null:{event:i,blockedReason:c,domain:le(s,["domain"])??le(r,["domain","task_domain"]),modelTier:le(s,["spawn_guard_model_tier","model_tier"])??le(r,["modelTier","model_tier"]),domainCurrent:m,domainMax:p,totalCurrent:g,totalMax:y,retryAt:le(s,["next_retry_at","nextRetryAt"]),retryInMs:Ms(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:I}}function ug(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 mg(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 qa(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&&mg(i)?a:i??a;if(l)return ha(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"?ha(r):Fi.test(r)||pg.test(r)||Oc.test(r)||qc.test(r)?"OrgX":ha(r)}const Fi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pg=/^[0-9a-f]{20,}$/i,fg=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function ta(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(fg)??[]){const c=l.trim().toLowerCase();Fi.test(c)&&t.add(c)}typeof e.runId=="string"&&Fi.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();Fi.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();Fi.test(d)&&t.add(d)}}return t}function hg(e){if(!e)return[];const t=lt(e);return Uc(t).decisionIds}function gg(e,t,s){if(!e)return[];const i=lt(e),r=le(i,["workstream_id","workstreamId"]),a=le(i,["initiative_id","initiativeId"]),l=ta(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 h=lt(y);if(!h)continue;const I=le(h,["workstream_id","workstreamId"]),b=le(h,["initiative_id","initiativeId"]),k=ta(y),E=l.size>0&&Array.from(l).some(P=>k.has(P)),q=!!r&&!!I&&r===I;if(!E&&!q&&!(!!a&&!!b&&a===b))continue;const _=Kc(y).filter(P=>!s.has(P.path));if(_.length===0)continue;const W=Math.abs(hs(y.timestamp)-c);if(!E&&W>7200*1e3)continue;const A=E?0:q?1:2;!E&&W>1200*1e3||d.push({priority:A,delta:W,evidence:_})}if(d.length===0)return[];d.sort((y,h)=>y.priority!==h.priority?y.priority-h.priority:y.delta-h.delta);const m=[],p=new Set(s),g=d[0].priority;for(const y of d){if(y.priority!==g)break;for(const h of y.evidence)if(!p.has(h.path)&&(p.add(h.path),m.push({key:`related.${h.key}`,path:h.path}),m.length>=8))return m}return m}function xg(e,t){if(!e)return null;const s=lt(e),i=le(s,["workstream_id","workstreamId"]),r=le(s,["initiative_id","initiativeId"]),a=ta(e);if(!i&&!r&&a.size===0)return null;const l=hs(e.timestamp),c=[];for(const m of t){if(m.id===e.id)continue;const p=zc(m);if(!p)continue;const g=lt(m);if(!g)continue;const y=le(g,["workstream_id","workstreamId"]),h=le(g,["initiative_id","initiativeId"]),I=ta(m),b=a.size>0&&Array.from(a).some(W=>I.has(W)),k=!!i&&!!y&&i===y;if(!b&&!k&&!(!!r&&!!h&&r===h))continue;const q=Math.abs(hs(m.timestamp)-l);if(!b&&q>1200*1e3)continue;const w=b?"shared_id":k?"workstream":"initiative",_=w==="shared_id"?0:w==="workstream"?1:2;c.push({priority:_,delta:q,relation:w,detail:p})}if(c.length===0)return null;c.sort((m,p)=>m.priority!==p.priority?m.priority-p.priority:m.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 Yi(e){const t=$n(e);return["done","complete","completed","stopped","success"].includes(t)}function yg(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":Yi(t)||e.stopReason==="completed"?"positive":"neutral"}function bg(e){if(Yi(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 Gc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function vg(e,t){if(!e&&t===null)return null;const s=e?yg(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=Gc(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=bg(e);if(a===null)return null;const l=i(a);return{pct:a,source:"lifecycle",label:l?r:"Progress",tone:s,terminalStop:l}}function wg(e,t,s,i=null){var E;const r=lt(e),a=$n(le(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)),m=le(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),g=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-g)),h=e.decisionRequired===!0||e.type==="decision_requested"||g>0||c==="needs_decision"&&y===0,I=e.type==="run_completed"||e.type==="milestone_completed"||Yi(c)||d==="completed",b=a.includes("spawn_guard_rate_limited")||!!(m&&/rate limit/i.test(m)),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 q=typeof(r==null?void 0:r.tasks_completed)=="number"?r.tasks_completed:null;return{label:"All done",summary:q?`All queued work complete — ${q} task${q===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:h?"Needs decision":"Blocked",summary:qt(e.title)??(h?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:h?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:h?"warning":"critical"};if(d==="error")return{label:"Error",summary:qt(e.title)??m??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const q=String((r==null?void 0:r.new_state)??"");return q==="running"?{label:"Resumed",summary:"Resumed — dispatching work",hint:"Autopilot is actively working through the queue.",tone:"positive"}:q==="blocked"||q==="error"?{label:"Paused",summary:"Paused — waiting for input",hint:"Review blockers and resolve to continue.",tone:"critical"}:null}if(b)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:m?qt(m)??"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:m?qt(m)??i.sentence:i.sentence,hint:i.nextAction,tone:"critical"};if(i.status==="needs_attention"){const q=h||(((E=i.nextAction)==null?void 0:E.toLowerCase().includes("decision"))??!1);return{label:q?"Needs decision":"Needs attention",summary:i.sentence,hint:i.nextAction??(q?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:q?"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:h?"Waiting on you":"Blocked",summary:m?qt(m)??"Execution is blocked.":h?"Blocked waiting on decision from you":"Paused after top queue item blocked",hint:h?"Resolve the pending decision in the Decisions panel to continue.":"Review blocker details, then retry or skip to continue.",tone:"critical"}:h?{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"}:I&&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"}:I?{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 Xc(e){if(typeof e=="string")return n.jsx(zi,{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:Xc(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Ig(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 kg(e){if(!e)return null;const t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^file:\/\//i.test(t)||!Hc(t)?null:Wr(t):null}function Qc(e){const t=zt(e);if(!t)return null;const s=zt(t.result),i=zt(t.outcomes),r=[s,i,t].filter(R=>!!R),a=R=>{for(const $ of r)for(const ne of R){if(!(ne in $))continue;const xe=$[ne];if(xe!=null)return xe}return null},l=R=>{for(const $ of r){const ne=le($,R);if(ne)return ne}return null},c=qt(l(["summary","user_summary","description","message"])),d=[],m=new Set,p=R=>{if(!R)return;const $=R.trim();if(!$)return;const ne=$.toLowerCase();m.has(ne)||(m.add(ne),d.push($))},g=(R,$)=>{if(Array.isArray(R))for(const ne of R){const xe=zt(ne);if(!xe)continue;const Te=le(xe,[`${$.toLowerCase()}_id`,`${$.toLowerCase()}Id`,"id"]),fe=le(xe,[`${$.toLowerCase()}_title`,`${$.toLowerCase()}Title`,"title","name"])??(Te&&!zn(Te)?Te:null),je=le(xe,["status","state"]),ae=qt(le(xe,["reason","summary","description","note"])),ie=fe?_s(fe,Te)??Xe(fe):$,X=je?Xe(je):null,oe=[ie];X&&oe.push(`→ ${X}`),ae&&oe.push(`· ${ae}`),p(oe.join(" "))}};for(const R of r)g(R.task_updates??R.taskUpdates,"Task"),g(R.milestone_updates??R.milestoneUpdates,"Milestone");const y=bn(a(["status_updates_applied","statusUpdatesApplied"]));y!==null&&y>0&&p(`${y} status update${y===1?"":"s"} applied`);const h=a(["status_updates_buffered","statusUpdatesBuffered"]),I=bn(h);(h===!0||I!==null&&I>0)&&p("Status updates buffered for sync");const k=[],E=new Set,q=R=>{const $=qt(R);if(!$)return;const ne=$.toLowerCase();E.has(ne)||(E.add(ne),k.push($))};q(l(["next_step","nextStep"]));for(const R of r){const $=R.next_actions??R.nextActions;if(Array.isArray($))for(const ne of $)typeof ne=="string"&&q(ne)}const w=[],_=new Set,W=(R,$,ne)=>{const xe=`${R.toLowerCase()}|${($??"").toLowerCase()}|${ne??""}`;_.has(xe)||(_.add(xe),w.push({title:R,type:$,url:ne}))},A=R=>{const $=Array.isArray(R)?R:R?[R]:[];for(const ne of $){const xe=zt(ne);if(!xe){if(typeof ne=="string"&&ne.trim().length>0){const ae=qt(ne)??Xe(ne);ae&&W(ae,null,null)}continue}const Te=le(xe,["artifact_type","artifactType","type"]),fe=le(xe,["url","source_pointer","sourcePointer","path"]),je=le(xe,["name","title","artifact_title","artifactTitle"])??(fe?Un(fe):ea(Te));W(Xe(je),Te,fe)}};for(const R of r)A(R.artifacts??R.artifact);const P=l(["artifact_type","artifactType"]),te=l(["url","artifact_url","artifactUrl"]);if(w.length===0&&(P||te)){const R=te?Un(te):ea(P);W(Xe(R),P,te)}return!c&&d.length===0&&w.length===0&&k.length===0?null:{summary:c,updatesApplied:d,artifactsCreated:w,nextUp:k}}function Ig(e){const t=Qc(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=kg(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:ea(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:Un(s.url)})}):n.jsx("p",{className:"mt-1 truncate text-micro text-secondary",children:Un(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=Hi(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:Xe(t)}const Ng=[/^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],jg=[/^User:\s*Read /i,/Read HEARTBEAT\.md/i,/Follow it strictly/i,/reply HEARTBEAT_OK/i,/Current time:/i,/workspace context/i];function Ag(e){return Ng.some(t=>t.test(e))}function _g(e){if(!e)return!1;const t=e.trim();return t?jg.some(s=>s.test(t)):!1}function Rr(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s&&!_g(s)&&!(s==="System event"||s==="Untitled session"))return s}return null}function Yc(e){const t=lt(e);if(!t)return null;const s=le(t,["user_summary","userSummary"]);if(s)return s;const i=le(t,["task_title","taskTitle","dispatch_task_title"])??le(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),r=le(t,["event","event_name","eventName"]),a=le(t,["parsed_status","status"]),l=le(t,["stop_reason","stopReason"]),c=le(t,["artifact_type","artifactType"]),d=le(t,["artifact_title","title","name"]),m=le(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=aa(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"&&m&&i)return`${m} is handling ${i}`;if(r==="decision_needed"||r==="question_asked"||r==="review_item_created"){const p=le(t,["decision_title","decisionTitle","decision_prompt","decisionPrompt","question","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(r==="decision_resolved"){const p=le(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 Sg(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 Xi(e){const t=Yc(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";if(!Ag(s)){const i=lg(Xe(Vc(s)));if(i&&i!=="Untitled session")return{title:i,isSystem:!1};const r=e.metadata,a=Nd(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 Cg=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),Tg=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 Wi(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,m=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&Tg.has(s)||l||c&&(d||m)||d&&(m||r.includes("outbox")||r.includes("replay"))||r.includes("outbox_replay")&&m)}function zl(e){var d;if(!e||!Wi(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=le(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 Ba(e){if(!Wi(e))return null;const t=lt(e);if(!t)return null;const s=le(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const i=le(t,["event","event_name","eventName"])??"",r=le(t,["changeset_id","changesetId"])??"",a=le(t,["entity_type","entityType"])??"",l=le(t,["entity_id","entityId"])??"",c=hi(e)??"",d=Xi(e).title.trim().toLowerCase();return`fallback:${i.toLowerCase()}:${r.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function Mg(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 Wl(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 Eg=[/^Autopilot dispatched slice for\s*/i,/^Orchestrator (selected|dispatched)\s*/i,/^Auto[-_]?continue.*?dispatching\s*/i,/^Slice (started|dispatched) for\s*/i];function Hl(e,t){const s=Yc(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 Eg)r=r.replace(c,"");r=r.trim();const a=r.split(`
|
|
211
|
+
`).map(c=>Wl(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let l=a[0]??Wl(r);return l.length<24&&a.length>1&&(l=`${l} ${a[1]}`.trim()),l.length>108?`${l.slice(0,107).trimEnd()}…`:l}const Rg=o.memo(function({activity:t,sessions:s,sliceRuns:i=[],initiatives:r=[],timelineNarrative:a=[],selectedRunIds:l,selectedSessionLabel:c=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:m=null,agentFilter:p=null,timeFilterId:g="live",onTimeFilterChange:y,customTimeRange:h={startIso:null,endIso:null},onCustomTimeRangeChange:I,hasMore:b=!1,isLoadingMore:k=!1,onLoadMore:E,onClearSelection:q,onClearWorkstreamFilter:w,onClearAgentFilter:_,onFocusRunId:W,onOpenDecision:A,onResolveDecision:P,requestedActivityItemId:te=null,onActivityItemRequestHandled:R,onPlayNextUp:$,onStartAutopilot:ne,onPauseWorkstream:xe,onCreateInitiative:Te,onOpenMissionControl:fe,onOpenSettings:je,workspaceId:ae=null,chatSnapshot:ie,onRefreshData:X,isLoading:oe=!1,onOpenNextUp:Le,devMode:Me=!1,nextUpQueue:de,autopilotState:ke=null}){var C;const T=xs(),{open:z}=Cc(),H=o.useMemo(()=>{if(!de)return new Map;const u=new Map;for(let x=0;x<de.length;x++){const v=de[x];u.set(v.workstreamId,{rank:x+1,title:v.workstreamTitle,state:v.queueState})}return u},[de]),[G,we]=o.useState("all"),[De,pe]=o.useState(!1),[Ie,M]=o.useState(""),[Ne,_e]=o.useState(new Set),[Ee,$e]=o.useState({}),[ge,mt]=o.useState("oldest"),[Se,Ae]=o.useState(!1),[J,dt]=o.useState(!1),[yt,Fe]=o.useState(Da),[Z,B]=o.useState(null),[se,ue]=o.useState(null),[Pe,We]=o.useState(!1),[rt,he]=o.useState(1),[Ve,re]=o.useState("structured"),[K,Ce]=o.useState(null),[Ze,at]=o.useState("feed"),[pt,ct]=o.useState(null),[ht,rn]=o.useState(null),[Y,ye]=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()),Ct=o.useRef(null),Ut=o.useRef(null),nt=o.useRef(null),et=o.useRef(null),$t=o.useRef(null),[_t,Tt]=o.useState(()=>_r(h.startIso)),[St,Kt]=o.useState(()=>_r(h.endIso)),[vn,ys]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Hn=o.useMemo(()=>cc(g),[g]),Kn=o.useMemo(()=>_r(h.startIso),[h.startIso]),Vn=o.useMemo(()=>_r(h.endIso),[h.endIso]),Gn=o.useMemo(()=>!_t||!St?!1:St.getTime()>=_t.getTime(),[St,_t]),Es=o.useMemo(()=>g!=="custom"?Hn.label:Kn&&Vn?`${Sr(Kn)} - ${Sr(Vn)}`:"Custom range",[Vn,Kn,g,Hn.label]);o.useEffect(()=>{Tt(Kn),Kt(Vn)},[Vn,Kn]),o.useEffect(()=>{if(typeof window>"u")return;const u=()=>ys(window.innerWidth<=640);return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[]),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 u=s.filter(N=>N.status==="completed").length,x=s.filter(N=>N.status==="blocked"||N.status==="failed").length,v=t.filter(N=>{var S;return N.type==="decision_requested"&&((S=N.metadata)==null?void 0:S.status)==="pending"}).length;return{completed:u,blocked:x,decisions:v}},[s,t]),Qt=o.useMemo(()=>{const u=new Map;for(const x of s)u.set(x.runId,x.title),u.set(x.id,x.title);return u},[s]),an=o.useMemo(()=>{const u=new Map;for(const x of s)x.status&&(u.set(x.runId,x.status),u.set(x.id,x.status));return u},[s]),hn=o.useRef(new Map),Rs=o.useMemo(()=>{var x;const u=new Map;for(const v of s){const N={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};u.set(v.runId,N),u.set(v.id,N)}return Rl(hn.current,u)?hn.current:(hn.current=u,u)},[s]),Xn=o.useRef(new Map),bs=o.useMemo(()=>{const u=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)},N=[x.runId,x.sliceRunId].filter(S=>typeof S=="string"&&S.trim().length>0).map(S=>S.trim());for(const S of N){const V=u.get(S);(!V||v.updatedEpoch>=V.updatedEpoch)&&u.set(S,v)}}return Rl(Xn.current,u)?Xn.current:(Xn.current=u,u)},[i]),ti=o.useMemo(()=>{const u=new Map;for(const x of i){const v={startedAt:x.startedAt??null,completedAt:x.completedAt??null},N=[x.runId,x.sliceRunId].filter(S=>typeof S=="string"&&S.trim().length>0);for(const S of N)u.set(S,v)}return u},[i]),Ls=o.useMemo(()=>{const u=new Map;for(const x of s){const v=Gc(x.progress);v!==null&&(u.set(x.runId,v),u.set(x.id,v))}return u},[s]),Vt=o.useMemo(()=>{const u=new Map;for(const x of s)!x.agentId||!x.agentName||u.set(x.agentId,x.agentName);return u},[s]),Cn=o.useMemo(()=>{const u=new Map;for(const x of s){const v=x.workstreamId??null;u.set(x.runId,v),u.set(x.id,v)}return u},[s]),Qn=o.useMemo(()=>{const u=new Map;for(const x of i){const v=x.workstreamId??null,N=_s(x.workstreamTitle,v);if(!N)continue;const S=[x.runId,x.sliceRunId].filter(V=>typeof V=="string"&&V.trim().length>0).map(V=>V.trim());for(const V of S)u.set(V,N)}return u},[i]),U=o.useMemo(()=>{const u=new Map;for(const x of r){const v=_s(x.name,x.id);v&&u.set(x.id,v)}return u},[r]),be=o.useMemo(()=>{const u=new Map;for(const x of r)for(const v of x.workstreams??[]){const N=_s(v.name,v.id);N&&u.set(v.id,N)}for(const x of i){const v=x.workstreamId??null;if(!v||u.has(v))continue;const N=_s(x.workstreamTitle,v);N&&u.set(v,N)}return u},[r,i]);o.useMemo(()=>{const u=[...s];return u.sort((x,v)=>{const N=hs(x.updatedAt??x.lastEventAt??x.startedAt??null);return hs(v.updatedAt??v.lastEventAt??v.startedAt??null)-N}),u},[s]);const ve=o.useMemo(()=>t.map(u=>{const x=hi(u),v=Xh(u),N=lt(u),S=x?Rs.get(x)??null:null,V=x?bs.get(x)??null:null,Q=Qh(u,N),ze=zf({sessionStatus:Q?null:(S==null?void 0:S.status)??(x?an.get(x)??null:null),sessionPhase:Q?null:(S==null?void 0:S.phase)??null,sessionState:Q?null:(S==null?void 0:S.state)??null,sliceStatus:Q?null:(V==null?void 0:V.status)??null,activityType:u.type,activityStatus:le(N,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:le(N,["stop_reason","stopReason"]),decisionRequired:u.decisionRequired??!1,blockingDecisionCount:Ys(N,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(V==null?void 0:V.blockingDecisions)??0,nonBlockingDecisionCount:Ys(N,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(V==null?void 0:V.nonBlockingDecisions)??0,blockerCount:Q?0:(S==null?void 0:S.blockerCount)??0,blockerReason:Q?null:(S==null?void 0:S.blockerReason)??null}),qe=Zh(v,ze),it=[u.title,u.description,u.summary,u.agentName,Ph(N)].filter(tt=>typeof tt=="string"&&tt.length>0).join(" ").toLowerCase(),Ke=x?(Qt.get(x)??x).toLowerCase():"",Ye=N==null?void 0:N.scope,ot=Ye==="milestone"||Ye==="workstream"?Ye:void 0;return{item:u,bucket:v,userState:qe.state,userStateWhy:qe.why,canonicalProjection:ze,runId:x,timestampEpoch:hs(u.timestamp),searchText:it,runLabelSearch:Ke,scopeGroupId:ot?x??null:null,scope:ot}}),[t,Qt,Rs,an,bs]),Be=o.useMemo(()=>{const u=[...ve];u.sort((N,S)=>{const V=S.timestampEpoch-N.timestampEpoch;return V!==0?V:S.item.id.localeCompare(N.item.id)});const x=N=>{const S=new Map,V=new Map,Q=new Map,ze=new Map;for(const qe of N){jr(S,qe.runId,qe),jr(ze,qe.userState,qe);const it=zs(qe.item)??(qe.runId?Cn.get(qe.runId)??null:null);jr(V,it,qe);const Ke=Gs(qe.item).agentName;jr(Q,Ke,qe)}return{all:N,byRunId:S,byWorkstreamId:V,byAgentName:Q,byUserState:ze}},v=[...u].reverse();return{newest:x(u),oldest:x(v)}},[ve,Cn]),wt=o.useMemo(()=>{let u=0;for(const x of ve)u=Math.max(u,x.timestampEpoch);return u<=0?!1:Date.now()-u<6e4},[ve]),Nt=o.useMemo(()=>new Set(l.filter(u=>u&&u.trim().length>0)),[l]),st=Nt.size>0,Yt=o.useMemo(()=>Ki.filter(u=>["live","24h","7d","all"].includes(u.id)),[]),jt=o.useMemo(()=>{if(!st)return null;for(const u of Nt){const x=s.find(v=>v.runId===u||v.id===u);if(x)return x}return null},[st,Nt,s]),Yn=o.useMemo(()=>st?jt!=null&&jt.runtimeProvider?{id:$h(jt.runtimeProvider)}:Cs(jt==null?void 0:jt.agentId,jt==null?void 0:jt.agentName,jt==null?void 0:jt.title,jt==null?void 0:jt.lastEventSummary,jt==null?void 0:jt.runtimeClient,c):Cs(),[jt,st,c]),Jn=o.useMemo(()=>p?Cs(p):Cs(),[p]),{filtered:Mt,filteredTotal:dn,hiddenCount:as,hiddenSyncCount:Zn}=o.useMemo(()=>{const u=ge==="newest"?Be.newest:Be.oldest,x=[];st&&x.push(Dh(u.byRunId,Nt)),d&&x.push(u.byWorkstreamId.get(d)??[]),p&&x.push(u.byAgentName.get(p)??[]),G==="completed"?x.push(u.byUserState.get("completed")??[]):G==="in_progress"?x.push(u.byUserState.get("in_progress")??[]):G==="needs_attention"&&x.push([...u.byUserState.get("needs_input")??[],...u.byUserState.get("issue")??[]]);const v=x.length>0?[...x].sort((ot,tt)=>ot.length-tt.length)[0]:u.all,N=[];let S=0,V=0,Q=0;const ze=new Set,qe=Ie.trim().toLowerCase();for(const ot of v){const tt=ot.runId;if(st&&(!tt||!Nt.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){Q++;continue}if(!Me){const Rn=lt(ot.item),tn=le(Rn,["event","event_name","eventName"]);if(tn&&Cg.has(tn))continue}const cn=Ba(ot.item);if(cn){if(ze.has(cn)){V+=1;continue}if(ze.add(cn),!De){V+=1;continue}}else if(!De&&Wi(ot.item)){V+=1;continue}G==="completed"&&ot.userState!=="completed"||G==="needs_attention"&&ot.userState!=="needs_input"&&ot.userState!=="issue"||G==="in_progress"&&ot.userState!=="in_progress"||qe.length>0&&!`${ot.searchText} ${ot.runLabelSearch}`.includes(qe)||(N.length<Tl?N.push(ot):S+=1)}const it=Math.min(Math.max(1,Math.min(Cl,yt)),N.length),Ke=N.slice(0,it),Ye=N.length+S;return{filtered:Ke,filteredTotal:Ye,hiddenCount:Math.max(0,Ye-Ke.length),hiddenSyncCount:V,skippedByAgent:Q}},[G,p,Be,st,Ie,yt,d,Nt,Cn,De,ge]),Ds=o.useMemo(()=>{if(!p)return null;let u=0;for(const x of t)if(Gs(x).agentName===p){const N=hs(x.timestamp);N>u&&(u=N)}return u===0?null:Rt(u)},[p,t]),$s=o.useMemo(()=>{const u=new Map;for(const v of Mt){const N=Yh(v.item.timestamp),S=u.get(N);S?S.push(v):u.set(N,[v])}return Array.from(u.keys()).sort((v,N)=>{const S=Number(N)-Number(v);return ge==="newest"?S:-S}).map(v=>({key:v,label:Jh(v),items:u.get(v)??[]}))},[Mt,ge]),os=o.useMemo(()=>$s.map(u=>{const x=new Map;for(const v of u.items){const N=Xi(v.item).title.trim().toLowerCase(),S=Ba(v.item),V=lt(v.item),Q=le(V,["event","event_name","eventName"]),ze=(Q==null?void 0:Q.startsWith("autopilot_"))||(Q==null?void 0:Q.startsWith("auto_continue_")),qe=typeof Q=="string"&&/(transition|started|stopped|completed|blocked|paused|resumed|failed|decision|dispatch)/i.test(Q),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}::${N}`,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{...u,clusters:Array.from(x.values())}}),[$s]),kn=o.useCallback(u=>{_e(x=>{const v=new Set(x);return v.has(u)?v.delete(u):v.add(u),v}),$e(x=>{if(Object.prototype.hasOwnProperty.call(x,u)){const v={...x};return delete v[u],v}return{...x,[u]:Oi}})},[]),Ji=o.useCallback((u,x)=>{$e(v=>{const N=v[u]??Oi,S=Math.min(x,N+Oi);return S===N?v:{...v,[u]:S}})},[]),ls=o.useCallback(()=>{!I||!y||!_t||!St||St.getTime()<_t.getTime()||(I({startIso:_t.toISOString(),endIso:St.toISOString()}),y("custom"),dt(!1))},[St,_t,I,y]),oa=o.useCallback(()=>{Tt(null),Kt(null),I==null||I({startIso:null,endIso:null}),g==="custom"&&(y==null||y("live"))},[I,y,g]),Pt=o.useMemo(()=>Math.min(Cl,Math.min(Tl,dn)),[dn]);o.useEffect(()=>{Fe(Da),_e(new Set),$e({})},[G,p,st,Ie,d,De,ge,g]),o.useEffect(()=>{if(!Se)return;const u=v=>{var S;const N=v.target;N instanceof Node&&((S=Ct.current)!=null&&S.contains(N)||Ae(!1))},x=v=>{v.key==="Escape"&&Ae(!1)};return window.addEventListener("pointerdown",u),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",u),window.removeEventListener("keydown",x)}},[Se]),o.useEffect(()=>{if(!J)return;const u=v=>{var S;const N=v.target;N instanceof Node&&((S=Ut.current)!=null&&S.contains(N)||dt(!1))},x=v=>{v.key==="Escape"&&dt(!1)};return window.addEventListener("pointerdown",u),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",u),window.removeEventListener("keydown",x)}},[J]);const Pn=o.useRef(E);Pn.current=E;const ni=o.useRef(b);ni.current=b;const ki=o.useRef(k);ki.current=k;const[es,la]=o.useState(!1),vs=o.useRef(null),on=o.useRef(g),Zi=o.useRef(Date.now()),Ps=o.useRef(!1);o.useEffect(()=>{on.current!==g&&(on.current=g,vs.current=null,Zi.current=Date.now(),Ps.current=!1)},[g]),o.useEffect(()=>{const u=nt.current,x=et.current;if(!u||!x)return;const v=new IntersectionObserver(S=>{const V=S.some(Q=>Q.isIntersecting);la(V)},{root:u,rootMargin:"0px 0px 600px 0px"});v.observe(x);const N=()=>{Ps.current=!0};return u.addEventListener("scroll",N,{passive:!0}),()=>{v.disconnect(),u.removeEventListener("scroll",N)}},[]),o.useEffect(()=>{var u;if(es){if(Mt.length<Pt){Fe(x=>Math.min(Pt,Math.max(x,Da)+Rh));return}if(ni.current&&!ki.current){(u=Pn.current)==null||u.call(Pn);return}}},[Mt.length,Pt,es]),o.useEffect(()=>{if(!es||b||k||!y)return;const u=nt.current,x=u?u.scrollHeight<=u.clientHeight+4:!1;if(!Ps.current&&!x||Date.now()-Zi.current<3e3)return;const N=El(g);N&&vs.current!==N&&(vs.current=N,y(N))},[Mt.length,b,k,y,es,g]);const un=o.useMemo(()=>Z?Mt.findIndex(u=>u.item.id===Z):-1,[Z,Mt]),L=un>=0?Mt[un]:null,er=o.useMemo(()=>{var x;const u=new Map;for(const v of a){const N=(x=v==null?void 0:v.sliceRunId)==null?void 0:x.trim();!N||u.has(N)||u.set(N,v)}return u},[a]),cs=o.useMemo(()=>{if(!L)return null;const u=L.runId??hi(L.item);return u?er.get(u)??null:null},[L,er]),mn=o.useMemo(()=>Wc((L==null?void 0:L.item)??null),[L]),On=o.useMemo(()=>Cr((L==null?void 0:L.item)??null),[L]),Os=o.useMemo(()=>zc((L==null?void 0:L.item)??null),[L]),ds=o.useMemo(()=>Os?null:xg((L==null?void 0:L.item)??null,t),[Os,L,t]),Qe=o.useMemo(()=>L?Ol(L.item):null,[L]),pn=o.useMemo(()=>Qe?Qe.executor??Qe.requester:null,[Qe]),ee=Os??(ds==null?void 0:ds.detail)??null,si=o.useMemo(()=>{var u,x;return qa((ee==null?void 0:ee.requesterAgentName)??((u=Qe==null?void 0:Qe.requester)==null?void 0:u.name)??null,(ee==null?void 0:ee.requesterAgentId)??((x=Qe==null?void 0:Qe.requester)==null?void 0:x.id)??null,Vt)},[ee,Qe,Vt]),ws=o.useMemo(()=>Fh(si),[si]),In=o.useMemo(()=>{var x,v;const u=qa((ee==null?void 0:ee.agentName)??((x=Qe==null?void 0:Qe.executor)==null?void 0:x.name)??null,(ee==null?void 0:ee.agentId)??((v=Qe==null?void 0:Qe.executor)==null?void 0:v.id)??null,Vt);return u==="—"?(Qe==null?void 0:Qe.primaryLabel)??"Codex":u},[ee,Qe,Vt]),Ii=o.useMemo(()=>L!=null&&L.runId?Ls.get(L.runId)??null:null,[L,Ls]),Bt=o.useMemo(()=>vg(ee,Ii),[ee,Ii]),F=o.useMemo(()=>{const u=ee;if(!u)return null;const x=u.initiativeId??(L==null?void 0:L.item.initiativeId)??null,v=x?r.find(tt=>tt.id===x)??null:null,N=u.initiativeTitle??(v==null?void 0:v.name)??null,S=u.initiativeStatus??(v==null?void 0:v.status)??null,V=(v==null?void 0:v.workstreams)??[],Q=V.length>0?V.length:null,ze=Q!==null?V.filter(tt=>Yi(tt.status)).length:null,qe=Q&&ze!==null?Math.round(ze/Q*100):null,it=u.workstreamId??null,Ke=it&&V.length>0?V.find(tt=>tt.id===it)??null:null,Ye=u.workstreamTitle??(Ke==null?void 0:Ke.name)??(it?be.get(it)??null:null),ot=u.workstreamStatus??(Ke==null?void 0:Ke.status)??null;return{initiativeId:x,initiativeTitle:N,initiativeStatus:S,totalInitiativeWorkstreams:Q,doneInitiativeWorkstreams:ze,initiativeWorkstreamPct:qe,workstreamId:it,workstreamTitle:Ye,workstreamStatus:ot,taskTitle:u.taskTitle,milestoneTitle:u.milestoneTitle,scopedTaskCount:u.taskIds.length,scopedMilestoneCount:u.milestoneIds.length,statusUpdatesApplied:u.statusUpdatesApplied,statusUpdatesBuffered:u.statusUpdatesBuffered,artifacts:u.artifacts,decisions:u.decisions,blockingDecisions:u.blockingDecisions,nonBlockingDecisions:u.nonBlockingDecisions,tokensUsed:u.tokensUsed,tokenBudget:u.tokenBudget,nextStep:u.nextStep,phase:u.phase,stopReason:u.stopReason,parsedStatus:u.parsedStatus}},[ee,L,r,be]),At=o.useMemo(()=>L?wg(L.item,ee,F?{decisions:F.decisions,blockingDecisions:F.blockingDecisions,nonBlockingDecisions:F.nonBlockingDecisions,stopReason:F.stopReason,parsedStatus:F.parsedStatus}:null,L.canonicalProjection??null):null,[ee,L,F]),Ft=o.useMemo(()=>{if(!L)return new Set;if(Me)return new Set(["header","artifact","outcome","structured_outcomes","action_needed","session","scope","summary","evidence"]);const u=le(lt(L.item),["event","event_name","eventName"])??"";return Sg(u,!!mn||!!Cr(L.item),!!At,rg(L.item))},[L,mn,At,Me]),us=o.useMemo(()=>{if(!F)return[];const u=[];At&&u.push({label:"Status",value:At.label}),F.scopedTaskCount>0&&u.push({label:"Tasks",value:F.scopedTaskCount}),F.scopedMilestoneCount>0&&u.push({label:"Milestones",value:F.scopedMilestoneCount});const x=F.artifacts??0;x>0&&u.push({label:"Artifacts",value:x});const v=F.decisions??0;v>0&&u.push({label:"Decisions",value:v}),F.blockingDecisions&&F.blockingDecisions>0&&u.push({label:"Blocking",value:F.blockingDecisions,tone:"critical"}),F.stopReason&&u.push({label:"Stop reason",value:pi(F.stopReason)??Xe(F.stopReason)});const N=Id(F.tokensUsed,F.tokenBudget);return N&&u.push({label:"Token usage",value:N}),u},[F,At]),Jt=o.useMemo(()=>{const u=new Set;for(const x of hg((L==null?void 0:L.item)??null))u.add(x);for(const x of(ee==null?void 0:ee.decisionIds)??[])u.add(x);for(const x of(ee==null?void 0:ee.blockingDecisionIds)??[])u.add(x);for(const x of(ee==null?void 0:ee.nonBlockingDecisionIds)??[])u.add(x);return Array.from(u)},[ee,L]),tr=o.useMemo(()=>A?Jt.length>0||(L==null?void 0:L.item.decisionRequired)===!0||((F==null?void 0:F.blockingDecisions)??0)>0?!0:(At==null?void 0:At.label)==="Needs decision":!1,[Jt,L,F,At,A]),gn=o.useMemo(()=>{if(!L)return null;const u=hi(L.item);return u?i.find(x=>x.runId===u||x.sliceRunId===u)??null:null},[L,i]),ca=o.useMemo(()=>(gn==null?void 0:gn.decisionOptions)??[],[gn]),nr=o.useMemo(()=>(gn==null?void 0:gn.pendingDecisions)??[],[gn]),ts=o.useMemo(()=>(gn==null?void 0:gn.blockers)??[],[gn]),sr=o.useMemo(()=>Bt?Bt.tone==="positive"?D.lime:Bt.tone==="warning"?D.amber:Bt.tone==="critical"?D.red:D.teal:D.teal,[Bt]),ms=(Bt==null?void 0:Bt.terminalStop)===!0,ut=o.useMemo(()=>tg(lt((L==null?void 0:L.item)??null)),[L]),qs=o.useMemo(()=>lt((L==null?void 0:L.item)??null),[L]),kt=o.useMemo(()=>dg((L==null?void 0:L.item)??null,ee),[ee,L]),ks=o.useMemo(()=>{if(!(kt!=null&&kt.retryAt))return null;const u=new Date(kt.retryAt);if(!Number.isFinite(u.getTime()))return null;const x=u.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),v=Rt(kt.retryAt);return v?`${x} (${v})`:x},[kt]),Ni=o.useMemo(()=>L?Gs(L.item):{agentId:null,agentName:null},[L]),ji=o.useMemo(()=>Ul(zt(L==null?void 0:L.item.metadata)??void 0),[L]),ir=o.useMemo(()=>{var v;if(!L)return[];const u=hi(L.item);if(u){const N=i.find(S=>S.runId===u||S.sliceRunId===u);if((v=N==null?void 0:N.scopeProgress)!=null&&v.milestones)return N.scopeProgress.milestones.map(S=>({id:S.id,title:S.title,tasks:[],totalTasks:S.total,doneTasks:S.done}))}const x=le(lt(L.item),["workstream_id","workstreamId"]);if(x&&de){const N=de.find(S=>S.workstreamId===x);if(N!=null&&N.milestoneBreakdown)return N.milestoneBreakdown}return[]},[L,i,de]);o.useMemo(()=>Ul(qs),[qs]);const xn=o.useMemo(()=>{const u=Kc((L==null?void 0:L.item)??null);return u.length>0?u:gg((L==null?void 0:L.item)??null,t,new Set)},[L,t]),Tn=o.useMemo(()=>xn.filter((u,x,v)=>v.findIndex(N=>N.path===u.path)===x),[xn]),da=o.useMemo(()=>Tn.slice(0,4),[Tn]),rr=o.useMemo(()=>Tn.slice(4),[Tn]),ar=o.useMemo(()=>{if(Tn.length===0)return null;const u=Tn[0];return u?Wr(u.path):null},[Tn]),Ai=o.useMemo(()=>{var N;const u=qt(K);if(u)return u;const x=zl((L==null?void 0:L.item)??null);if(x)return x;const v=qt(L==null?void 0:L.item.summary)??qt(L==null?void 0:L.item.description);if(v)return v;if(L){const S=L.item,V=lt(S),Q=le(V,["agent_name","agentName"])??S.agentName??"OrgX",ze=le(V,["task_title","taskTitle","workstream_title","workstreamTitle"]),qe=((N=S.type)==null?void 0:N.replace(/_/g," "))??"activity";return ze?`${Q} worked on ${ze}`:`${Q} recorded a ${qe}`}return null},[K,L]),or=o.useMemo(()=>L?Wi(L.item):!1,[L]),ln=o.useMemo(()=>{if(!ee||!L)return null;const u=ee.initiativeId??L.item.initiativeId??null,x=ee.workstreamId??zs(L.item);if(!u||!x)return null;const v=$n((F==null?void 0:F.parsedStatus)??ee.parsedStatus),N=$n((F==null?void 0:F.stopReason)??ee.stopReason),S=Math.max(0,(F==null?void 0:F.blockingDecisions)??ee.blockingDecisions??(L.item.decisionRequired?1:0)),V=Math.max(0,(F==null?void 0:F.nonBlockingDecisions)??ee.nonBlockingDecisions??0),Q=v==="blocked"||v==="error"||v==="failed"||N==="blocked"||N==="error"||L.item.type==="blocker_created",ze=!Q&&S===0&&V>0&&(v==="needs_decision"||v==="completed"||N==="completed");return!Q&&!ze?null:{initiativeId:u,workstreamId:x,runId:L.runId??null,event:ee.event,requestedByAgentId:ee.requesterAgentId??L.item.requesterAgentId??null,requestedByAgentName:ee.requesterAgentName??L.item.requesterAgentName??null,actionLabel:Q?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Q?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Q}},[ee,L,F]),Mn=o.useCallback(()=>{B(null)},[]),ii=o.useCallback(async(u,x)=>{if(x){Ge(null),ye(u);try{await x()}catch(v){Ge(v instanceof Error?v.message:"Action failed")}finally{ye(v=>v===u?null:v)}}},[]),ri=o.useCallback(async()=>{var u;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 N=(u=v==null?void 0:v.scheduled)!=null&&u.dueAt?new Date(v.scheduled.dueAt):null,S=N&&Number.isFinite(N.getTime())?N.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(!se)return;const u=window.setTimeout(()=>ue(null),2e3);return()=>window.clearTimeout(u)},[se]),o.useEffect(()=>{Ge(null)},[G,Ie,g]),o.useEffect(()=>{if(!te){$t.current=null;return}const u=te.trim();!u||$t.current===u||!t.some(v=>v.id===u)||($t.current=u,we("all"),M(""),he(1),B(u),R==null||R(u))},[t,R,te]);const En=o.useCallback(async(u,x)=>{if(x)try{await navigator.clipboard.writeText(x),ue(`${u} copied`)}catch{ue("Copy failed")}},[]);o.useEffect(()=>{re("structured"),We(!1),He(!1),ft(null)},[Z]),o.useEffect(()=>{Ce(null),at("feed"),ct(null),rn(null);const u=Mg((L==null?void 0:L.item)??null);if(!u||Wn())return;const x=new URLSearchParams({turnId:u.turnId});u.sessionKey&&x.set("sessionKey",u.sessionKey),u.runId&&x.set("run",u.runId);const v=new AbortController;return fetch(`/orgx/api/live/activity/detail?${x.toString()}`,{method:"GET",headers:Ot({workspaceId:ae}),signal:v.signal}).then(async N=>N.ok?await N.json():(N.status===404&&at("missing"),null)).then(N=>{var Q;const S=((Q=N==null?void 0:N.detail)==null?void 0:Q.summary)??null;typeof S=="string"&&S.trim().length>0?(Ce(S),at("local")):at("missing");const V=N==null?void 0:N.headline;typeof V=="string"&&V.trim().length>0&&(ct(V.trim()),rn((N==null?void 0:N.headlineSource)??null))}).catch(N=>{N instanceof DOMException&&N.name==="AbortError"||at("missing")}),()=>v.abort()},[L,ae]);const Is=o.useCallback(u=>{var N;if(Mt.length===0)return;const v=((un>=0?un:0)+u+Mt.length)%Mt.length;he(u),B(((N=Mt[v])==null?void 0:N.item.id)??null)},[un,Mt]);o.useEffect(()=>{Z&&(un>=0||B(null))},[un,Z]),o.useEffect(()=>{if(!Z)return;const u=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",u),()=>window.removeEventListener("keydown",u)},[Z,Is]);const ns=Nt.size===1,ai=ns?[...Nt][0]:null,lr=ai?s.find(u=>u.runId===ai||u.id===ai)??null:null,f=o.useMemo(()=>{if(!ns)return[];const u=[],x=new Set;for(const v of ve){if(!v.runId||!Nt.has(v.runId))continue;const N=Ba(v.item);if(N){if(x.has(N)||(x.add(N),!De))continue}else if(!De&&Wi(v.item))continue;u.push(v.item)}return u},[ns,ve,Nt,De]),j=!T&&Mt.length<=160,O=(u,x,v)=>{const N=u.item,S=v??N.id,V=Gs(N),Q=Ol(N),ze=Hh(N,Q),qe=Q.executor??Q.requester,it=qa(yn((qe==null?void 0:qe.name)??Q.primaryLabel??N.agentName??V.agentName??null),yn((qe==null?void 0:qe.id)??N.agentId??V.agentId??null),Vt)||"OrgX";let Ke=Vh(ze)||it;if(ze==="agent"&&it){const bo=Gi(it);bo&&(Ke=`${it} (${bo})`)}const Ye=Oa(u.userState),ot=ze==="agent"?oo(it)||Ye:Kh[ze]||Ye,tt=ge==="newest"&&x<2,Dt=u.runId,cn=zl(N),Rn=ig(N),tn=vi(N),{title:Je}=Xi(N),nn=lt(N),qn=Er([{value:le(nn,["initiative_title","initiativeTitle"]),idHint:N.initiativeId},{value:N.initiativeId?U.get(N.initiativeId)??null:null,idHint:N.initiativeId}]),Ns=zs(N)??(Dt?Cn.get(Dt)??null:null),go=Er([{value:le(nn,["workstream_title","workstreamTitle"]),idHint:Ns},{value:Ns?be.get(Ns)??null:null,idHint:Ns},{value:Dt?Qn.get(Dt)??null:null,idHint:Ns}]),xo=[qn,go].filter(Boolean).join(" > "),cr=Rr(tn.scope,xo,Je,qt(N.description),Xe(Xs(N.type)))??Xe(Xs(N.type)),ua=Rr(cn,Rn,tn.update,qt(N.summary)),ma=Rr(tn.status,tn.outcomes[0],tn.nextUp[0]?`Next up: ${tn.nextUp[0]}`:null,qt(N.description)),pa=Rr(tn.update,Hl(N,ua??ma??null),Je,cr)??cr,Jc=_s(le(nn,["event","event_name","eventName"]),null),_i=Ns?H.get(Ns):void 0,Zc=(ke==null?void 0:ke.state)==="running"&&Ns===(ke==null?void 0:ke.activeWorkstreamId),ed=_i?` — #${_i.rank} in queue`:"",td=(xo||qn||go||Jc||Xs(N.type))+(Zc?ed:""),nd=Pa(u.userState),sd=new Date(N.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),id=Rt(N.timestamp),rd=u.bucket==="artifact"?ng(N):null,yo=sg(N);return n.jsx(ah,{renderKey:S,displayTitle:cr,headline:pa,contextLabel:td,detailText:(ua??ma)!==pa?ua??ma:null,displayAgentName:Ke,railColor:ot,statusColor:Ye,userStateLabel:nd,userStateWhy:u.userStateWhy,relativeTime:id,timeLabel:sd,isRecent:tt,enableMotion:j,onOpen:()=>{he(1),B(N.id)},ariaLabel:`Open activity details for ${pa||cr||Xs(N.type)}`,artifactSnippet:rd,evidenceChips:yo.length>0?yo:void 0,actorCategory:ze,queuePosition:_i?{rank:_i.rank,state:_i.state}:null},S)};return n.jsx(kh,{sessions:s,initiatives:r??[],workspaceId:ae??null,query:Ie,statusFilter:G,sortOrder:ge,timeFilterId:g,customTimeRange:h,snapshot:ie,onRequestRefresh:X,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[ns&&f.length>0?n.jsx(nh,{items:f,session:lr,agentName:((C=f[0])==null?void 0:C.agentName)??null,onBack:q,onOpenItem:u=>{he(1),B(u.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"]}),Zn>0&&!De&&n.jsxs("button",{type:"button",onClick:()=>pe(!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:[Zn," sync hidden"]}),De&&n.jsx("button",{type:"button",onClick:()=>pe(!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:me("h-1.5 w-1.5 flex-shrink-0 rounded-full",wt&&"pulse-soft"),style:{backgroundColor:D.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:Ie,onChange:u=>M(u.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(u=>!u),Ae(!1)},"aria-haspopup":"menu","aria-expanded":J,className:me("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",J?"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:me("transition-transform duration-200",J&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:J&&n.jsx(ce.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:Ki.filter(u=>u.id!=="custom").map(u=>{const x=g===u.id;return n.jsx("button",{type:"button",onClick:()=>{y==null||y(u.id),dt(!1)},className:me("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:u.label},u.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:$a(_t),onChange:u=>Tt(Dl(u.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(vo,{selected:_t,onChange:u=>Tt(u instanceof Date?u:null),selectsStart:!0,startDate:_t,endDate:St,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:$a(_t),value:$a(St),onChange:u=>Kt(Dl(u.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(vo,{selected:St,onChange:u=>Kt(u instanceof Date?u:null),selectsEnd:!0,minDate:_t??void 0,startDate:_t,endDate:St,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:Gn?`${Sr(_t)} - ${Sr(St)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:oa,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:!Gn,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:q,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Ll(Yn.id)?n.jsx(xi,{provider:Yn.id,size:"xs"}):n.jsx(Gt,{name:(jt==null?void 0:jt.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:w,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",m?`: ${m}`:""]}),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:[Ll(Jn.id)?n.jsx(xi,{provider:Jn.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(Ar).map(u=>{const x=G===u;return n.jsx("button",{type:"button",onClick:()=>we(u),"aria-pressed":x,className:me("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:Ar[u]},u)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:Ct,children:[n.jsxs("button",{type:"button",onClick:()=>{Ae(u=>!u),dt(!1)},"aria-haspopup":"menu","aria-expanded":Se,"aria-label":"Activity filters",title:"Activity filters",className:me("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Se?"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:me("transition-transform duration-200",Se&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:Se&&n.jsx(ce.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(u=>n.jsx("button",{type:"button",onClick:()=>{mt(u.id),Ae(!1)},className:me("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",ge===u.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:u.label},u.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(Ar).map(u=>{const x=G===u;return n.jsx("button",{type:"button",onClick:()=>{we(u),Ae(!1)},className:me("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:Ar[u]},u)})})]}),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:()=>{pe(u=>!u)},className:me("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:[Mt.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(ra,{icon:"activity",headline:oe?"Syncing activity feed...":st?"No activity yet for this session":d?"No activity yet for this workstream":p?`No recent activity from ${p}`:G!=="all"?`No matches for this filter. ${dn>0?`${dn} events in other categories.`:""}`:de&&de.length>0?`Waiting for autopilot to start. Queue has ${de.length} item${de.length===1?"":"s"} ready.`:"No activity yet",description:oe?"Live updates usually appear within a few seconds after dispatch.":G!=="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(u=>{const x=g===u.id;return n.jsx("button",{type:"button",onClick:()=>y==null?void 0:y(u.id),className:me("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:u.label},`empty-time-${u.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||G!=="all")&&n.jsx("button",{type:"button",onClick:()=>{st&&q(),d&&(w==null||w()),p&&(_==null||_()),G!=="all"&&we("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"}),$&&n.jsx("button",{type:"button",onClick:()=>void ii("play",$),disabled:Y!==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:Y==="play"?"Starting...":"Start next session"}),!$&&fe&&n.jsx("button",{type:"button",onClick:fe,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(sh,{completedCount:wn.completed,decisionsCount:wn.decisions,blockerCount:wn.blocked,visible:Ht,onDismiss:()=>{gt(!1),vt.current=Date.now()}}),Mt.length>0&&n.jsxs("div",{className:"space-y-4",children:[os.map(u=>{const x=u.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:u.label}),j?n.jsx(bt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:x.map((v,N)=>{const S=Ne.has(v.key),V=v.allItems.slice(1),Q=V.length,ze=Math.min(Q,Ee[v.key]??Oi),qe=V.slice(0,ze);if(v.count===1)return O(v.representative,N);if(v.key.startsWith("autopilot::")&&v.count>=3){const Ke=Fl(v);return n.jsx(Sl,{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:[O(v.representative,N,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:me("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)=>O(Ke,N+Ye+1)),ze<Q&&n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),Ji(v.key,Q)},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 (",Q-ze," remaining)"]})]})]},v.key)})})}):n.jsx("div",{className:"space-y-2",children:x.map((v,N)=>{const S=Ne.has(v.key),V=v.allItems.slice(1),Q=V.length,ze=Math.min(Q,Ee[v.key]??Oi),qe=V.slice(0,ze);if(v.count===1)return O(v.representative,N);if(v.key.startsWith("autopilot::")&&v.count>=3){const Ke=Fl(v);return n.jsx(Sl,{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:[O(v.representative,N,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:me("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)=>O(Ke,N+Ye+1)),ze<Q&&n.jsxs("button",{type:"button",onClick:Ke=>{Ke.stopPropagation(),Ji(v.key,Q)},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 (",Q-ze," remaining)"]})]})]},v.key)})})]},u.key)}),n.jsx("div",{ref:et,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:me("flex items-center justify-center py-6 transition-[opacity,transform] duration-500 ease-out",k?"opacity-100 translate-y-0":b?"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]"})]})})}),!b&&!k&&Mt.length>0&&!El(g)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:as>0?`${Mt.length} of ${dn} events`:"Beginning of activity history"})]})]})]}),Me?n.jsx(Eh,{}):null,n.jsx(oh,{open:L!==null,onClose:Mn,children:L&&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:Oa(L.userState),boxShadow:`0 0 12px ${Oa(L.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Pa(L.userState)," · ",un+1,"/",Mt.length," sessions"]}),se&&n.jsx(Ln,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:se})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[L.runId&&W&&n.jsx("button",{type:"button",onClick:()=>{W(L.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(u=>!u),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:[L.runId&&n.jsx("button",{type:"button",onClick:()=>{En("Run id",L.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"}),Ni.agentId&&n.jsx("button",{type:"button",onClick:()=>{En("Agent id",Ni.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",L.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(ce.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||Hl(L.item,K)||Xe(L.item.title||Xs(L.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(L.item.timestamp).toLocaleString()," · ",Rt(L.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 u=lt(L.item),x=(ee==null?void 0:ee.workstreamId)??zs(L.item)??(L.runId?Cn.get(L.runId)??null:null),v=Er([{value:(ee==null?void 0:ee.workstreamTitle)??null,idHint:x},{value:le(u,["workstream_title","workstreamTitle"]),idHint:x},{value:x?be.get(x)??null:null,idHint:x},{value:L.runId?Qn.get(L.runId)??null:null,idHint:x}]),S=[Er([{value:(ee==null?void 0:ee.initiativeTitle)??null,idHint:L.item.initiativeId},{value:le(u,["initiative_title","initiativeTitle"]),idHint:L.item.initiativeId},{value:L.item.initiativeId?U.get(L.item.initiativeId)??null:null,idHint:L.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:Pa(L.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?ql(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"})]}),or&&n.jsx(Ln,{tone:"lime",children:"Sync replay"})]})]}),Ft.has("artifact")&&L&&Cr(L.item)&&!mn&&n.jsxs("button",{type:"button",onClick:()=>{const u=Cr(L.item);u&&z(u)},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:D.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:D.cyan},children:"View registered artifact"})]}),n.jsx(dh,{item:L.item}),Ft.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:()=>re("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:()=>re("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:()=>z(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"?Xc(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)})})})]}),Ft.has("outcome")&&At&&n.jsxs("div",{className:me("rounded-xl border px-3.5 py-3",At.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",At.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",At.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",At.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:At.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:At.summary}),At.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:At.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[L.runId&&W&&n.jsx("button",{type:"button",onClick:()=>{W(L.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"}),tr&&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:()=>z(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"}),ar&&n.jsx("a",{href:ar,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:me("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(!Ft.has("structured_outcomes"))return null;const u=lt(L.item),x=zt(u==null?void 0:u.outcomes),v=aa(u),N=bn((u==null?void 0:u.status_updates_applied)??(u==null?void 0:u.statusUpdatesApplied)??((cn=zt(u==null?void 0:u.result))==null?void 0:cn.status_updates_applied)??((Rn=zt(u==null?void 0:u.result))==null?void 0:Rn.statusUpdatesApplied)),S=((tn=le(u,["event","event_name","eventName"]))==null?void 0:tn.toLowerCase())??"",V=(u==null?void 0:u.status_updates_buffered)??(u==null?void 0:u.statusUpdatesBuffered),Q=S.includes("status_updates_buffered")||V===!0||typeof V=="number"&&V>0||typeof V=="string"&&["true","1","yes"].includes(V.trim().toLowerCase()),ze=le(x,["pr_url","prUrl","url"]),qe=x==null?void 0:x.pr_number,it=le(x,["commit_sha","commitSha"]),Ke=le(x,["commit_url","commitUrl"]),Ye=zt(x==null?void 0:x.tests),tt=(v.length>0||(N??0)>0||Q)&&(!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:Q?"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"}`:(N??0)>0?`${N} status update${N===1?"":"s"}`:"Status updates recorded",Q?" · 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?D.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?D.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:[je&&n.jsx("button",{type:"button",onClick:je,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(u=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:u.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${u.tone==="critical"?"text-red-300":"text-primary"}`,children:u.value})]},u.label))})]}),Qe&&!ee&&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:ql(Qe.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Qe.executor.label}),(()=>{const u=Gi(Qe.executor.label);return u?n.jsxs("span",{className:"text-caption text-muted",children:["(",u,")"]}):null})()]}),Qe.mode==="handoff"&&Qe.requester&&n.jsxs("span",{className:"text-caption text-muted",children:["requested by ",Qe.requester.label]})]}),ee&&n.jsxs("div",{className:"space-y-5",children:[Ft.has("action_needed")&&(F==null?void 0:F.nextStep)&&((Bt==null?void 0:Bt.tone)==="critical"||(Bt==null?void 0:Bt.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:F.nextStep})]}),(()=>{if(!Ft.has("session"))return null;const u=lt(L.item),x=le(u,["parsed_status","status"]),v=["Queued","Dispatched","Running","Completed"],N={queued:"Queued",dispatched:"Dispatched",running:"Running",completed:"Completed",success:"Completed",blocked:"Running",needs_decision:"Running",needs_attention:"Running",failed:"Running"},S=N[x??""]??N[ee.event??""]??null,V=S?v.indexOf(S):-1,Q=x==="completed"||x==="success",ze=hi(L.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:pi(ee.event)??Xe(ee.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(Lh,{startMs:it,endMs:Ke,isTerminal:Q})," ","elapsed"]})]})]}),Bt&&n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:sr},children:ms?(At==null?void 0:At.label)??"Stopped":`${Bt.pct}%`})]}),V>=0&&n.jsx("div",{className:"mt-3 flex items-center gap-1",children:v.map((Ye,ot)=>{const tt=ot<V||ot===V&&Q,Dt=ot===V&&!Q;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?D.lime:"rgba(255,255,255,0.14)"}}),n.jsxs("div",{className:"flex flex-col items-center gap-1",children:[n.jsx("span",{className:me("h-2 w-2 rounded-full transition-transform duration-200",Dt&&"animate-pulse scale-110"),style:{backgroundColor:tt||Dt?D.lime:"rgba(255,255,255,0.18)"}}),n.jsxs("span",{className:me("text-[10px] leading-none tracking-[0.05em]",tt||Dt?"text-primary":"text-muted/60"),children:[Ye,tt&&ot===v.length-1&&" ✓"]})]})]},Ye)})}),Bt&&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,Bt.pct)}%`,backgroundColor:sr}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:ms?(At==null?void 0:At.summary)??Bt.label:Bt.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}),ee.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",Xe(ee.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}),ee.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",Xe(ee.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})]}),ee.dispatcherClient&&ee.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(ee.dispatcherClient)})]}),(ee.domain||ee.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:[ee.domain??"",ee.requiredSkills.length>0?`${ee.domain?" · ":""}${ee.requiredSkills.join(", ")}`:""]})]})]})]}),Ft.has("scope")&&F&&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:F.initiativeTitle??(F.initiativeId?Ss(F.initiativeId):"—")})]}),F.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Xe(F.initiativeStatus)})]}),(F.workstreamTitle||F.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:F.workstreamTitle??Ss(F.workstreamId)})]}),F.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Xe(F.workstreamStatus)})]})]}),F.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:[F.doneInitiativeWorkstreams??0,"/",F.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,F.initiativeWorkstreamPct)}%`}})})]})]}),ir.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(Um,{nodes:qm(ir),compact:!0})]}),((F==null?void 0:F.taskTitle)||(F==null?void 0:F.milestoneTitle)||(F==null?void 0:F.phase)||(F==null?void 0:F.nextStep)||(F==null?void 0:F.parsedStatus)||(F==null?void 0:F.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:[(F==null?void 0:F.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:F.taskTitle})]}),(F==null?void 0:F.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:F.milestoneTitle})]}),(F==null?void 0:F.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:pi(F.phase)??Xe(F.phase)})]}),(F==null?void 0:F.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:F.nextStep})]}),(F==null?void 0:F.parsedStatus)&&F.parsedStatus!==(F==null?void 0:F.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:pi(F.parsedStatus)??Xe(F.parsedStatus)})]}),(F==null?void 0:F.stopReason)&&F.stopReason!==(F==null?void 0:F.phase)&&F.stopReason!==(F==null?void 0:F.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:pi(F.stopReason)??Xe(F.stopReason)})]})]})]}),ee.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:ee.error})]}),Ft.has("summary")&&Ai&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Ze==="missing"&&!or&&Me&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(zi,{mode:"block",text:Ai,className:"text-body leading-relaxed text-primary"})]}),qt(L.item.description)&&qt(L.item.description)!==Ai&&(()=>{const u=qt(L.item.description)??"";return u.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(zi,{mode:"block",text:u,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(zi,{mode:"block",text:u,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((u,x)=>n.jsx("li",{children:u},`${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(!Ft.has("evidence"))return null;const u=lt(L.item),x=zt(u==null?void 0:u.blocker),v=le(u,["error","reason","blocked_reason","blockedReason","last_error","lastError"])??null,N=ts[0]??null,S=x?{description:le(x,["description","summary"])??v??null,waiting_on:le(x,["waiting_on","required_actor","requiredActor"])??null,required_action:le(x,["required_action","requiredAction"])??le(u,["next_step","nextStep"])??null}:N?{description:N.reason,waiting_on:N.waitingOn,required_action:N.requiredAction}:(L.item.type==="run_failed"||L.item.type==="blocker_created")&&v?{description:v,waiting_on:null,required_action:le(u,["next_step","nextStep"])}:void 0,V=(u==null?void 0:u.decisions_needed)??(u==null?void 0:u.decisionsNeeded),Q=Array.isArray(V)?V.map(Je=>{const nn=zt(Je);return nn?{title:le(nn,["title","label","question","summary"])??"Pending decision",id:le(nn,["id","decision_id","decisionId"])}:null}).filter(Je=>Je!==null):[],ze=Q.length>0?Q:nr.length>0?nr.map(Je=>({title:Je.title,id:Je.id})):Jt.length>0?Jt.map(Je=>({id:Je,title:"Pending decision"})):void 0,qe=u==null?void 0:u.outcomes,it=(tn=u==null?void 0:u.task_updates)==null?void 0:tn.filter(Je=>{var nn,qn;return((nn=Je.title)==null?void 0:nn.trim().toLowerCase())!==((qn=S==null?void 0:S.description)==null?void 0:qn.trim().toLowerCase())}),Ke=(S==null?void 0:S.description)&&(At==null?void 0:At.summary)&&S.description.trim().toLowerCase()===At.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]})]})]}),tr&&Jt.length>0&&n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ca.map(Je=>n.jsx("button",{type:"button",onClick:()=>void(P==null?void 0:P(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:[da.map((Je,nn)=>{const qn=Wr(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:Un(Je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[qn&&n.jsx("a",{href:qn,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}`)}),rr.length>0&&rr.map((Je,nn)=>{const qn=Wr(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:Un(Je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[qn&&n.jsx("a",{href:qn,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||(ee==null?void 0:ee.logPath)||ji)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),Me&&(ut||(ee==null?void 0:ee.logPath)||(ee==null?void 0:ee.outputPath)||(F==null?void 0:F.initiativeId)||(F==null?void 0:F.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?Hi(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 u;return void En("Skill pack checksum",((u=ut.skillPack)==null?void 0:u.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(u=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:u},u))]}),(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"})]}),((ee==null?void 0:ee.logPath)||(ee==null?void 0:ee.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(ee==null?void 0:ee.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: ",Un(ee.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void En("Log path",(ee==null?void 0:ee.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"})]}),(ee==null?void 0:ee.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: ",Un(ee.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void En("Output path",(ee==null?void 0:ee.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"})]})]}),((F==null?void 0:F.initiativeId)||(F==null?void 0:F.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(F==null?void 0:F.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",Ss(F.initiativeId)]}),(F==null?void 0:F.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",Ss(F.workstreamId)]})]})]})]}),Me&&ji&&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:ji})]})]})},L.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 Lg({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:D.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(ce.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(ce.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 Dg=o.lazy(async()=>({default:(await sn(()=>import("./CQSRb1yu.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),$g=o.lazy(async()=>({default:(await sn(()=>import("./DlEa8PI0.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),Pg=o.lazy(async()=>({default:(await sn(()=>import("./M4QxcXjh.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),Og=o.lazy(()=>sn(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),qg=o.lazy(()=>sn(()=>import("./Ckd1R1iE.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),Bg=o.lazy(async()=>({default:(await sn(()=>import("./DF2PMTwT.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),Fg=o.lazy(async()=>({default:(await sn(()=>import("./B6VftyY6.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),Ug=o.lazy(async()=>({default:(await sn(()=>import("./DZtNMX0t.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),zg=o.lazy(async()=>({default:(await sn(()=>import("./BPL4CL3c.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),Wg=o.lazy(async()=>({default:(await sn(()=>import("./MrW1ixGx.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),Hg=o.lazy(async()=>({default:(await sn(()=>import("./DJYl7gyA.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Kg=o.lazy(async()=>({default:(await sn(()=>import("./BANQdlC4.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),Vg=o.lazy(async()=>({default:(await sn(()=>import("./CFB0MM7j.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),Gg=o.lazy(async()=>({default:(await sn(()=>import("./B_LdOJUa.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),Kl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},Xg={connected:D.lime,reconnecting:D.amber,disconnected:D.red},Vl={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Qg=/^\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 Yg(e){const t=Zt(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Jg(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 Zg(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:Jg(s),action:"settings"}}function Lr(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 ex(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 Gl(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 Xl(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Ql(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 Yl(e,t){const s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";return!s||!i?null:`${s}:${i}`}function tx(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=Yl(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=Yl(a.initiativeId,a.workstreamId);d&&i.has(d)||(r+=1)}return r}function nx(e){return e.filter(t=>t.queueState!=="running"&&t.queueState!=="completed").length}function sx(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 Fa(e,t){const s=Vl[e.status]??99,i=Vl[t.status]??99;return s!==i?s-i:Zt(e.updatedAt??e.lastEventAt??e.startedAt)-Zt(t.updatedAt??t.lastEventAt??t.startedAt)}function Jl(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 Zl(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 ec(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 ix(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 rx(e){if(wi(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function ax(e){if(wi(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function ox(e){const t=e.metadata;return t==null||typeof t!="object"?!1:t.mock===!0}function lx(e){return Qg.test(e)}function Dr(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 cx(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function dx(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function ux(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 mx(e,t){gs(e,t)}function px(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 fx(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=ux(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Ua);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function hx(){const e=Mu();return e.showGate?n.jsx(km,{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(qp,{children:n.jsx(vx,{onboarding:e})})}function gx(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 xx(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 tc(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 nc(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function yx(){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:sa,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function bx(){const{state:e}=Cc();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Kg,{})}):null}function vx({onboarding:e}){var lr;const[t,s]=o.useState(()=>Ui()),[i,r]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Or)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(wa)==="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"}),[m,p]=o.useState(()=>fx()),g=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",m??"__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:m})});if(!j.ok)return[];const O=await j.json().catch(()=>null),C=Array.isArray(O==null?void 0:O.data)?O.data:[],u=[];for(const x of C){if(!x||typeof x!="object"||Array.isArray(x))continue;const v=Dr(x,["id"]);if(!v)continue;const N=Dr(x,["status","priority"]);if(!cx(N))continue;const S=Dr(x,["title","name"])??(v.length>10?`${v.slice(0,8)}…`:v),V=x.is_default===!0,Q=dx({title:S,isDefault:V}),ze=Dr(x,["created_at"]);u.push({id:v,title:Q,status:N,isDefault:V,createdAt:ze})}return u.sort((x,v)=>{if(x.isDefault!==v.isDefault)return x.isDefault?-1:1;const N=Zt(x.createdAt)-Zt(v.createdAt);return N!==0?N:x.title.localeCompare(v.title)}),u},staleTime:6e4}),h=o.useMemo(()=>{var f;return m?((f=y.find(j=>j.id===m))==null?void 0:f.title)??`Workspace ${m.slice(0,8)}`:"All workspaces"},[m,y]),I=o.useMemo(()=>!m||y.some(f=>f.id===m)?y:[{id:m,title:h,status:null,isDefault:!1,createdAt:null},...y],[m,h,y]);o.useEffect(()=>{m&&y.length!==0&&(y.some(f=>f.id===m)||p(null))},[m,y]),t||e.state.hasApiKey&&e.state.connectionVerified;const b=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:E,error:q,refetch:w,approveDecision:_,rejectDecision:W,approveAllDecisions:A,bulkDecisionAction:P,decisionMutation:te}=ou({useMock:t,enabled:!0,enableDecisions:!0,projectId:m,...b}),R=t||i,$=o.useMemo(()=>R?k.sessions.nodes:k.sessions.nodes.filter(f=>!rx(f)),[k.sessions.nodes,R]),ne=o.useMemo(()=>k.activity.filter(f=>!(!R&&ax(f)||!a&&ox(f))),[k.activity,R,a]),xe=k.connection==="connected"||k.decisions.length>0,[Te,fe]=o.useState(null),[je,ae]=o.useState(!1),[ie,X]=o.useState(null),[oe,Le]=o.useState(null),[Me,de]=o.useState(null),[ke,T]=o.useState(null),[z,H]=o.useState(null),[G,we]=o.useState("24h"),[De,pe]=o.useState({startIso:null,endIso:null}),Ie=o.useRef(new Set),[M,Ne]=o.useState(null),[_e,Ee]=o.useState(null),[$e,ge]=o.useState(null),[mt,Se]=o.useState(null),Ae=o.useRef(null),J=o.useCallback(f=>{Ae.current&&clearTimeout(Ae.current),Se(f),Ae.current=setTimeout(()=>Se(null),4e3)},[]),[dt,yt]=o.useState(!1),[Fe,Z]=o.useState(!1),[B,se]=o.useState([]),ue=o.useRef(null),Pe=o.useRef(null),[We,rt]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[he,Ve]=o.useState(!1),[re,K]=o.useState(null),[Ce,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"),ye("needs_attention"))},[]),[Y,ye]=o.useState("all"),Oe=o.useMemo(()=>Array.isArray(k.sliceRuns)?k.sliceRuns:[],[k.sliceRuns]),Ge=o.useMemo(()=>{var u,x,v,N;const f=Oe.filter(S=>{const V=Lt(S.status);return V==="completed"||V==="archived"});if(f.length===0)return[];const j=new Map;for(const S of $){const V=(u=S.runId)==null?void 0:u.trim();V&&!j.has(V)&&j.set(V,S);const Q=(x=S.id)==null?void 0:x.trim();Q&&!j.has(Q)&&j.set(Q,S)}const O=new Map;for(const S of $){const V=(v=S.initiativeId)==null?void 0:v.trim(),Q=(N=S.groupLabel)==null?void 0:N.trim();!V||!Q||O.has(V)||O.set(V,Q)}const C=[];for(const S of f){const V=(S.runId??S.sliceRunId??"").trim();if(!V)continue;const Q=j.get(V)??j.get(S.sliceRunId)??null,ze=S.initiativeId??(Q==null?void 0:Q.initiativeId)??null,qe=ne.filter(tt=>{const Dt=Lr(tt),cn=Gl(tt);return!!(Dt&&(Dt===V||Dt===S.sliceRunId)||cn&&cn===S.sliceRunId)}).sort((tt,Dt)=>Zt(tt.timestamp)-Zt(Dt.timestamp)),it=[...qe].reverse().map(tt=>vi(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??(Q==null?void 0:Q.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=>vi(tt).nextUp).filter(Boolean))).slice(0,5);C.push({key:`completed:${S.sliceRunId}`,runId:V,title:S.workstreamTitle??(Q==null?void 0:Q.title)??`Completed slice ${S.sliceRunId.slice(0,8)}`,statusExplainer:S.statusExplainer??S.lastEventSummary??(Q==null?void 0:Q.lastEventSummary)??null,whatChanged:Ke,whatThisUnlocked:Ye,nextUp:ot,initiativeTitle:ze?O.get(ze)??ze:null,workstreamTitle:S.workstreamTitle??(Q==null?void 0:Q.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??(Q==null?void 0:Q.updatedAt)??(Q==null?void 0:Q.lastEventAt)??null,timelineEvents:qe})}return C.sort((S,V)=>Zt(V.completedAt)-Zt(S.completedAt)),C},[Oe,ne,$]),Re=Ge.length,[He,Ue]=o.useState(null),ft=o.useCallback(f=>{const j=Oe.find(O=>O.initiativeId===f.initiativeId&&O.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)=>{J("Slice accepted and marked complete."),w()},[w,J]),Ct=o.useCallback(async(f,j)=>{J("Changes requested — feedback posted.")},[J]),Ut=o.useCallback(async(f,j,O)=>{await _(f,{optionId:j,...O?{note:O}:{}}),J("Decision resolved.")},[_,J]),nt=Qu({projectId:m,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:k.snapshotVersion}),et=Yu({authToken:null,embedMode:!1,projectId:m}),{model:$t,actions:_t}=em({enabled:!0,workspaceId:m,authToken:null,embedMode:!1}),Tt=o.useMemo(()=>$t.items.filter(f=>f.kind==="failure_diagnostic"),[$t.items]),St=o.useMemo(()=>({...$t,items:Tt,total:Tt.length}),[Tt,$t]),[Kt,vn]=o.useState(null),[ys,Hn]=o.useState(0),Kn=o.useCallback(f=>{vn(f);const j=Tt.findIndex(O=>O.id===f.id);Hn(j>=0?j:0)},[Tt]),Vn=o.useCallback(f=>{if(Tt.length===0)return;const j=(ys+f+Tt.length)%Tt.length;Hn(j),vn(Tt[j]??null)},[ys,Tt]),Gn=nt,Es=o.useMemo(()=>{var f;return((f=Gn.summary)==null?void 0:f.visibleTotal)??nx(Gn.items)},[Gn.items,(lr=Gn.summary)==null?void 0:lr.visibleTotal]),wn=o.useMemo(()=>{var u;const f=nt.items.filter(x=>x.autoContinue);if(f.length===0)return null;const j=[...f].sort((x,v)=>ec(v)-ec(x)),O=j.find(x=>{var v,N;return((v=x.autoContinue)==null?void 0:v.status)==="running"||((N=x.autoContinue)==null?void 0:N.status)==="stopping"})??null;if(O)return{item:O,state:((u=O.autoContinue)==null?void 0:u.status)==="stopping"?"stopping":"running"};const C=j.find(x=>{var v,N;return((v=x.autoContinue)==null?void 0:v.stopReason)==="blocked"||((N=x.autoContinue)==null?void 0:N.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",Xn=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(Gr,"1"),window.localStorage.removeItem(Xr)):(window.localStorage.removeItem(Gr),window.localStorage.removeItem(Xr))}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{i?window.localStorage.setItem(Or,"1"):window.localStorage.removeItem(Or)}catch{}},[i]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(wa,"1"):window.localStorage.removeItem(wa)}catch{}},[a]),o.useEffect(()=>{a||Ve(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{m?window.localStorage.setItem(Ua,m):window.localStorage.removeItem(Ua)}catch{}try{const f=new URL(window.location.href);m?mx(f.searchParams,m):px(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{}}},[m]);const Vt=o.useCallback((f,j)=>{rt(O=>({open:!0,tab:f??O.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{}},[]),Qn=o.useCallback(()=>{Vt("orgx")},[Vt]),U=o.useCallback(()=>{sn(()=>import("./CQSRb1yu.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),be=e.state.connectionVerified&&!t,{data:ve,isLoading:Be}=_c(be,m),{data:wt,isLoading:Nt}=Op(be,m),{data:st=[]}=ei({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Yt,jt]=o.useState(null),[Yn,Jn]=o.useState(""),[Mt,dn]=o.useState(!1),as=o.useCallback((f,j)=>{jt({type:f,initiativeId:j}),Jn(""),dn(!1)},[]),Zn=o.useCallback(()=>{jt(null),Jn(""),dn(!1)},[]),Ds=o.useCallback(()=>{Le(null)},[]),$s=o.useCallback(()=>{de(null),T(null)},[]),os=o.useCallback(()=>{ge(null)},[]);o.useEffect(()=>{var O;const f=((O=$[0])==null?void 0:O.id)??null;if(!f){Te!==null&&fe(null);return}if(Te===null){fe(f);return}$.some(C=>C.id===Te)||fe(f)},[$,Te]),o.useEffect(()=>{if(!oe)return;$.some(j=>j.id===oe)||Le(null)},[oe,$]);const kn=o.useCallback(f=>{sn(()=>import("./DlEa8PI0.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),fe(f),ae(!0),X(null),Le(f),de(null),T(null)},[]);o.useEffect(()=>{if(!z)return;const f=$.find(j=>j.id===z||j.runId===z)??null;f&&(kn(f.id),H(null))},[kn,z,$]);const Ji=o.useCallback(f=>{sn(()=>import("./DlEa8PI0.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),fe(f.id),ae(!0),Le(f.id),de(f.workstreamId??null),T(f.title),X({workstreamId:f.workstreamId??null,text:`Intervention requested for "${f.title}". `}),J(`Opened intervention composer for ${f.title}.`)},[]),ls=o.useCallback(f=>{const j=f.trim();if(!j)return;const O=$.find(C=>C.runId===j||C.id===j)??null;if(!O){J("Session not found — it may have ended or not started yet.");return}kn(O.id),J(`Focused session: ${O.title}`)},[$,kn,J]),oa=o.useCallback(f=>{var C;const j=(C=f.id)==null?void 0:C.trim();if(!j)return;const O=Lr(f);if(O){const u=$.find(x=>x.runId===O||x.id===O)??null;u&&(fe(u.id),Le(u.id))}g("activity"),Ze("activity"),ae(!1),Ne(j),J("Opened activity detail from session timeline.")},[$,g]),Pt=o.useMemo(()=>$.find(f=>f.id===oe)??null,[oe,$]),Pn=o.useMemo(()=>{var O,C;const f=((O=Pt==null?void 0:Pt.runId)==null?void 0:O.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 O=j.trim();O.length>0&&f.add(O)}return f},[Pn]),ki=o.useMemo(()=>{const f=new Map;for(const j of $){const O=j.workstreamId??null;j.runId&&f.set(j.runId,O),j.id&&f.set(j.id,O)}return f},[$]),es=o.useMemo(()=>{const f=Pn.length>0?Pn.join("|"):"*",j=(Me==null?void 0:Me.trim())||"*",O=($e==null?void 0:$e.trim())||"*";return`${f}::${j}::${O}`},[Me,$e,Pn]),la=o.useCallback(f=>{Ie.current.add(es),we(f)},[es]);o.useEffect(()=>{if(Ie.current.has(es)||E)return;const f=Date.now(),j=ne.filter(u=>{const x=Lr(u);if(ni.size>0&&(!x||!ni.has(x)))return!1;if(Me){const v=Xl(u);if((Ql(v,["workstreamId","workstream_id"])??(x?ki.get(x)??null:null))!==Me)return!1}if($e){const v=Xl(u);if((Ql(v,["agentName","agent_name"])??u.agentName)!==$e)return!1}return!0});if(j.length===0)return;const C=["live","24h","7d","all"].find(u=>{const x=Qi(u,f);return j.some(v=>{const N=Zt(v.timestamp);return N?x===null||N>=x:!1})})??"all";Ie.current.add(es),C!==G&&we(C)},[Me,ne,es,G,ki,$e,E,ni]);const vs=gu({seed:ne,timeFilterId:G,customSinceIso:G==="custom"?De.startIso:null,customUntilIso:G==="custom"?De.endIso:null,runId:(Pt==null?void 0:Pt.runId)??null,projectId:m,pageSize:50,demoMode:t}),on=o.useMemo(()=>$.find(f=>f.id===Te)??null,[$,Te]),Zi=o.useMemo(()=>Ac({sessions:$,sliceRuns:Oe}),[Oe,$]),Ps=typeof k.runningWorkSlices=="number"&&Number.isFinite(k.runningWorkSlices)?Math.max(0,Math.floor(k.runningWorkSlices)):Zi.length,un=o.useMemo(()=>ex(Oe,k.needsInputItems),[Oe,k.needsInputItems]),L=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]),er=o.useMemo(()=>xe?k.decisions.length:0,[k.decisions.length,xe]),cs=o.useMemo(()=>xe?tx(k.decisions,un.map(f=>f.item)):0,[k.decisions,xe,un]),mn=L+cs,On=Ps,Os=o.useMemo(()=>L,[L]);o.useMemo(()=>$.filter(f=>f.status==="failed").length,[$]);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 $.filter(j=>j.status==="completed"&&sx(j.updatedAt??j.lastEventAt??j.startedAt,f)).length},[k.completedTodayTotal,$]);o.useMemo(()=>{const f=mn;return[{id:"active",label:"Running",value:On,color:On>0?D.lime:D.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:f,color:f>0?D.amber:D.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:ds,color:D.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(()=>q?Zg(q):null,[q]),pn=o.useMemo(()=>{const f=[];if(Qe){const j=Qe.action==="refresh"&&typeof w=="function";f.push({id:`stream-error:${q}`,kind:"error",icon:"notification",title:Qe.title,message:Qe.message,actionLabel:j?"Refresh":"Settings",onAction:j?()=>void w():()=>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:Qn}),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,q,Qe,Qn,w,Vt,mt]);o.useEffect(()=>{const f=new Set(pn.map(j=>j.id));se(j=>j.filter(O=>f.has(O)))},[pn]);const ee=o.useMemo(()=>pn.filter(f=>!B.includes(f.id)),[B,pn]),si=er,ws=mn,In=o.useCallback((f,j)=>{g(f),pt("initiatives"),Ze("initiatives"),ht("in_progress"),ye("needs_attention"),j!=null&&j.closeNotifications&&Z(!1)},[g]),Ii=o.useCallback(f=>{In("mission-control",f)},[In]),Bt=o.useCallback(f=>{In("activity",f)},[In]),F=o.useCallback(f=>{se(j=>j.includes(f)?j:j.concat(f))},[]),At=o.useCallback(()=>{se(pn.map(f=>f.id))},[pn]);o.useEffect(()=>{if(!Fe)return;const f=O=>{var u,x;const C=O.target;C&&((u=Pe.current)!=null&&u.contains(C)||(x=ue.current)!=null&&x.contains(C)||Z(!1))},j=O=>{O.key==="Escape"&&Z(!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)}},[Fe]);const Ft=o.useMemo(()=>{var O;const f=new Map;for(const C of $){const u=C.initiativeId??C.groupId??"unscoped",x=C.groupLabel&&C.groupLabel.trim().length>0?C.groupLabel:C.initiativeId??"Unscoped Initiative",v=gx(x),N=f.get(u)??{id:u,name:x,category:v,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(C.progress!==null&&(N.progressTotal+=C.progress,N.progressCount+=1),N.statusCounts[C.status]=(N.statusCounts[C.status]??0)+1,C.agentName&&(N.allAgents.add(C.agentName),["running","queued","pending","blocked"].includes(C.status)&&N.activeAgents.add(C.agentName)),C.workstreamId){const S=k.sessions.groups.find(Q=>Q.id===C.workstreamId),V=((O=S==null?void 0:S.label)==null?void 0:O.trim())||C.workstreamId;N.workstreams.set(C.workstreamId,V)}N.latestEpoch=Math.max(N.latestEpoch,Zt(C.updatedAt??C.lastEventAt??C.startedAt)),f.set(u,N)}const j=[];for(const C of f.values()){const u=C.progressCount>0?Math.round(C.progressTotal/C.progressCount):C.statusCounts.completed?100:C.statusCounts.running?55:0,x=C.category,v=xx(x),N=Math.round(Math.max(0,Math.min(100,u))/100*(v.length-1)),S=(C.statusCounts.blocked??0)>0,V=(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,Q=!V&&!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.":V?`${Ke} completed.`:S?`${Ke} linked · resolve blockers to continue.`:Q?`${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(V||Dt<N)&&(cn="completed"),Dt===N&&!V&&(cn=S?"warning":"current"),{name:tt,status:cn}});j.push({id:C.id,name:C.name,status:V?"completed":S?"blocked":Q?"paused":"active",rawStatus:V?"completed":S?"blocked":Q?"paused":"active",category:x,health:Math.max(0,Math.min(100,u)),phases:ot,currentPhase:V?v.length-1:N,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,u)=>{const x=C.status==="blocked"?0:C.status==="active"?1:2,v=u.status==="blocked"?0:u.status==="active"?1:2;return x!==v?x-v:u.health-C.health})},[$,k.sessions.groups]),us=o.useMemo(()=>{const f=(C,u)=>{var N,S;const x=typeof u.description=="string"&&u.description.trim().length>0?u.description:null,v=typeof C.description=="string"&&C.description.trim().length>0?C.description:null;return{...C,...u,health:u.health>0?u.health:C.health,activeAgents:Math.max(C.activeAgents,u.activeAgents),totalAgents:Math.max(C.totalAgents,u.totalAgents),avatars:(N=C.avatars)!=null&&N.length?C.avatars:u.avatars,workstreams:(S=C.workstreams)!=null&&S.length?C.workstreams:u.workstreams,description:x??v??void 0,rawStatus:u.rawStatus??C.rawStatus??null,targetDate:u.targetDate??C.targetDate??null,createdAt:u.createdAt??C.createdAt??null,updatedAt:u.updatedAt??C.updatedAt??null}},j=new Map;for(const C of Ft)j.set(C.id,C);for(const C of[...wt??[],...ve??[]]){if(!R&&wi(C.id)){j.delete(C.id);continue}const u=C.rawStatus??C.status;if(!nc(u)){j.delete(C.id);continue}const x=j.get(C.id);j.set(C.id,x?f(x,C):C)}const O=new Set(st);return Array.from(j.values()).filter(C=>!O.has(C.id)).filter(C=>nc(C.rawStatus??C.status)).sort((C,u)=>{const x=Q=>Q==="blocked"?0:Q==="active"?1:Q==="paused"?2:3,v=x(C.status)-x(u.status);if(v!==0)return v;const N=tc(C.priority)-tc(u.priority);if(N!==0)return N;const S=Zt(u.updatedAt)-Zt(C.updatedAt);if(S!==0)return S;const V=u.health-C.health;return V!==0?V:C.name.localeCompare(u.name)})},[Ft,ve,R,wt,st]),Jt=o.useMemo(()=>[...$].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,[$]),tr=!t&&e.state.connectionVerified&&!E&&!Be&&!Nt&&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]),ca=o.useMemo(()=>{if(!Pt)return null;const f=Pt.agentName,j=Pt.title;if(f){const O=ne.find(C=>{var u;return C.runId===Pt.runId&&((u=C.summary)==null?void 0:u.trim())});if(O!=null&&O.summary){const C=O.summary.trim().length>40?O.summary.trim().slice(0,40)+"…":O.summary.trim();return`${f}: ${C}`}return f}if(j){const O=j.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(O.length>0)return O}return j??null},[ne,Pt]),nr=o.useMemo(()=>{const f=new Map;for(const j of $){const O=(j.agentId??"").trim()||`name:${(j.agentName??"").trim()}`,C=(j.agentName??"").trim()||(j.agentId??"").trim();if(!C)continue;const u=j.updatedAt??j.lastEventAt??j.startedAt??"unknown",x=Zt(u),v=x?Math.max(0,Math.floor((Date.now()-x)/6e4)):Number.MAX_SAFE_INTEGER,N=f.get(O),S={id:O,name:C,role:"Agent",status:ix(j.status),task:j.title??null,progress:j.progress??null,lastActive:u,lastActiveMinutes:v};(!N||Zt(S.lastActive)>Zt(N.lastActive))&&f.set(O,S)}return Array.from(f.values())},[$]),ts=o.useCallback(async(f,j)=>{const O=await f.json().catch(()=>null),C=typeof(O==null?void 0:O.error)=="string"&&O.error.trim()||typeof(O==null?void 0:O.message)=="string"&&O.message.trim()||`${j} (${f.status})`;return/unknown api endpoint/i.test(C)?`${j}. This route is unavailable in the running plugin build.`:Xt(C)},[]),sr=o.useCallback(async()=>{if($.length===0){J("No sessions available to continue.");return}const f=[...$].sort(Fa)[0];if(fe(f.id),Le(f.id),de(null),T(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 ts(j,`Failed to resume ${f.title}`))}J(`Focused highest priority session: ${f.title}`),await w()},[ts,w,$]),ms=o.useCallback((f,j)=>!f||f.trim().length===0?j:Xt(f.trim())||j,[]),ut=o.useCallback(async()=>{const f=Jl(nt.items);if(!f){J("No startable Next Up workstream is available."),g("mission-control");return}const j=await nt.playWorkstream({initiativeId:f.initiativeId,workstreamId:f.workstreamId,agentId:f.runnerAgentId});ht("in_progress"),ye("all"),pt("initiatives"),Le(null),de(f.workstreamId),T(f.workstreamTitle),ge(null),typeof j.sessionId=="string"&&j.sessionId.trim().length>0&&H(j.sessionId.trim()),J(j.dispatchMode==="pending"?`Dispatching ${f.workstreamTitle}…`:`Started ${f.workstreamTitle}.`),await Promise.all([nt.refetch(),w()])},[w,nt,g]),qs=o.useCallback(async(f=null)=>{const j=Jl(nt.items,f);if(!j){J("No startable initiative is ready for Autopilot yet."),g("mission-control");return}await et.move({initiativeId:j.initiativeId,workstreamId:j.workstreamId,placement:"top"});const O=await nt.startWorkstreamAutoContinue({initiativeId:j.initiativeId,workstreamId:j.workstreamId,agentId:j.runnerAgentId,scope:"initiative"});ht("in_progress"),ye("all"),pt("initiatives"),Le(null);const C=Zl(O);C?H(C):(de(j.workstreamId),T(j.workstreamTitle)),J(C?`Autopilot started for ${j.initiativeTitle}.`:`Autopilot started for ${j.initiativeTitle}; dispatching from ${j.workstreamTitle}.`),await Promise.all([nt.refetch(),w()])},[w,et,nt,g]),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}),J(`Autopilot stopped for ${Qt.initiativeTitle}.`),await Promise.all([nt.refetch(),w()])}finally{yt(!1)}},[hn,Qt,an,w,nt,qs]),ks=o.useCallback(async f=>{const j=(f.initiativeId??"").trim(),O=(f.workstreamId??"").trim();if(!j||!O)throw new Error("Missing initiative/workstream metadata for this session.");const C=await nt.playWorkstream({initiativeId:j,workstreamId:O,agentId:f.agentId??void 0});Le(null),de(O),T(f.title),typeof C.sessionId=="string"&&C.sessionId.trim().length>0&&H(C.sessionId.trim()),J(C.dispatchMode==="pending"?`Dispatching ${f.title}…`:`Started ${f.title}.`),await Promise.all([nt.refetch(),w()])},[w,nt]),Ni=o.useCallback(async f=>{const j=(f.initiativeId??"").trim(),O=(f.workstreamId??"").trim();if(!j||!O)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:O,placement:"bottom",resetToTodo:!1})});if(!C.ok){const u=await ts(C,"Failed to pause workstream from In Progress");throw new Error(u)}J(`Paused ${f.title} and sent it to the bottom of queue.`),await Promise.all([nt.refetch(),w()])},[ts,w,nt]),ji=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 O=f.text.trim();if(lx(O)){Vt("agents",{focusAgentDomain:"engineering"}),J("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:O,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!C.ok)throw new Error(await ts(C,"Failed to submit intervention"));J(`Intervention sent for ${f.session.title}.`),await w()},[Vt,ts,w]),ir=o.useCallback(async f=>{if(fe(f.id),Le(f.id),de(null),T(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 ts(j,`Failed to dispatch ${f.title}`))}J(`Dispatch requested: ${f.title}`),await w()},[ts,w]),xn=o.useCallback(async(f,j,O={})=>{const C=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/${j}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!C.ok){const u=await C.json().catch(()=>null);throw new Error((u==null?void 0:u.error)??`${j} failed (${C.status})`)}},[]),Tn=o.useCallback(async f=>{var u;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 O=await j.json().catch(()=>null),C=O&&"data"in O&&((u=O.data)==null?void 0:u.id)||O&&"id"in O&&O.id||null;J(C?`Checkpoint created: ${C.slice(0,8)}`:"Checkpoint created."),await w()},[w]),da=o.useCallback(async f=>{await xn(f,"pause",{reason:"pause_from_dashboard"}),J(`Pause requested: ${f.title}`),await w()},[w,xn]),rr=o.useCallback(async f=>{await xn(f,"resume",{reason:"resume_from_dashboard"}),J(`Resume requested: ${f.title}`),await w()},[w,xn]),ar=o.useCallback(async f=>{await xn(f,"cancel",{reason:"restart_from_in_progress"}),await ks(f),J(`Restarted ${f.title}.`),await w()},[ks,w,xn]),Ai=o.useCallback(async f=>{await xn(f,"cancel",{reason:"cancel_from_dashboard"}),J(`Cancel requested: ${f.title}`),await w()},[w,xn]),or=o.useCallback(async f=>{var v;const j=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/checkpoints`,{method:"GET"});if(!j.ok){const N=await j.json().catch(()=>null);throw new Error((N==null?void 0:N.error)??`Checkpoint list failed (${j.status})`)}const O=await j.json().catch(()=>null),x=(v=(Array.isArray(O)?O:Array.isArray(O==null?void 0:O.data)?O.data:[]).map(N=>({id:typeof N.id=="string"?N.id:"",createdAt:typeof N.createdAt=="string"?N.createdAt:typeof N.created_at=="string"?N.created_at:""})).filter(N=>N.id.length>0).sort((N,S)=>Date.parse(S.createdAt)-Date.parse(N.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"}),J(`Rollback requested for ${f.title}.`),await w()},[w,xn]),ln=o.useCallback(async()=>{var O;if(!Yt||Yn.trim().length===0||Mt)return;dn(!0);const f=Yt.type,j=Yn.trim();try{const C={type:f,title:j,status:"active"};if(f==="workstream"){const x=Yt.initiativeId??(on==null?void 0:on.initiativeId)??((O=Ft[0])==null?void 0:O.id)??null;if(!x){J("Select an initiative first to start a workstream."),dn(!1);return}C.initiative_id=x,C.parentId=x}const u=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(!u.ok){const x=await u.json().catch(()=>null);throw new Error((x==null?void 0:x.error)??`Failed to create ${f}.`)}J(`Created ${f}: ${j}`),Zn(),await w()}catch(C){J(ms(C instanceof Error?C.message:"",`Failed to create ${f}.`)),dn(!1)}},[Zn,Mt,Yt,Yn,Ft,w,on==null?void 0:on.initiativeId]),Mn=o.useCallback(f=>{jt({type:"initiative"}),Jn((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=Ft[0])==null?void 0:f.id)??null)},[Ft,on==null?void 0:on.initiativeId,ri]);const En=o.useCallback(f=>{const j=[...$].filter(O=>(O.initiativeId??O.groupId)===f.id).sort(Fa)[0];j&&(fe(j.id),Le(j.id),de(null),T(null),J(`Focused initiative: ${f.name}`))},[$]),Is=o.useCallback(f=>{const j=Ft.find(O=>O.id===f)??us.find(O=>O.id===f)??null;j&&En(j)},[En,Ft,us]),ns=o.useCallback(f=>{const j=(f??"").trim();g("activity"),pt("initiatives"),Ze("initiatives"),ht("in_progress"),ye("needs_attention"),Ee(j.length>0?j:null),J(j.length>0?"Reviewing pending decision.":"Review needs attention.")},[g]),ai=o.useCallback(f=>{const j=new Set,O=(f.runId??"").trim();O.length>0&&j.add(O),j.add(f.sliceRunId);const C=new Map;for(const S of ne){const V=Lr(S),Q=Gl(S);(V&&j.has(V)||Q&&Q===f.sliceRunId)&&C.set(S.id,S)}const u=Array.from(C.values()),x=S=>{const V=S.type.trim().toLowerCase();let Q=0;return(V==="decision_requested"||V==="blocker_created")&&(Q+=80),(V==="run_failed"||V==="autopilot_stopped")&&(Q+=70),(V.includes("slice_completed")||V.includes("completed"))&&(Q+=60),V.includes("artifact")&&(Q+=55),(V.includes("progress")||V.includes("update"))&&(Q+=35),Q+=Math.floor(Zt(S.timestamp)/1e3),Q};u.sort((S,V)=>x(V)-x(S));const v=u[0]??null;g("activity"),Ze("activity"),pt("initiatives");const N=(O?$.find(S=>S.runId===O||S.id===O)??null:null)??(f.initiativeId&&f.workstreamId?$.find(S=>S.initiativeId===f.initiativeId&&S.workstreamId===f.workstreamId)??null:null);if(N?(fe(N.id),Le(N.id),de(null),T(null)):f.workstreamId&&(Le(null),de(f.workstreamId),T(f.workstreamTitle??"Work slice")),v!=null&&v.id){Ne(v.id),J(`Reviewing activity for ${f.workstreamTitle??"work slice"}.`);return}if(f.primaryAction==="resolve_decision"){ns();return}if(O.length>0){ls(O),J("Opened the related work session. Timeline details were unavailable.");return}J("No activity details were found for this slice yet.")},[ne,ls,ns,$,g]);return o.useCallback(f=>{const j=new Set(f),O=[...$].filter(C=>j.has(C.status)).sort(Fa)[0];if(!O){J("No matching sessions for that metric right now.");return}kn(O.id),Ze("activity")},[$,kn]),o.useCallback(f=>{c==="activity"&&(f==="sessions"||f==="active"||f==="blocked"||f==="failed"||f==="decisions"||f==="outbox"||f==="handoffs")&&K(f)},[c]),E?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:D.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}})]})]})]}):tr?n.jsx(Lg,{workspaceLabel:h,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(),w()}}):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:D.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(yx,{}),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(Im,{color:Xg[k.connection],pulse:k.connection==="connected",title:[`Status: ${Kl[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: ${Yg(k.lastSnapshotAt)}`,Qe?`Details: ${Qe.message}`:null].filter(Boolean).join(`
|
|
212
|
+
`),children:Kl[k.connection]??"Unknown"}),(On>0||Os>0||si>0||ds>0)&&n.jsx(pl,{className:"hidden md:flex",running:On,blocked:Os,decisionsCount:si,completedToday:ds,onNeedsAttentionClick:()=>Ii(),onDecisionsClick:()=>Bt(),onBlockedClick:()=>{Oe.length>0?(g("mission-control"),ht("in_progress"),ye("needs_attention")):K("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:()=>g("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:()=>g("mission-control"),onMouseEnter:U,onFocus:U,"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:m??"__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: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),I.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),Qn()},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:ue,onClick:()=>Z(f=>!f),title:"Notifications","aria-haspopup":"dialog","aria-expanded":Fe,"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"})]}),ee.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:ee.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:w,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"})]}),Fe&&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:[ee.length>0&&n.jsx("button",{type:"button",onClick:At,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Z(!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(pl,{className:"max-w-full overflow-hidden",running:On,blocked:Os,decisionsCount:si,completedToday:ds,onNeedsAttentionClick:()=>Ii({closeNotifications:!0}),onDecisionsClick:()=>Bt({closeNotifications:!0}),onBlockedClick:()=>{Oe.length>0?(g("mission-control"),ht("in_progress"),ye("needs_attention")):K("blocked"),Z(!1)}})}),ee.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:ee.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),Z(!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:()=>F(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:m??"__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: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),I.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:()=>g("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:()=>g("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(Dg,{initiatives:us,activities:ne,agents:nr,runtimeInstances:k.runtimeInstances??[],workspaceInitiativeId:m,isLoading:E,authToken:null,embedMode:!1,connection:k.connection,lastSnapshotAt:k.lastSnapshotAt,error:q,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>Vt("orgx"),onRefresh:w,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 ${Ce!=="agents"?"hidden lg:flex":""}`,children:n.jsx(Ef,{sessions:k.sessions,activity:ne,runtimeInstances:k.runtimeInstances??[],showSyntheticEntities:t||i,selectedSessionId:Te,onSelectSession:kn,onAgentFilter:ge,agentFilter:$e,timeFilterId:G,onReconnect:Qn,onLaunched:w,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 ${Ce!=="activity"?"hidden lg:flex":""}`,children:n.jsx(Rg,{activity:vs.items,sessions:$,sliceRuns:Oe,initiatives:Ft,timelineNarrative:k.timelineNarrative??[],workspaceId:m,chatSnapshot:k.chat,devMode:a,selectedRunIds:Pn,selectedSessionLabel:ca,selectedWorkstreamId:Me,selectedWorkstreamLabel:ke,agentFilter:$e,timeFilterId:G,onTimeFilterChange:la,customTimeRange:De,onCustomTimeRangeChange:pe,hasMore:vs.hasMore,isLoadingMore:vs.isLoadingMore,onLoadMore:vs.loadMore,onClearSelection:Ds,onClearWorkstreamFilter:$s,onClearAgentFilter:os,onFocusRunId:ls,onOpenDecision:ns,onResolveDecision:Ut,requestedActivityItemId:M,onActivityItemRequestHandled:()=>Ne(null),onPlayNextUp:ut,onStartAutopilot:qs,onPauseWorkstream:Ni,onCreateInitiative:ii,onOpenMissionControl:()=>g("mission-control"),onOpenNextUp:()=>g("mission-control"),onOpenSettings:()=>Vt("orgx"),onRefreshData:w,isLoading:E})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${Ce!=="decisions"&&Ce!=="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:me("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:me("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:me("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:me("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=>{J(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:me("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:me("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:Xn})]})]}),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:()=>ye("all"),className:me("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Y==="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:()=>ye("needs_attention"),className:me("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Y==="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:()=>ye("completed"),className:me("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Y==="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})]}),xe&&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]}),xe&&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"?Y==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[St.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(Og,{model:St,actions:_t,onOpenDetail:Kn})})}),xe?n.jsxs("section",{className:me("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 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(Pg,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:k.decisions,focusDecisionId:_e,onFocusDecisionHandled:()=>Ee(null),onApproveDecision:_,onRejectDecision:W,onApproveAll:A,onBulkDecisionAction:P,mutationState:te,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:me("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:xe?"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(Ip,{className:me("h-full min-h-0"),title:xe?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Oe,initiatives:Ft,onOpenDecisions:()=>ns(),onFocusRunId:ls,onReviewActivity:ai,onOpenSliceDetail:gt})})]})]}):Y==="completed"?n.jsx(_p,{rows:Ge,onFocusRunId:ls,onOpenNextUp:()=>ht("next_up")}):n.jsx(mp,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:$,sliceRuns:Oe,initiatives:Ft,needsAttentionCount:mn,onSwitchToNeedsAttention:()=>ye("needs_attention"),onOpenSession:kn,onFocusRunId:ls,onPlayWorkstream:ks,onPauseWorkstream:Ni,onResumeWorkstream:ks,onRestartSession:ar,onIntervene:Ji,onOpenSliceDetail:Ht}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Bg,{projectId:m,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}:${Y}`)]}):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:je&&on&&n.jsxs(n.Fragment,{children:[n.jsx(ce.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:()=>ae(!1)},"session-drawer-backdrop"),n.jsx(ce.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:D.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($g,{session:on,activity:ne,initiatives:Ft,sliceRuns:Oe,initialInterventionDraft:ie,onSubmitIntervention:ji,onOpenActivityItem:oa,onContinueHighestPriority:sr,onDispatchSession:ir,onPauseSession:da,onResumeSession:rr,onCancelSession:Ai,onCreateCheckpoint:Tn,onRollbackSession:or,onStartInitiative:ii,onStartWorkstream:ri,onClose:()=>ae(!1)})})})},"session-drawer-panel")]})}),c==="activity"?n.jsx(jm,{activeTab:Ce,onTabChange:rn,pendingDecisionCount:xe?k.decisions.length:0}):null,n.jsx(ia,{open:Yt!==null,onClose:Zn,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:Yn,onChange:f=>Jn(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:Zn,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:Yn.trim().length===0||Mt,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:Mt?"Creating…":"Create"})]})]})}),We.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Fg,{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||Qn()},devMode:a,onToggleDevMode:l,showSyntheticEntities:i,onToggleShowSyntheticEntities:r,workspaceOptions:I,selectedWorkspaceId:m,onSelectWorkspace:p,onboarding:e,authToken:null,embedMode:!1})}),a&&he&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Gg,{open:he,selectedWorkspaceId:m,onClose:()=>Ve(!1)})}),(re==="sessions"||re==="active"||re==="blocked"||re==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ug,{open:re==="sessions"||re==="active"||re==="blocked"||re==="failed",onClose:()=>K(null),mode:re==="active"||re==="blocked"||re==="failed"?re:"sessions",sessions:$,onOpenSession:f=>{kn(f.id),K(null)},onRunAction:async(f,j)=>{await xn(f,j,{reason:`bulk_${j}_from_header`})},onRefetch:async()=>w(),onSetNotice:f=>J(f)})}),re==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(zg,{open:re==="decisions",onClose:()=>K(null),decisions:xe?k.decisions:[],onApproveDecision:_,onRejectDecision:W,onApproveAll:A,onBulkDecisionAction:P})}),re==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Wg,{open:re==="outbox",onClose:()=>K(null),outbox:k.outbox,onOpenSettings:()=>{K(null),Vt("orgx")},onRefresh:()=>{w()}})}),re==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Hg,{open:re==="handoffs",onClose:()=>K(null),handoffs:k.handoffs})}),n.jsx(bx,{}),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(qg,{item:Kt,actions:_t,onClose:()=>vn(null),onNavigate:Vn,currentIndex:ys,totalCount:Tt.length,decisions:xe?k.decisions:void 0,onApproveDecision:_,onRejectDecision:W})})})}),He&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Vg,{target:He,initiatives:Ft,onClose:()=>Ue(null),onPlayWorkstream:async(f,j,O)=>{try{const C=await nt.playWorkstream({initiativeId:f,workstreamId:j,agentId:O??void 0});await Promise.all([nt.refetch(),w()]),typeof C.sessionId=="string"&&C.sessionId.trim().length>0&&H(C.sessionId.trim()),J(C.dispatchMode==="pending"?"Dispatching workstream…":"Started workstream.")}catch(C){J(ms(C instanceof Error?C.message:null,"Failed to dispatch workstream"))}},onStartAutoContinue:async(f,j,O)=>{try{await et.move({initiativeId:f,workstreamId:j,placement:"top"});const C=await nt.startWorkstreamAutoContinue({initiativeId:f,workstreamId:j,agentId:O??void 0,scope:"initiative"}),u=Zl(C);await Promise.all([nt.refetch(),w()]),u&&H(u),J(u?"Auto-continue started.":"Auto-continue is dispatching now.")}catch(C){J(ms(C instanceof Error?C.message:null,"Failed to start auto-continue"))}},onMoveWorkstream:async(f,j,O)=>{try{await et.move({initiativeId:f,workstreamId:j,placement:O}),J(`Moved workstream to ${O}.`),w()}catch(C){J(ms(C instanceof Error?C.message:null,"Move failed"))}},onRemoveFromQueue:async(f,j)=>{try{await et.remove({initiativeId:f,workstreamId:j}),J("Removed workstream from queue."),w()}catch(O){J(ms(O instanceof Error?O.message:null,"Remove failed"))}},onOpenSession:kn,onFocusRunId:ls,onOpenInitiative:Is,onReviewActivity:ai,onOpenDecisions:()=>ns(),onAcceptSlice:vt,onRejectSlice:Ct})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});ju();const wx=new ud({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});cd.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(md,{client:wx,children:n.jsx(hx,{})})}));export{um as $,Gt as A,gs as B,me as C,Et as D,en as E,zn as F,Ss as G,Qu as H,Ox as I,Ex as J,Rx as K,Lx as L,zi as M,js as N,Cs as O,Ts as P,zf as Q,Tx as R,Un as S,Ln as T,Eu as U,Lt as V,bc as W,lo as X,ra as Y,Px as Z,dm as _,Ru as a,vc as a0,ym as a1,Dx as a2,Cd as a3,Mx as a4,Nc as a5,$x as a6,xr as a7,Pm as a8,qm as a9,cf as aa,Cx as ab,pi as ac,Um as ad,Hr as ae,Ot as b,Ka as c,Tp as d,uu as e,D as f,Hx as g,Xt as h,Wn as i,zx as j,sf as k,Ks as l,qx as m,Wt as n,Cc as o,ja as p,rs as q,Fx as r,Wx as s,Mp as t,Yu as u,Ux as v,Rt as w,Bx as x,qi as y,ia as z};
|