@useorgx/openclaw-plugin 0.7.18 → 0.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dashboard/dist/assets/{sdoPH_Z1.js → B014hrCe.js} +1 -1
  2. package/dashboard/dist/assets/B014hrCe.js.br +0 -0
  3. package/dashboard/dist/assets/B014hrCe.js.gz +0 -0
  4. package/dashboard/dist/assets/{PVi0vr9a.js → BGY6oI8h.js} +1 -1
  5. package/dashboard/dist/assets/BGY6oI8h.js.br +0 -0
  6. package/dashboard/dist/assets/BGY6oI8h.js.gz +0 -0
  7. package/dashboard/dist/assets/BJI1Iy5v.css +1 -0
  8. package/dashboard/dist/assets/BJI1Iy5v.css.br +0 -0
  9. package/dashboard/dist/assets/BJI1Iy5v.css.gz +0 -0
  10. package/dashboard/dist/assets/BUvcp_7V.js +1 -0
  11. package/dashboard/dist/assets/BUvcp_7V.js.br +0 -0
  12. package/dashboard/dist/assets/BUvcp_7V.js.gz +0 -0
  13. package/dashboard/dist/assets/BV2Tf8S2.js +212 -0
  14. package/dashboard/dist/assets/BV2Tf8S2.js.br +0 -0
  15. package/dashboard/dist/assets/BV2Tf8S2.js.gz +0 -0
  16. package/dashboard/dist/assets/{B71dt9yu.js → BYb6DARX.js} +1 -1
  17. package/dashboard/dist/assets/BYb6DARX.js.br +0 -0
  18. package/dashboard/dist/assets/BYb6DARX.js.gz +0 -0
  19. package/dashboard/dist/assets/{DS79hzMu.js → BoDhb8_y.js} +1 -1
  20. package/dashboard/dist/assets/BoDhb8_y.js.br +0 -0
  21. package/dashboard/dist/assets/BoDhb8_y.js.gz +0 -0
  22. package/dashboard/dist/assets/Bqk_l0k6.js +1 -0
  23. package/dashboard/dist/assets/Bqk_l0k6.js.br +0 -0
  24. package/dashboard/dist/assets/Bqk_l0k6.js.gz +0 -0
  25. package/dashboard/dist/assets/{C3_j_W9V.js → CV0sWMbv.js} +1 -1
  26. package/dashboard/dist/assets/CV0sWMbv.js.br +0 -0
  27. package/dashboard/dist/assets/CV0sWMbv.js.gz +0 -0
  28. package/dashboard/dist/assets/CaAkScfa.js +1 -0
  29. package/dashboard/dist/assets/CaAkScfa.js.br +0 -0
  30. package/dashboard/dist/assets/CaAkScfa.js.gz +0 -0
  31. package/dashboard/dist/assets/{CfMS9yIf.js → Ck5KlsPN.js} +1 -1
  32. package/dashboard/dist/assets/Ck5KlsPN.js.br +0 -0
  33. package/dashboard/dist/assets/Ck5KlsPN.js.gz +0 -0
  34. package/dashboard/dist/assets/{CReugbyT.js → D2G51wQm.js} +1 -1
  35. package/dashboard/dist/assets/D2G51wQm.js.br +0 -0
  36. package/dashboard/dist/assets/D2G51wQm.js.gz +0 -0
  37. package/dashboard/dist/assets/{467jKHFJ.js → DAr4MfFk.js} +1 -1
  38. package/dashboard/dist/assets/DAr4MfFk.js.br +0 -0
  39. package/dashboard/dist/assets/DAr4MfFk.js.gz +0 -0
  40. package/dashboard/dist/assets/{BcJmNILk.js → DXVs61e1.js} +1 -1
  41. package/dashboard/dist/assets/DXVs61e1.js.br +0 -0
  42. package/dashboard/dist/assets/DXVs61e1.js.gz +0 -0
  43. package/dashboard/dist/assets/{5Ihga-4X.js → DibzNd0I.js} +1 -1
  44. package/dashboard/dist/assets/DibzNd0I.js.br +0 -0
  45. package/dashboard/dist/assets/DibzNd0I.js.gz +0 -0
  46. package/dashboard/dist/assets/{qDJ6rqcs.js → Dm0CfDGr.js} +1 -1
  47. package/dashboard/dist/assets/Dm0CfDGr.js.br +0 -0
  48. package/dashboard/dist/assets/Dm0CfDGr.js.gz +0 -0
  49. package/dashboard/dist/assets/_zpQCpjm.js +1 -0
  50. package/dashboard/dist/assets/_zpQCpjm.js.br +0 -0
  51. package/dashboard/dist/assets/_zpQCpjm.js.gz +0 -0
  52. package/dashboard/dist/assets/{C-XuWXGi.js → uNGpYMSH.js} +1 -1
  53. package/dashboard/dist/assets/uNGpYMSH.js.br +0 -0
  54. package/dashboard/dist/assets/uNGpYMSH.js.gz +0 -0
  55. package/dashboard/dist/assets/{a6qcPiWt.js → wa4jJQK9.js} +1 -1
  56. package/dashboard/dist/assets/wa4jJQK9.js.br +0 -0
  57. package/dashboard/dist/assets/wa4jJQK9.js.gz +0 -0
  58. package/dashboard/dist/index.html +2 -2
  59. package/dashboard/dist/index.html.br +0 -0
  60. package/dashboard/dist/index.html.gz +0 -0
  61. package/dist/http/helpers/auto-continue-engine.d.ts +39 -0
  62. package/dist/http/helpers/auto-continue-engine.js +96 -0
  63. package/dist/http/index.js +2 -1
  64. package/dist/http/routes/mission-control-read.d.ts +14 -0
  65. package/dist/http/routes/mission-control-read.js +69 -5
  66. package/dist/outbox.js +9 -2
  67. package/package.json +2 -1
  68. package/dashboard/dist/assets/467jKHFJ.js.br +0 -0
  69. package/dashboard/dist/assets/467jKHFJ.js.gz +0 -0
  70. package/dashboard/dist/assets/5Ihga-4X.js.br +0 -0
  71. package/dashboard/dist/assets/5Ihga-4X.js.gz +0 -0
  72. package/dashboard/dist/assets/B71dt9yu.js.br +0 -0
  73. package/dashboard/dist/assets/B71dt9yu.js.gz +0 -0
  74. package/dashboard/dist/assets/BEnI6kNR.js +0 -1
  75. package/dashboard/dist/assets/BEnI6kNR.js.br +0 -0
  76. package/dashboard/dist/assets/BEnI6kNR.js.gz +0 -0
  77. package/dashboard/dist/assets/BcJmNILk.js.br +0 -0
  78. package/dashboard/dist/assets/BcJmNILk.js.gz +0 -0
  79. package/dashboard/dist/assets/C-XuWXGi.js.br +0 -0
  80. package/dashboard/dist/assets/C-XuWXGi.js.gz +0 -0
  81. package/dashboard/dist/assets/C3_j_W9V.js.br +0 -0
  82. package/dashboard/dist/assets/C3_j_W9V.js.gz +0 -0
  83. package/dashboard/dist/assets/C9-UYhBb.js +0 -1
  84. package/dashboard/dist/assets/C9-UYhBb.js.br +0 -0
  85. package/dashboard/dist/assets/C9-UYhBb.js.gz +0 -0
  86. package/dashboard/dist/assets/C9yV06GS.js +0 -1
  87. package/dashboard/dist/assets/C9yV06GS.js.br +0 -0
  88. package/dashboard/dist/assets/C9yV06GS.js.gz +0 -0
  89. package/dashboard/dist/assets/CReugbyT.js.br +0 -0
  90. package/dashboard/dist/assets/CReugbyT.js.gz +0 -0
  91. package/dashboard/dist/assets/CSDhTbKy.js +0 -1
  92. package/dashboard/dist/assets/CSDhTbKy.js.br +0 -0
  93. package/dashboard/dist/assets/CSDhTbKy.js.gz +0 -0
  94. package/dashboard/dist/assets/CfMS9yIf.js.br +0 -0
  95. package/dashboard/dist/assets/CfMS9yIf.js.gz +0 -0
  96. package/dashboard/dist/assets/D2Kqcmv9.js +0 -212
  97. package/dashboard/dist/assets/D2Kqcmv9.js.br +0 -0
  98. package/dashboard/dist/assets/D2Kqcmv9.js.gz +0 -0
  99. package/dashboard/dist/assets/DS79hzMu.js.br +0 -0
  100. package/dashboard/dist/assets/DS79hzMu.js.gz +0 -0
  101. package/dashboard/dist/assets/PVi0vr9a.js.br +0 -0
  102. package/dashboard/dist/assets/PVi0vr9a.js.gz +0 -0
  103. package/dashboard/dist/assets/RZkbqlJk.css +0 -1
  104. package/dashboard/dist/assets/RZkbqlJk.css.br +0 -0
  105. package/dashboard/dist/assets/RZkbqlJk.css.gz +0 -0
  106. package/dashboard/dist/assets/a6qcPiWt.js.br +0 -0
  107. package/dashboard/dist/assets/a6qcPiWt.js.gz +0 -0
  108. package/dashboard/dist/assets/qDJ6rqcs.js.br +0 -0
  109. package/dashboard/dist/assets/qDJ6rqcs.js.gz +0 -0
  110. package/dashboard/dist/assets/sdoPH_Z1.js.br +0 -0
  111. package/dashboard/dist/assets/sdoPH_Z1.js.gz +0 -0
@@ -1,212 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CSDhTbKy.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/BEnI6kNR.js","assets/BcJmNILk.js","assets/eeHXe_OQ.js","assets/a6qcPiWt.js","assets/BCudUvwg.js","assets/PVi0vr9a.js","assets/5Ihga-4X.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/C-XuWXGi.js","assets/467jKHFJ.js","assets/CReugbyT.js","assets/CSlBSRyv.js","assets/C-MOJWHs.js","assets/CfMS9yIf.js","assets/DS79hzMu.js","assets/C9-UYhBb.js","assets/C3_j_W9V.js","assets/sdoPH_Z1.js","assets/qDJ6rqcs.js","assets/C9yV06GS.js","assets/B71dt9yu.js"])))=>i.map(i=>d[i]);
2
- var Ac=Object.defineProperty;var _c=(e,t,s)=>t in e?Ac(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Un=(e,t,s)=>_c(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as Sc,d as Cc}from"./Dj2k1r16.js";import{u as Ma,a as Mc,b as Cn,c as qs,Q as Tc,d as Ec}from"./DMKyYAtD.js";import{m as ce,A as vt,u as is}from"./eeHXe_OQ.js";import{a7 as Rc}from"./cX2e-TLi.js";import{D as Ya}from"./BjK42gtU.js";import{T as Lc,u as $c}from"./BV0BcV1u.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function s(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=s(i);fetch(i.href,a)}})();const Dc="modulepreload",Fc=function(e){return"/orgx/live/"+e},Za={},nn=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=c(s.map(u=>{if(u=Fc(u),u in Za)return;Za[u]=!0;const p=u.endsWith(".css"),x=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${x}`))return;const b=document.createElement("link");if(b.rel=p?"stylesheet":Dc,p||(b.as="script"),b.crossOrigin="",b.href=u,d&&b.setAttribute("nonce",d),document.head.appendChild(b),p)return new Promise((g,j)=>{b.addEventListener("load",g),b.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return i.then(c=>{for(const l of c||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})},eo=()=>{const e=new Date,t=s=>new Date(e.getTime()-s*60*1e3).toISOString();return{connection:"connected",lastActivity:"2m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:1,sessions:{groups:[{id:"init-1",label:"Q4 Feature Ship",status:"active"},{id:"init-2",label:"Black Friday Email",status:"active"}],edges:[{parentId:"run-1",childId:"run-2"},{parentId:"run-1",childId:"run-3"}],nodes:[{id:"run-1",parentId:null,runId:"run-1",title:"Q4 Feature Ship – Planning",agentId:"eli",agentName:"Eli",status:"running",progress:45,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(120),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Delegated work to design and data agents.",blockers:[]},{id:"run-2",parentId:"run-1",runId:"run-2",title:"Dashboard UI pass",agentId:"dana",agentName:"Dana",status:"running",progress:70,initiativeId:"init-1",workstreamId:"ws-4",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(80),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Drafted handoff for approval.",blockers:["Approval pending"]},{id:"run-3",parentId:"run-1",runId:"run-3",title:"Usage tracking instrumentation",agentId:"pace",agentName:"Pace",status:"queued",progress:0,initiativeId:"init-1",workstreamId:"ws-5",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(30),updatedAt:t(12),lastEventAt:t(12),lastEventSummary:"Waiting for data pipeline access.",blockers:["Access to events table"]},{id:"run-4",parentId:null,runId:"run-4",title:"Black Friday Email Campaign",agentId:"mark",agentName:"Mark",status:"running",progress:55,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Black Friday Email",startedAt:t(90),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Drafted subject line variants.",blockers:[]}]},activity:[{id:"activity-1",type:"decision_requested",title:"Decision requested",description:"Approve dashboard UI layout for Q4 Feature Ship.",agentId:"dana",agentName:"Dana",requesterAgentId:"dana",requesterAgentName:"Dana",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-2",initiativeId:"init-1",timestamp:t(2),metadata:{event:"decision_needed",event_name:"decision_needed",source:"agent",parsed_status:"blocked",decision_title:"Approve dashboard UI layout",decisions_needed:[{title:"Dashboard layout direction",id:"dec-1"}],blocker:{description:"Waiting for layout approval",waiting_on:"you"}}},{id:"activity-2",type:"artifact_created",title:"Artifact created: Subject line variants",description:"Drafted 3 subject line variants for approval.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-4",initiativeId:"init-2",timestamp:t(8),metadata:{event:"artifact_created",event_name:"artifact_created",source:"agent",parsed_status:"completed",outcomes:{pr_url:"https://github.com/orgx/demo/pull/47",pr_number:47,commit_sha:"a3f2b1c",commit_url:"https://github.com/orgx/demo/commit/a3f2b1c",tests:{passed:12,failed:0,skipped:2}},task_updates:[{title:"Draft email variants",status:"completed"},{title:"A/B test setup",status:"in_progress"}]}},{id:"activity-3",type:"delegation",title:"Task delegated",description:"Spin up data agent for instrumentation plan.",agentId:"eli",agentName:"Eli",requesterAgentId:"eli",requesterAgentName:"Eli",executorAgentId:"eli",executorAgentName:"Eli",runId:"run-1",initiativeId:"init-1",timestamp:t(18),metadata:{event:"autopilot_slice_dispatched",event_name:"autopilot_slice_dispatched",source:"orchestrator",parsed_status:"running",run_id:"slice-run-1",dispatch_selection_reason:"Highest priority unblocked task"}},{id:"activity-4",type:"run_completed",title:"Implemented usage tracking pipeline",description:"Completed instrumentation for usage tracking events.",agentId:"pace",agentName:"Pace",requesterAgentId:"eli",requesterAgentName:"Eli",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-3",initiativeId:"init-1",timestamp:t(35),metadata:{event:"autopilot_slice_result",event_name:"autopilot_slice_result",source:"agent",parsed_status:"completed",run_id:"slice-run-3",outcomes:{tests:{passed:8,failed:0,skipped:0}},task_updates:[{title:"Usage tracking instrumentation",status:"completed"}]}},{id:"activity-5",type:"delegation",title:"Dispatched work to Dana",description:"Orchestrator assigned dashboard UI pass to Dana.",agentId:"xandy",agentName:"Xandy",requesterAgentId:"xandy",requesterAgentName:"Xandy",executorAgentId:"xandy",executorAgentName:"Xandy",runId:"run-1",initiativeId:"init-1",timestamp:t(25),metadata:{event:"orchestrator_dispatch",event_name:"orchestrator_dispatch",source:"system"}},{id:"activity-6",type:"run_started",title:"Started autopilot",description:"User started autopilot for Q4 Feature Ship.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-1",initiativeId:"init-1",timestamp:t(120),metadata:{event:"auto_continue_started",event_name:"auto_continue_started",source:"user",parsed_status:"running"}},{id:"activity-7",type:"run_started",title:"Heartbeat",description:"System health check.",agentId:"system",agentName:"System",requesterAgentId:"system",requesterAgentName:"System",executorAgentId:"system",executorAgentName:"System",runId:"run-1",initiativeId:"init-1",timestamp:t(5),metadata:{event:"heartbeat",event_name:"heartbeat",source:"system"}}],handoffs:[{id:"handoff-1",title:"Dashboard UI approval",status:"created",priority:"high",summary:"Need approval on dashboard UI layout and component hierarchy.",currentActorType:"user",currentActorId:"me",createdAt:t(12),updatedAt:t(2),events:[{id:"handoff-event-1",handoffId:"handoff-1",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Draft layout ready for review."},createdAt:t(12)}]}],decisions:[{id:"decision-1",title:"Approve dashboard copy update",context:"Marketing requested a copy refresh before final launch. Confirm wording changes.",status:"pending",agentName:"Mark",requestedAt:t(22),updatedAt:t(2),waitingMinutes:22}],sliceRuns:[{id:"slice-run-1",sliceRunId:"slice-run-1",runId:"run-2",initiativeId:"init-1",workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",taskIds:["task-1"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Needs your decision to proceed with this slice.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"approve-layout",label:"Approve layout",description:"Proceed with the current dashboard layout.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"codex",runtimeState:"active",startedAt:t(80),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting on approval before implementation continues.",correlationId:"run-2",confidence:"high"},{id:"slice-run-2",sliceRunId:"slice-run-2",runId:"run-4",initiativeId:"init-2",workstreamId:"ws-9",workstreamTitle:"Email campaign generation",taskIds:["task-2"],milestoneIds:[],status:"completed",statusExplainer:"Completed with verified output artifacts.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-1",type:"document",title:"Subject line variants",url:null,createdAt:t(8)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:t(90),updatedAt:t(8),completedAt:t(8),failedAt:null,archivedAt:null,lastEventAt:t(8),lastEventSummary:"Produced subject line variants and attached artifact.",correlationId:"run-4",confidence:"high"},{id:"slice-run-3",sliceRunId:"slice-run-3",runId:"run-3",initiativeId:"init-1",workstreamId:"ws-5",workstreamTitle:"Usage tracking instrumentation",taskIds:["task-3"],milestoneIds:[],status:"completed",statusExplainer:"Completed successfully.",primaryAction:"review_output",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"stopped",startedAt:t(38),updatedAt:t(35),completedAt:t(35),failedAt:null,archivedAt:null,lastEventAt:t(35),lastEventSummary:"Usage tracking pipeline implemented.",correlationId:"run-3",confidence:"high"}],outbox:{pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},Bi="all";function ss(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Pc(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return ss(e.get("workspace_id"))??ss(e.get("workspaceId"))??ss(e.get("command_center_id"))??ss(e.get("commandCenterId"))??ss(e.get("center"))??ss(e.get("project_id"))??ss(e.get("projectId"))}catch{return null}}function Ns(e,t,s){const r=ss(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",Bi),e.set("command_center_id",Bi),e.set("center",Bi));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function Oc(e){const t=ss(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??Pc();return Object.assign(t,Oc(s)),t}const Bc=[[/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 Cr(e){if(!e)return"";for(const[s,r]of Bc)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const Sl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Cl=/^[0-9a-f]{20,}$/i;function ws(e){return Sl.test(e)?`#${e.slice(0,4)}`:Cl.test(e)?`#${e.slice(0,4)}`:e}function Vn(e){return Sl.test(e)||Cl.test(e)}function Ds(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const r=s.split("/");return r.length>t&&(s=r.slice(-t).join("/")),s}function at(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=>Cr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Ds(s)),t}function Yt(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=>Ds(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 qi(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 to(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function mr(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function qc(e,t){if(!e)return null;for(const s of t){const r=e[s];if(!(typeof r!="number"||!Number.isFinite(r)))return r}return null}function no(e){const t=to(e);if(!t)return null;const s=to(t.error),r=s??t,i=mr(r,["message","detail","error_description"])??(s?null:mr(t,["error"])),a=mr(r,["code","error_code","type"]),c=qc(r,["status","httpStatusCode"]),l=mr(r,["requestId","request_id"]),d=mr(r,["docsUrl","docs_url"]);return!i&&!a&&c==null&&!l&&!d?null:{code:a,message:i,status:c,requestId:l,docsUrl:d}}function zc(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),r=no(s);if(r)return r;const i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){const p=t.slice(i,a+1);try{const x=JSON.parse(p),b=no(x);if(b)return b}catch{}}const c=t.match(/"message"\s*:\s*"([^"]+)"/i),l=t.match(/"code"\s*:\s*"([^"]+)"/i);return!c&&!l?null:{code:((d=l==null?void 0:l[1])==null?void 0:d.trim())||null,message:((u=c==null?void 0:c[1])==null?void 0:u.trim())||null,status:null,requestId:null,docsUrl:null}}function so(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 Wt(e){var l;const t=zc(e),s=((l=t==null?void 0:t.code)==null?void 0:l.toLowerCase())??"",r=(t==null?void 0:t.message)??null,i=(r==null?void 0:r.toLowerCase())??"";if(s==="internal_error"||i.includes("internal server error"))return/list decision|load decision|decision/i.test(i)?"Decisions are temporarily unavailable. Try refreshing in a moment.":"OrgX hit a temporary server issue. We will retry automatically.";if(s==="unauthorized"||s==="forbidden"||i.includes("unauthorized")||i.includes("forbidden"))return"Authentication needs attention. Reconnect OrgX in Settings.";const a=so(r||e),c=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(c)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(c)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(c)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(c)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(c)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(c)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(c)?"This session is no longer available.":/500|internal_error|internal server error/i.test(c)?"Something went wrong on the server. Retrying automatically.":/econnrefused|network error|fetch failed/i.test(c)?"Connection issue. Retrying automatically.":/40[13]/.test(c)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(c)?"This item was paused without a specific reason.":Yt(at(a))}function Wc(e,t){if(e==null&&t==null||e===0&&t)return null;const s=e??0,r=t??0,i=a=>a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:`${a}`;return r>0?`${i(s)} / ${i(r)} (${Math.round(s/r*100)}%)`:i(s)}function Uc(e){const t=e.metadata??{},s=Xs(t,"task_title")??Xs(t,"workstream_title"),r=s?Yt(String(s)):e.title?Yt(e.title):null,i=Xs(t,"user_summary")??Xs(t,"summary"),a=i?Yt(String(i)):e.summary?Yt(e.summary):e.description?Yt(e.description):null,c=Xs(t,"next_step")??Xs(t,"nextStep"),l=c?Yt(String(c)):null,d=(x,b)=>x===b||x.includes(b)||b.includes(x),u=a&&r&&d(a,r)?null:a,p=l&&(r&&d(l,r)||a&&d(l,a))?null:l;return{taskDescription:r,outcomeDescription:u,nextStep:p}}function Xs(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const Hc={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 pr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Hc[t]??e.replace(/_/g," ")}const Vc={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function jg(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Vc[t]??e.replace(/_/g," ")}function Ng(e,t){return e.toLowerCase().includes("path")?Ds(t):Vn(t)?ws(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return Vn(i)?ws(i):i}).join(", "):Yt(t)}function Kc(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 r=Math.floor(t/24);return r<7?`${r} day${r===1?"":"s"}`:r<14?"over a week":`${Math.floor(r/7)} weeks`}function Ig(e){const t=Kc(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function wi(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function $t(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const r=Math.floor(Math.abs(s)/1e3),i=s<0?"past":"future";if(r<10)return i==="past"?"just now":"soon";if(r<60)return i==="past"?`${r}s ago`:`in ${r}s`;const a=Math.floor(r/60);if(a<60)return i==="past"?`${a}m ago`:`in ${a}m`;const c=Math.floor(a/60);if(c<24)return i==="past"?`${c}h ago`:`in ${c}h`;const l=Math.floor(c/24);return i==="past"?`${l}d ago`:`in ${l}d`}const Gc=8e3,Xc=320,Qc=300,Jc=80,Yc=80,Zc=120,ro=6e4,ed=1200,td=90,nd=3,sd=24,io=24,fr=new WeakMap,Ta={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Wr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Os={threads:[],total:0,updatedAt:null},ao={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},Ml=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Ur=10*6e4;function rd(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 id(e){const t=e.map(a=>a.trim()).filter(Boolean);if(t.length===0)return"Live data is unavailable right now. OrgX Live will retry automatically.";const s=t.map(a=>a.toLowerCase());return s.every(a=>a.includes("timed out")||a.includes("timeout")||a.includes("signal is aborted")||a.includes("request cancelled")||a.includes("request canceled"))?"Live sync is taking longer than expected. OrgX Live is retrying in the background.":s.some(a=>a.includes("unknown api endpoint"))?"This plugin runtime is missing required live routes. Restart the plugin, then update if needed.":s.some(a=>a.includes("unauthorized")||a.includes("forbidden"))?"OrgX authorization needs attention. Reconnect your API key in Settings.":Array.from(new Set(t.map(a=>{const c=a.replace(/^[^:]+:\s*/,"").trim();return c.length>0?c:a}))).slice(0,2).map(a=>Wt(a)).filter(a=>a.length>0).join(" ")}function ad(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 Wt(s.length>0?s:e.trim())}function od(e){const t=e.map(s=>ad(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function wt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function vi(e,t){const s=ao[e.status]??99,r=ao[t.status]??99;if(s!==r)return s-r;const i=wt(e.updatedAt??e.lastEventAt??e.startedAt),a=wt(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function ld(e){return(e??"").trim().toLowerCase()}function oo(e){return Ml.has(ld(e.status))}function zi(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function lo(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const g=Date.now(),j=e.nodes.filter(k=>{const N=wt(k.updatedAt??k.lastEventAt??k.startedAt);if(oo(k))return!0;const C=["completed","archived","failed"].includes((k.status??"").toLowerCase())?Ur/3:Ur;return g-N<=C});if(!j.length)return t;const y=new Set(j.map(k=>k.id)),I=new Set(j.map(k=>k.groupId));return{nodes:j.sort(vi),edges:e.edges.filter(k=>y.has(k.parentId)&&y.has(k.childId)),groups:e.groups.filter(k=>I.has(k.id))}}const s=new Set,r=[...t.nodes];for(const g of t.nodes)for(const j of zi(g))s.add(j);const i=Date.now(),a=[];for(const g of e.nodes){if(zi(g).some(h=>s.has(h)))continue;const y=wt(g.updatedAt??g.lastEventAt??g.startedAt),k=["completed","archived","failed"].includes((g.status??"").toLowerCase())?Ur/3:Ur,N=i-y<=k;if(oo(g)||N){a.push(g),r.push(g);for(const h of zi(g))s.add(h)}}if(!a.length)return t;const c=new Set(r.map(g=>g.id)),l=new Map(e.groups.map(g=>[g.id,g])),d=new Map(t.groups.map(g=>[g.id,g])),u=[...t.groups];for(const g of a){if(d.has(g.groupId))continue;const j=l.get(g.groupId)??{id:g.groupId,label:g.groupLabel||g.agentName||"Ungrouped",status:null};d.set(g.groupId,j),u.push(j)}const p=g=>`${g.parentId}->${g.childId}`,x=new Set,b=[];for(const g of t.edges){if(!c.has(g.parentId)||!c.has(g.childId))continue;const j=p(g);x.has(j)||(x.add(j),b.push(g))}for(const g of e.edges){if(!c.has(g.parentId)||!c.has(g.childId))continue;const j=p(g);x.has(j)||(x.add(j),b.push(g))}return{nodes:r.sort(vi),edges:b,groups:u}}function hr(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(vi).slice(0,t),r=new Set(s.map(a=>a.id)),i=new Set(s.map(a=>a.groupId));return{nodes:s,edges:e.edges.filter(a=>r.has(a.parentId)&&r.has(a.childId)),groups:e.groups.filter(a=>i.has(a.id))}}function co(e,t){return e.length<=t?e:[...e].sort((s,r)=>wt(r.updatedAt)-wt(s.updatedAt)).slice(0,t)}function cd(e){const t=e.requestedAt??e.updatedAt??null,s=e.updatedAt??t,r=Number.isFinite(e.waitingMinutes)?Math.max(0,Math.floor(e.waitingMinutes)):t?Math.max(0,Math.floor((Date.now()-wt(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:r,metadata:e.metadata}}function Tl(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 uo(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 r=e.nodes[s],i=t.nodes[s];if(r.id!==i.id||r.status!==i.status||r.title!==i.title||r.progress!==i.progress||r.updatedAt!==i.updatedAt||r.lastEventAt!==i.lastEventAt)return!1}for(let s=0;s<e.edges.length;s+=1){const r=e.edges[s],i=t.edges[s];if(r.parentId!==i.parentId||r.childId!==i.childId)return!1}for(let s=0;s<e.groups.length;s+=1){const r=e.groups[s],i=t.groups[s];if(r.id!==i.id||r.label!==i.label||r.status!==i.status)return!1}return!0}function mo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function po(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function El(e){if(!e||typeof e!="object")return Ta;const t=e.pendingByQueue&&typeof e.pendingByQueue=="object"?Object.fromEntries(Object.entries(e.pendingByQueue).filter(([r])=>typeof r=="string"&&r.length>0).map(([r,i])=>[r,Number.isFinite(Number(i))?Math.max(0,Math.floor(Number(i))):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((r,i)=>r+i,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 dd(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),r=Object.keys(t.pendingByQueue);if(s.length!==r.length)return!1;for(const i of s)if(e.pendingByQueue[i]!==t.pendingByQueue[i])return!1;return!0}function ki(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 r=e,i=fr.get(r);if(i)return i;if(t>=nd){const x=Array.isArray(e)?"[…]":"{…}";return fr.set(r,x),x}if(fr.set(r,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const x=e.slice(0,io).map(j=>ki(j,t+1)).join(","),b=e.length>io?",…":"",g=`[${x}${b}]`;return fr.set(r,g),g}const a=e,c=Object.keys(a).sort(),l=c.slice(0,sd),d=l.map(x=>`${x}:${ki(a[x],t+1)}`).join("|"),u=c.length>l.length?"|…":"",p=`{${d}${u}}`;return fr.set(r,p),p}function ud(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ts(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function md(e){const t=ud(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"",i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??Ts(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=Ts(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??Ts(t,["initiative_id","initiativeId"]),l=Ts(t,["workstream_id","workstreamId"]),d=Ts(t,["task_id","taskId"]),u=Ts(t,["stop_reason","stopReason"]),p=Ts(t,["parsed_status","parsedStatus"]),x=(e.title??"").trim().toLowerCase();return!r&&!i&&!a||!i&&!a&&!l&&!d?null:[r,c??"",l??"",d??"",i??"",a??"",u??"",p??"",x].join("|")}function Hr(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 Rl(e,t){const s=new Set,r=new Set,i=new Map,a=[];for(const c of e){if(s.has(c.id)){const d=a.findIndex(u=>u.id===c.id);d>=0&&Hr(c)>Hr(a[d])&&(a[d]=c);continue}s.add(c.id);const l=md(c);if(l&&r.has(l)){const d=i.get(l);Hr(c)>Hr(a[d])&&(a[d]=c);continue}if(l&&(r.add(l),i.set(l,a.length)),a.push(c),a.length>=t)break}return a}function pd(e,t,s){if(t.length===0)return e;const r=new Map,i=new Map;for(const d of e)r.set(d.id,d),i.set(d.id,ki(d.metadata));let a=!1;for(const d of t){const u=r.get(d.id),p=ki(d.metadata);if(!u){r.set(d.id,d),i.set(d.id,p),a=!0;continue}(u.timestamp!==d.timestamp||u.type!==d.type||u.title!==d.title||u.description!==d.description||u.summary!==d.summary||u.kind!==d.kind||u.agentId!==d.agentId||u.agentName!==d.agentName||u.requesterAgentId!==d.requesterAgentId||u.requesterAgentName!==d.requesterAgentName||u.executorAgentId!==d.executorAgentId||u.executorAgentName!==d.executorAgentName||u.runId!==d.runId||u.initiativeId!==d.initiativeId||u.decisionRequired!==d.decisionRequired||i.get(d.id)!==p)&&(r.set(d.id,d),i.set(d.id,p),a=!0)}if(!a)return e;const c=Array.from(r.values()).sort((d,u)=>{const p=wt(u.timestamp)-wt(d.timestamp);return p!==0?p:u.id.localeCompare(d.id)}),l=Rl(c,s);return Tl(e,l)?e:l}function Wi(e,t){const s=[...e].sort((r,i)=>{const a=wt(i.timestamp)-wt(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Rl(s,t)}function fo(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(cd).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:wt(c.requestedAt??c.updatedAt)-wt(a.requestedAt??a.updatedAt)).slice(0,t),r=new Set,i=[];for(const a of s)r.has(a.id)||(r.add(a.id),i.push(a));return i}function ho(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 fd(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 hd(e,t){return!!(Ml.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function Vr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function Ui(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 gd(e,t,s){const r=new Map,i=[...e].sort((l,d)=>wt(d.timestamp)-wt(l.timestamp));for(const l of i){if(!l.runId)continue;const d=l.runId,u=r.get(d),p=l.timestamp;if(!u){const x=l.initiativeId??null;r.set(d,{id:d,parentId:null,runId:d,title:l.title,agentId:l.agentId??null,agentName:l.agentName??null,status:ho(l.type),progress:null,initiativeId:x,workstreamId:null,groupId:x??"unscoped",groupLabel:Vr(x),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:l.title,blockers:l.type==="blocker_created"&&l.description?[l.description]:[]});continue}(!u.startedAt||wt(p)<wt(u.startedAt))&&(u.startedAt=p),wt(p)>=wt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=p,u.lastEventAt=p,u.lastEventSummary=l.title,u.status=ho(l.type),l.agentName&&(u.agentName=l.agentName),l.agentId&&(u.agentId=l.agentId),l.initiativeId&&(u.initiativeId=l.initiativeId,u.groupId=l.initiativeId,u.groupLabel=Vr(l.initiativeId)),(!u.title||u.title.length<4)&&(u.title=l.title)),l.type==="blocker_created"&&l.description&&(u.blockers.includes(l.description)||u.blockers.push(l.description))}for(const l of t??[]){const d=l.runId??`agent:${l.id}`,u=r.get(d),p=fd(l.status),x=new Date().toISOString(),b=hd(l,p),g=l.startedAt??(b?x:null),j=l.initiativeId??null,y=l.currentTask&&l.currentTask.trim().length>0?l.currentTask.trim():`${l.name??l.id} ${p==="archived"?"idle":p}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:y,agentId:l.id,agentName:l.name??l.id,status:p,progress:null,initiativeId:j,workstreamId:null,groupId:j??"unscoped",groupLabel:Vr(j),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:l.currentTask,blockers:Ui(l.blockers)});continue}!u.agentName&&l.name&&(u.agentName=l.name),u.agentId||(u.agentId=l.id),(!u.title||u.title===u.runId)&&(u.title=y),b&&(u.updatedAt=g??u.updatedAt??x,u.lastEventAt=g??u.lastEventAt??x),u.status==="archived"&&p!=="archived"&&(u.status=p),Ui(l.blockers).length>0&&(u.blockers=Ui(l.blockers)),j&&!u.initiativeId&&(u.initiativeId=j,u.groupId=j,u.groupLabel=Vr(j))}const a=Array.from(r.values()).sort(vi).slice(0,s),c=new Map;for(const l of a)c.has(l.groupId)||c.set(l.groupId,{id:l.groupId,label:l.groupLabel,status:l.status});return{nodes:a,edges:[],groups:Array.from(c.values())}}async function xd(e,t,s){var p;const r=Number.isFinite(s.timeoutMs)?Math.max(100,Math.floor(s.timeoutMs)):0,i=r>0?new AbortController:null,a=t==null?void 0:t.signal,c=(i==null?void 0:i.signal)??a,l=c?{...t??{},signal:c}:t??{};let d=null,u=null;if(i){if(a!=null&&a.aborted)i.abort();else if(a){const x=()=>i.abort();a.addEventListener("abort",x,{once:!0}),u=()=>a.removeEventListener("abort",x)}d=setTimeout(()=>i.abort(),r)}try{const x=await fetch(e,l),g=(((p=x.headers.get("content-type"))==null?void 0:p.toLowerCase())??"").includes("application/json");if(!x.ok){let j=`${x.status} ${x.statusText}`;if(g){const y=await x.json().catch(()=>null);y!=null&&y.error&&(j=`${x.status} ${y.error}`)}else{const y=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);y.length>0&&(j=`${x.status} ${y}`)}return{ok:!1,status:x.status,data:null,error:j}}if(!g){const j=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:x.status,data:null,error:`Unexpected content type for ${e}${j?`: ${j}`:""}`}}return{ok:!0,status:x.status,data:await x.json(),error:null}}catch(x){const b=x instanceof Error?x.message:"Network error",g=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return x instanceof DOMException&&x.name==="AbortError"||rd(b)?{ok:!1,status:0,data:null,error:g&&r>0?`request timed out after ${r}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:b}}finally{d&&clearTimeout(d),u&&u()}}function yd(e,t,s,r,i=[],a=Ta,c=null,l=1,d=[],u=Os,p){var j,y,I;const x=((j=t[0])==null?void 0:j.timestamp)??null,b=((y=r[0])==null?void 0:y.requestedAt)??((I=r[0])==null?void 0:I.updatedAt)??null,g=wt(x)>=wt(b)?x:b;return{connection:"connected",lastActivity:g?$t(g):null,lastSnapshotAt:c,snapshotVersion:l,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:El(a),chat:ui(u),runtimeInstances:d,workSliceProjections:(p==null?void 0:p.workSliceProjections)??[],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}}function go(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 r=s.id.trim();r&&t.set(r,s)}return Array.from(t.values()).sort((s,r)=>wt(r.lastEventAt??r.lastHeartbeatAt)-wt(s.lastEventAt??s.lastHeartbeatAt))}function xo(e,t){const s=e??[],r=t??[];if(s.length!==r.length)return!1;for(let i=0;i<s.length;i+=1)if(s[i].id!==r[i].id||s[i].state!==r[i].state||s[i].lastEventAt!==r[i].lastEventAt||s[i].runId!==r[i].runId||s[i].progressPct!==r[i].progressPct)return!1;return!0}function bd(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 r=s.id.trim();r&&t.set(r,{...s,id:r,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,r)=>wt(r.lastActivityAt??r.updatedAt)-wt(s.lastActivityAt??s.updatedAt))}function ui(e){if(!e||typeof e!="object")return Os;const t=bd(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 wd(e,t){const s=e??Os,r=t??Os;if(s.total!==r.total||s.updatedAt!==r.updatedAt||s.threads.length!==r.threads.length)return!1;for(let i=0;i<s.threads.length;i+=1){const a=s.threads[i],c=r.threads[i];if(a.id!==c.id||a.status!==c.status||a.lastActivityAt!==c.lastActivityAt||a.lastSnippet!==c.lastSnippet||a.assigneeId!==c.assigneeId||a.launchCount!==c.launchCount||a.messageCount!==c.messageCount)return!1}return!0}function mi(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(r,i)=>{const a=[],c=l=>{if(typeof l!="string")return;const d=l.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(r))for(const l of r)c(l);else if(typeof r=="string")for(const l of r.split(/[\n,;]+/g))c(l);return i&&c(i),a};for(const r of e){if(!r||typeof r!="object")continue;const i=typeof r.sliceRunId=="string"&&r.sliceRunId.trim().length>0?r.sliceRunId.trim():typeof r.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!i)continue;const a=s(r.initiativeIds,r.initiativeId??null),c=s(r.workstreamIds,r.workstreamId??null),l=s(r.iwmtIds,r.iwmtId??null),d=typeof r.initiativeId=="string"&&r.initiativeId.trim().length>0?r.initiativeId.trim():a[0]??null,u=typeof r.workstreamId=="string"&&r.workstreamId.trim().length>0?r.workstreamId.trim():c[0]??null,p=typeof r.iwmtId=="string"&&r.iwmtId.trim().length>0?r.iwmtId.trim():l[0]??null;t.set(i,{...r,id:i,sliceRunId:i,initiativeId:d,initiativeIds:a,workstreamId:u,workstreamIds:c,iwmtId:p,iwmtIds:l,artifacts:Array.isArray(r.artifacts)?r.artifacts:[],decisionOptions:Array.isArray(r.decisionOptions)?r.decisionOptions:[],taskIds:Array.isArray(r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r.milestoneIds)?r.milestoneIds:[]})}return Array.from(t.values()).sort((r,i)=>wt(i.updatedAt??i.lastEventAt)-wt(r.updatedAt??r.lastEventAt))}function Kr(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 r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!r)continue;const i=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(r,{...s,sliceRunId:r,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(i==null?void 0:i.initiativeIds)?i.initiativeIds:[],initiativeTitles:Array.isArray(i==null?void 0:i.initiativeTitles)?i.initiativeTitles:[],workstreamIds:Array.isArray(i==null?void 0:i.workstreamIds)?i.workstreamIds:[],workstreamTitles:Array.isArray(i==null?void 0:i.workstreamTitles)?i.workstreamTitles:[],taskIds:Array.isArray(i==null?void 0:i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i==null?void 0:i.milestoneIds)?i.milestoneIds:[],iwmtIds:Array.isArray(i==null?void 0:i.iwmtIds)?i.iwmtIds:[],sliceRunId:r,sessionId:typeof(i==null?void 0:i.sessionId)=="string"?i.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,r)=>wt(r.updatedAt??r.completedAt??r.failedAt)-wt(s.updatedAt??s.completedAt??s.failedAt))}function Hi(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 r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;r&&t.set(r,{...s,sliceRunId:r,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,r)=>wt(r.occurredAt)-wt(s.occurredAt))}function Vi(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 yo(e){var s;if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const r of e){if(r.sliceKind!=="work_slice")continue;const i=r.lineage.initiativeIds[0]??null,a=r.lineage.workstreamIds[0]??null,c=r.lineage.workstreamTitles[0]??r.lineage.workstreamIds[0]??null,l=r.lifecycleState==="completed"&&r.outcomeState==="succeeded_without_artifacts"?"needs_review":r.lifecycleState,d=((s=r.actionContract)==null?void 0:s.actionType)??null,u=d==="open_artifact"||d==="open_logs"||d==="open_session"||d==="open_run"||d==="open_workstream"||d==="open_task"||d==="open_initiative"||d==="open_pr"||d==="open_diff"||d==="open_branch"?"open_artifact":d==="approve"||d==="reject"||d==="provide_context"||d==="request_info"||d==="confirm_scope"||d==="connect_provider"||d==="refresh_credentials"||d==="reassign"||d==="escalate"?"resolve_decision":d==="retry"||d==="resume"||d==="start"||d==="auto_fix"?"retry_slice":r.outcomeState==="succeeded_without_artifacts"?"review_output":"none";t.push({id:r.sliceRunId,sliceRunId:r.sliceRunId,runId:r.runId,initiativeId:i,initiativeIds:r.lineage.initiativeIds,workstreamId:a,workstreamIds:r.lineage.workstreamIds,iwmtId:r.lineage.iwmtIds[0]??null,iwmtIds:r.lineage.iwmtIds,workstreamTitle:c,taskIds:r.lineage.taskIds,milestoneIds:r.lineage.milestoneIds,status:l,statusExplainer:r.statusExplainer,primaryAction:u,hasArtifact:r.hasArtifact,artifactCount:r.artifactCount,artifacts:r.artifacts.map(p=>({id:p.artifactId,type:p.type,title:p.title,url:p.url,createdAt:p.producedAt})),decisionCount:r.outcomeState==="needs_input"?1:0,blockingDecisionCount:r.outcomeState==="needs_input"?1:0,decisionOptions:[],sourceClient:r.sourceClient,runtimeState:r.runtimeState,startedAt:null,updatedAt:r.updatedAt,completedAt:r.completedAt,failedAt:r.failedAt,archivedAt:r.archivedAt,lastEventAt:r.updatedAt,lastEventSummary:r.statusExplainer,correlationId:r.sliceRunId,confidence:r.confidence})}return mi(t)}function vd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.status!==i.status||r.updatedAt!==i.updatedAt||r.lastEventAt!==i.lastEventAt||r.artifactCount!==i.artifactCount||r.decisionCount!==i.decisionCount||r.blockingDecisionCount!==i.blockingDecisionCount||r.runtimeState!==i.runtimeState)return!1}return!0}function kd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.lifecycleState!==i.lifecycleState||r.outcomeState!==i.outcomeState||r.updatedAt!==i.updatedAt||r.artifactCount!==i.artifactCount||r.lineage.sessionId!==i.lineage.sessionId)return!1}return!0}function jd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.occurredAt!==i.occurredAt||r.outcome.state!==i.outcome.state||r.outcome.artifactCount!==i.outcome.artifactCount)return!1}return!0}function Nd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.initiativeId!==i.initiativeId||r.pendingCount!==i.pendingCount||r.queue.length!==i.queue.length)return!1}return!0}function Id(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 Ad(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 _d(e={}){const{enabled:t=!0,pollInterval:s=Gc,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=Xc,maxActivityItems:d=Qc,maxHandoffs:u=Jc,maxDecisions:p=Yc,batchWindowMs:x=Zc}=e,b=typeof a=="string"&&a.trim().length>0?a.trim():null,g=typeof c=="string"&&c.trim().length>0?c.trim():null,[j,y]=o.useState(eo()),[I,k]=o.useState(Wr),[N,h]=o.useState(!r),[C,V]=o.useState(null),te=o.useRef(),z=o.useRef(null),Ie=o.useRef(null),[B,ee]=o.useState(!1),be=o.useRef(0),ve=o.useRef(!1),Ae=o.useRef(`${b??"__all__"}::${g??"__all__"}`),ue=o.useRef(!1),Ke=o.useRef(null),pe=o.useCallback((P,H)=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null),k(P),H!=null&&H.autoResetMs&&H.autoResetMs>0&&(Ke.current=setTimeout(()=>{Ke.current=null,k(Wr)},H.autoResetMs))},[]);o.useEffect(()=>()=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null)},[]),o.useEffect(()=>{const P=`${b??"__all__"}::${g??"__all__"}`;Ae.current!==P&&(Ae.current=P,ue.current=!0,pe(Wr),y(H=>({...H,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Os,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(H.snapshotVersion??0)+1})),h(!0),V(null))},[b,g,pe]);const ae=o.useCallback((P,H,Q,ge=null,ke=null,se=null,ye=null,he=null,L=null,q=null)=>{be.current=Date.now(),ve.current=!1,y(G=>{const re=ue.current;re&&(ue.current=!1);const Re=H===null?re?[]:G.activity:Wi(H,d),Ge=Q===null?re?[]:G.handoffs:co(Q,u),Ee=hr(P===null?re?{nodes:[],edges:[],groups:[]}:G.sessions:re?hr(P,l):lo(G.sessions,hr(P,l)),l),$=ge===null?re?[]:G.decisions:fo(ge,p),rt=ke===null?re?[]:G.sliceRuns:mi(ke),Le=se===null?re?Ta:G.outbox:El(se),Xe=he===null?re?[]:G.runtimeInstances??[]:go(he),kt=L===null?re?Os:G.chat??Os:ui(L),jt=(q==null?void 0:q.workSliceProjections)==null?re?[]:G.workSliceProjections??[]:Kr(q.workSliceProjections),Nt=(q==null?void 0:q.timelineNarrative)==null?re?[]:G.timelineNarrative??[]:Hi(q.timelineNarrative),O=(q==null?void 0:q.nextUpByInitiative)==null?re?[]:G.nextUpByInitiative??[]:Vi(q.nextUpByInitiative),_e=typeof(q==null?void 0:q.runningWorkSlices)=="number"&&Number.isFinite(q.runningWorkSlices)?Math.max(0,Math.floor(q.runningWorkSlices)):G.runningWorkSlices??0,fe=typeof(q==null?void 0:q.needsInputTotal)=="number"&&Number.isFinite(q.needsInputTotal)?Math.max(0,Math.floor(q.needsInputTotal)):G.needsInputTotal??0,Te=typeof(q==null?void 0:q.failedActionableTotal)=="number"&&Number.isFinite(q.failedActionableTotal)?Math.max(0,Math.floor(q.failedActionableTotal)):G.failedActionableTotal??0,Qe=typeof(q==null?void 0:q.completedTodayTotal)=="number"&&Number.isFinite(q.completedTodayTotal)?Math.max(0,Math.floor(q.completedTodayTotal)):G.completedTodayTotal??0,tt=(q==null?void 0:q.consistencyFlags)==null?G.consistencyFlags??[]:q.consistencyFlags.filter(we=>typeof we=="string"),Y=(q==null?void 0:q.dataHealth)===void 0||(q==null?void 0:q.dataHealth)===null?G.dataHealth:q.dataHealth,We=(G.snapshotVersion??0)+1;return uo(G.sessions,Ee)&&Tl(G.activity,Re)&&mo(G.handoffs,Ge)&&po(G.decisions,$)&&vd(G.sliceRuns,rt)&&dd(G.outbox,Le)&&wd(G.chat,kt)&&xo(G.runtimeInstances,Xe)&&kd(G.workSliceProjections??[],jt)&&jd(G.timelineNarrative??[],Nt)&&Nd(G.nextUpByInitiative??[],O)&&(G.runningWorkSlices??0)===_e&&(G.needsInputTotal??0)===fe&&(G.failedActionableTotal??0)===Te&&(G.completedTodayTotal??0)===Qe&&Id(G.consistencyFlags??[],tt)&&Ad(G.dataHealth,Y)&&G.lastSnapshotAt===ye&&G.connection==="connected"?G:yd(Ee,Re,Ge,$,rt,Le,ye,We,Xe,kt,{workSliceProjections:jt,timelineNarrative:Nt,nextUpByInitiative:O,runningWorkSlices:_e,needsInputTotal:fe,failedActionableTotal:Te,completedTodayTotal:Qe,consistencyFlags:tt,dataHealth:Y})}),h(!1)},[d,p,u,l]),ne=o.useCallback(async()=>{if(!t){y(Q=>Q.connection==="disconnected"?Q:{...Q,connection:"disconnected"}),h(!1),V(null);return}const P=`${b??"__all__"}::${g??"__all__"}`;if(z.current&&Ie.current===P)return z.current;if(r){y(eo()),h(!1);return}const H=(async()=>{try{const Q=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});g&&Ns(Q,g),b&&Q.set("initiative",b);const ge=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${Q.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${Q.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${Q.toString()}`}],ke=[];let se=null,ye=!1;for(let De=0;De<ge.length;De+=1){const st=ge[De];De>0&&await new Promise(Ct=>{setTimeout(Ct,td)});const dt=await xd(st.url,{headers:Ot({workspaceId:g})},{timeoutMs:ed});if(dt.ok&&dt.data){se=dt.data;break}(dt.status===401||dt.status===403)&&(ye=!0),ke.push(`${st.label}: ${dt.error??"unavailable"}`)}if(!se){if(ye){const De=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw De.code="ORGX_AUTH",De}throw new Error(id(ke))}if(Ae.current!==P)return;const he=Array.isArray(se.degraded)?se.degraded.filter(De=>typeof De=="string"):[],L=he.map(De=>De.toLowerCase()),q=(...De)=>L.some(st=>De.some(dt=>st.includes(dt))),G=Array.isArray(se.activity)?se.activity:[],re=Array.isArray(se.handoffs)?se.handoffs:[],Re=Array.isArray(se.decisions)?se.decisions:[],Ge=G.length===0&&q("activity unavailable","activity local fallback failed"),Ee=q("sessions unavailable","sessions local fallback failed"),$=re.length===0&&q("handoffs unavailable"),rt=Re.length===0&&q("decisions unavailable"),Le=Kr(Array.isArray(se.projections)?se.projections:[]),Xe=ui(se.chat??null),kt=Hi(Array.isArray(se.timelineNarrative)?se.timelineNarrative:[]),jt=Vi(Array.isArray(se.nextUpByInitiative)?se.nextUpByInitiative:[]),Nt=Le.length>0?yo(Le):mi(Array.isArray(se.sliceRuns)?se.sliceRuns:[]),O=se.sessions&&Array.isArray(se.sessions.nodes)&&Array.isArray(se.sessions.edges)&&Array.isArray(se.sessions.groups)?se.sessions:gd(G,se.agents,l),_e=Nt.length===0&&Le.length===0&&q("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),fe=jt.length===0&&q("next-up unavailable","next-up queue"),Te=Ge?null:G,Qe=$?null:re,tt=rt?null:Re,Y=Ee&&O.nodes.length===0?null:O,We=_e?null:Le,we=_e?null:kt,X=_e?null:Nt,$e=fe?null:jt;ae(Y,Te,Qe,tt,X,se.outbox??null,se.generatedAt??null,se.runtimeInstances??null,Xe,{workSliceProjections:We,timelineNarrative:we,nextUpByInitiative:$e,runningWorkSlices:_e?null:se.runningWorkSlices??null,needsInputTotal:_e?null:se.needsInput??null,failedActionableTotal:_e?null:se.failedActionable??null,completedTodayTotal:_e?null:se.completedToday??null,consistencyFlags:Array.isArray(se.consistencyFlags)?se.consistencyFlags:null,dataHealth:se.dataHealth??null});const He=he.length>0?od(he):[];He.length>0?(V(`Partial live data: ${He.join("; ")}`),y(De=>De.connection==="connected"?De:{...De,connection:"connected"}),ee(!1)):(V(null),y(De=>De.connection==="connected"?De:{...De,connection:"connected"}))}catch(Q){if(Ae.current!==P)return;const ge=Q instanceof Error?Q.message:"Unknown error",ke=!!(Q&&typeof Q=="object"&&"code"in Q&&Q.code==="ORGX_AUTH");ke&&(ve.current=!0);const se=be.current>0&&Date.now()-be.current>ro;V(ge),y(ye=>{const he=ke||se?"disconnected":"reconnecting";return ye.connection===he?ye:{...ye,connection:he}}),ee(!ke),h(!1)}finally{Ie.current===P&&(z.current=null,Ie.current=null)}})();return z.current=H,Ie.current=P,H},[ae,t,i,d,p,u,l,g,b,r]),ie=o.useCallback(async(P,H,Q)=>{var L,q,G;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const ge=Array.from(new Set(P.filter(Boolean)));if(ge.length===0)return{updated:0,failed:0};const ke=((L=Q==null?void 0:Q.note)==null?void 0:L.trim())||void 0,se=((q=Q==null?void 0:Q.optionId)==null?void 0:q.trim())||void 0;if(r){const re=new Set(ge);return y(Re=>{const Ge=Re.decisions.filter(Le=>re.has(Le.id));if(Ge.length===0)return Re;const Ee=new Date().toISOString(),$=Ge.map(Le=>({id:`decision:${H}:${Le.id}:${Date.now()}`,type:"decision_resolved",title:H==="approve"?`Approved: ${Le.title}`:`Rejected: ${Le.title}`,description:Le.context,agentId:null,agentName:Le.agentName,requesterAgentId:null,requesterAgentName:Le.agentName??null,executorAgentId:null,executorAgentName:Le.agentName??null,runId:null,initiativeId:null,timestamp:Ee,metadata:{decisionId:Le.id,action:H}})),rt=Wi($.concat(Re.activity),d);return{...Re,decisions:Re.decisions.filter(Le=>!re.has(Le.id)),activity:rt,lastActivity:$t(Ee)}}),{updated:re.size,failed:0,firstError:void 0}}const ye=new Date().toISOString(),he=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ot({contentTypeJson:!0,workspaceId:g}),body:JSON.stringify({ids:ge,action:H,...ke?{note:ke}:{},...se?{option_id:se}:{}})});try{const re=await he.json().catch(()=>null),Re=Array.isArray(re==null?void 0:re.results)?re.results:[],Ge=new Set(Re.filter(Xe=>Xe.ok).map(Xe=>Xe.id)),$=((G=Re.filter(Xe=>!Xe.ok).find(Xe=>typeof Xe.error=="string"&&Xe.error.trim().length>0))==null?void 0:G.error)??(typeof(re==null?void 0:re.error)=="string"&&re.error.trim().length>0?re.error:void 0);if(!he.ok&&he.status!==207){const Xe=$??`Decision action failed (${he.status})`;throw new Error(Xe)}if(Ge.size===0&&he.ok&&((re==null?void 0:re.failed)??0)===0)for(const Xe of ge)Ge.add(Xe);Ge.size>0?y(Xe=>{const kt=Xe.decisions.filter(fe=>Ge.has(fe.id));if(kt.length===0)return Xe;const jt=new Date().toISOString(),Nt=kt.map(fe=>({id:`decision:${H}:${fe.id}:${Date.now()}`,type:"decision_resolved",title:H==="approve"?`Approved: ${fe.title}`:`Rejected: ${fe.title}`,description:fe.context,agentId:null,agentName:fe.agentName,requesterAgentId:null,requesterAgentName:fe.agentName??null,executorAgentId:null,executorAgentName:fe.agentName??null,runId:null,initiativeId:null,timestamp:jt,metadata:{decisionId:fe.id,action:H}})),O=Wi(Nt.concat(Xe.activity),d);return{...Xe,decisions:Xe.decisions.filter(fe=>!Ge.has(fe.id)),activity:O,lastActivity:$t(jt)}}):he.ok&&ge.length>0&&y(Xe=>({...Xe,decisions:Xe.decisions.filter(kt=>!ge.includes(kt.id))})),ne();const rt=(re==null?void 0:re.updated)??Ge.size,Le=(re==null?void 0:re.failed)??Math.max(0,ge.length-Ge.size);return pe({phase:Le>0?"error":"success",action:H,targetCount:ge.length,message:Le>0?`${H==="approve"?"Approve":"Reject"} completed with ${Le} failure${Le===1?"":"s"}.`:H==="approve"?`Approved ${rt} decision${rt===1?"":"s"}.`:`Rejected ${rt} decision${rt===1?"":"s"}.`,startedAt:ye,completedAt:new Date().toISOString()},{autoResetMs:Le>0?8e3:4e3}),{updated:rt,failed:Le,firstError:$}}catch(re){throw pe({phase:"error",action:H,targetCount:ge.length,message:re instanceof Error?re.message:"Decision update failed.",startedAt:ye,completedAt:new Date().toISOString()}),re}},[i,ne,d,g,pe,r]),xe=o.useCallback(async(P,H)=>ie([P],"approve",H),[ie]),K=o.useCallback(async(P,H)=>ie([P],"reject",H),[ie]),R=o.useCallback(async()=>{let P=[];return y(H=>(P=H.decisions.map(Q=>Q.id),H)),P.length===0?{updated:0,failed:0}:ie(P,"approve")},[ie]),U=o.useCallback(async(P,H,Q)=>ie(P,H,Q?{note:Q}:void 0),[ie]);return o.useEffect(()=>{i||pe(Wr)},[i,pe]),o.useEffect(()=>{if(!t){ee(!1),h(!1),V(null);return}if(r){ne();return}if(ne(),g){ee(!0);return}const P=new URLSearchParams;g&&Ns(P,g),b&&P.set("initiative",b);const H=P.toString()?`/orgx/api/live/stream?${P.toString()}`:"/orgx/api/live/stream",Q=new EventSource(H),ge=new EventSource("/orgx/api/hooks/runtime/stream");let ke=null,se=null,ye=null,he=null,L=[],q=null,G;const re=()=>{if(G=void 0,ke){be.current=Date.now(),ve.current=!1;const Ee=ke;ke=null,ye=null,he=null,L=[],q=null,se=null,ae(Ee.sessions,Ee.activity,Ee.handoffs,Ee.decisions,Ee.sliceRuns,Ee.outbox,Ee.generatedAt,Ee.runtimeInstances,Ee.chat,Ee.v2);return}!ye&&!he&&!q&&!se&&L.length===0||(be.current=Date.now(),ve.current=!1,y(Ee=>{var rt;let $=Ee;if(ye){const Le=hr(ye,l),Xe=hr(lo($.sessions,Le),l);ye=null,uo($.sessions,Xe)||($={...$,sessions:Xe})}if(he){const Le=co(he,u);he=null,mo($.handoffs,Le)||($={...$,handoffs:Le})}if(q){const Le=fo(q,p);q=null,po($.decisions,Le)||($={...$,decisions:Le})}if(se){const Le=go(se);se=null,xo($.runtimeInstances,Le)||($={...$,runtimeInstances:Le})}if(L.length>0){const Le=pd($.activity,L,d);L=[],Le!==$.activity&&($={...$,activity:Le,lastActivity:(rt=Le[0])!=null&&rt.timestamp?$t(Le[0].timestamp):$.lastActivity})}return $===Ee?Ee:$.connection==="connected"?$:{...$,connection:"connected"}}),V(null),h(!1))},Re=()=>{G||(G=setTimeout(re,x))};Q.onopen=()=>{be.current=Date.now(),ve.current=!1,ee(!1),y(Ee=>Ee.connection==="connected"?Ee:{...Ee,connection:"connected"}),V(null)},Q.onerror=()=>{if(ve.current){y($=>$.connection==="disconnected"?$:{...$,connection:"disconnected"}),ee(!1);return}const Ee=be.current>0&&Date.now()-be.current>ro;y($=>$.connection===(Ee?"disconnected":"reconnecting")?$:{...$,connection:Ee?"disconnected":"reconnecting"}),ee(!0)},Q.addEventListener("snapshot",Ee=>{try{const $=JSON.parse(Ee.data),rt=typeof $.generatedAt=="string"&&$.generatedAt.length>0?$.generatedAt:new Date().toISOString();ke={sessions:$.sessions,activity:$.activity??[],handoffs:$.handoffs??[],decisions:$.decisions??null,sliceRuns:Array.isArray($.sliceRuns)?mi($.sliceRuns):Array.isArray($.projections)?yo(Kr($.projections)):null,outbox:$.outbox??null,generatedAt:rt,runtimeInstances:Array.isArray($.runtimeInstances)?$.runtimeInstances:null,chat:ui($.chat??null),v2:{workSliceProjections:Array.isArray($.projections)?Kr($.projections):null,timelineNarrative:Array.isArray($.timelineNarrative)?Hi($.timelineNarrative):null,nextUpByInitiative:Array.isArray($.nextUpByInitiative)?Vi($.nextUpByInitiative):null,runningWorkSlices:typeof $.runningWorkSlices=="number"?$.runningWorkSlices:null,needsInputTotal:typeof $.needsInput=="number"?$.needsInput:null,failedActionableTotal:typeof $.failedActionable=="number"?$.failedActionable:null,completedTodayTotal:typeof $.completedToday=="number"?$.completedToday:null,consistencyFlags:Array.isArray($.consistencyFlags)?$.consistencyFlags:null,dataHealth:$.dataHealth??null}},Re()}catch($){V($ instanceof Error?$.message:"Invalid snapshot")}}),Q.addEventListener("activity.appended",Ee=>{try{const $=JSON.parse(Ee.data);if($.length===0)return;L=L.concat($),Re()}catch{}}),Q.addEventListener("session.updated",Ee=>{try{ye=JSON.parse(Ee.data),Re()}catch{}});const Ge=Ee=>{try{const $=JSON.parse(Ee.data);se=Array.isArray($)?$:[$],Re()}catch{}};return Q.addEventListener("runtime.updated",Ge),ge.addEventListener("runtime.updated",Ge),Q.addEventListener("handoff.updated",Ee=>{try{he=JSON.parse(Ee.data),Re()}catch{}}),Q.addEventListener("decision.updated",Ee=>{try{q=JSON.parse(Ee.data),Re()}catch{}}),()=>{G&&clearTimeout(G),Q.close(),ge.close()}},[ae,x,t,i,ne,d,p,u,l,b,g,r]),o.useEffect(()=>{if(!(!t||r||(te.current&&clearInterval(te.current),!B&&!!!g)))return te.current=setInterval(ne,s),()=>{te.current&&clearInterval(te.current)}},[t,ne,g,s,B,r]),{data:j,isLoading:N,error:C,refetch:ne,approveDecision:xe,rejectDecision:K,approveAllDecisions:R,bulkDecisionAction:U,decisionMutation:I}}const Mr=[{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 Ll(e){return Mr.find(t=>t.id===e)??Mr[0]}function Lr(e,t=Date.now()){if(e==="all")return null;if(e==="live")return t-60*6e4;if(e==="24h"){const r=new Date(t);return r.setHours(0,0,0,0),r.getTime()}if(e==="custom")return null;const s=Mr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Sd(e,t=Date.now()){const s=Lr(e,t);return s?new Date(s).toISOString():null}const Cd=new Set(["ungrouped","unscoped","unknown"]),Md="orgx.demo_mode",Td="orgx.show_synthetic_entities";function zs(e){const t=(e??"").trim().toLowerCase();return!!(!t||Cd.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Gt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Md)==="1"}catch{return!1}}function Ed(){if(typeof window>"u")return!1;if(Gt())return!0;try{return window.localStorage.getItem(Td)==="1"}catch{return!1}}function Rd(e){return Gt()?!0:!zs(e)}function wa(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function $l(e,t){const s=wa(t.timestamp)-wa(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function Ld(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $d(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function Dl(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=Ld(e.metadata);return $d(s,["initiative_id","initiativeId"])}function Ki(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function va(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 c=0;c<e.length;c+=1)if(!va(e[c],t[c]))return!1;return!0}const s=e,r=t,i=Object.keys(s).sort(),a=Object.keys(r).sort();if(i.length!==a.length)return!1;for(let c=0;c<i.length;c+=1){const l=i[c];if(l!==a[c]||!va(s[l],r[l]))return!1}return!0}const Dd=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function nr(e,...t){}function Fd(e,t,s,r){const i=new Map,a=t.sinceEpoch,c=t.untilEpoch;let l=0,d=0,u=0;for(const p of e??[]){if(!p||typeof p.id!="string")continue;if(s&&p.runId!==s){l++;continue}if(r&&Dl(p)!==r){d++;continue}const x=wa(p.timestamp);if(x){if(a!==null&&x<a){u++;continue}if(c!==null&&x>c){u++;continue}i.set(p.id,p)}}return nr("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:i.size,runId:s,initiativeId:r,skippedRun:l,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:c?new Date(c).toISOString():null}),Array.from(i.values()).sort($l)}function bo(e,t){if(t.length===0)return e;const s=new Map;for(const c of e)s.set(c.id,c);let r=0,i=0,a=!1;for(const c of t){const l=s.get(c.id);if(!l){s.set(c.id,c),a=!0,r++;continue}(l.timestamp!==c.timestamp||l.type!==c.type||l.title!==c.title||l.description!==c.description||l.summary!==c.summary||!va(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return nr("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort($l):e}function Pd(e){const{seed:t,timeFilterId:s,customSinceIso:r=null,customUntilIso:i=null,runId:a=null,initiativeId:c=null,projectId:l=null,pageSize:d=50,demoMode:u=Gt()}=e,p=o.useMemo(()=>Ki(a),[a]),x=o.useMemo(()=>Ki(c),[c]),b=o.useMemo(()=>Ki(l),[l]),g=o.useMemo(()=>Lr(s),[s]),j=o.useMemo(()=>Sd(s),[s]),y=o.useMemo(()=>{if(s==="custom"){const R=(r==null?void 0:r.trim())??"";return R.length>0?R:null}return j},[r,j,s]),I=o.useMemo(()=>{if(s!=="custom")return null;const R=(i==null?void 0:i.trim())??"";return R.length>0?R:null},[i,s]),k=o.useMemo(()=>{if(y){const R=Date.parse(y);if(Number.isFinite(R))return R}return g},[g,y]),N=o.useMemo(()=>{if(!I)return null;const R=Date.parse(I);return Number.isFinite(R)?R:null},[I]),h=o.useMemo(()=>Fd(t,{sinceEpoch:k,untilEpoch:N},p,x),[t,k,N,p,x]),C=u?null:"",[V,te]=o.useState(h),[z,Ie]=o.useState(()=>C),[B,ee]=o.useState(!1),[be,ve]=o.useState(null),[Ae,ue]=o.useState(null),Ke=o.useRef(null),pe=o.useRef(!1),ae=o.useRef(h);ae.current=h;const ne=o.useMemo(()=>`${p??""}|${x??""}|${s}|${y??""}|${I??""}|${b??""}|${u?"demo":"live"}`,[p,x,s,y,I,b,u]),ie=o.useRef(ne);o.useEffect(()=>{ie.current!==ne&&(ie.current=ne,nr("RESET",{reason:"filter/run change",runId:p,initiativeId:x,projectId:b,timeFilterId:s,sinceIso:y,untilIso:I,seedCount:ae.current.length}),te(ae.current),Ie(C),ve(null),ue(null),pe.current=!1)},[ne,C,p,x,b,s,y,I]),o.useEffect(()=>{te(R=>{const U=bo(R,h);return U!==R&&nr("SSE_MERGE",{prevCount:R.length,seedCount:h.length,nextCount:U.length,delta:U.length-R.length}),U})},[h]);const xe=o.useCallback(async()=>{if(u){Ie(null),ve(null);return}if(z===null)return;if(Ke.current)return Ke.current;ee(!0);const R=(async()=>{try{const U=new URLSearchParams;U.set("limit",String(Math.max(1,Math.min(500,d)))),z.trim().length>0&&U.set("cursor",z),y&&U.set("since",y),I&&U.set("until",I),p&&U.set("run",p),x&&U.set("initiative",x),b&&Ns(U,b);const P=await fetch(`/orgx/api/live/activity/page?${U.toString()}`,{headers:Ot({workspaceId:b})}),H=await P.json().catch(()=>null);if(!P.ok||!H){const ke=typeof(H==null?void 0:H.error)=="string"&&H.error.trim()||typeof(H==null?void 0:H.message)=="string"&&H.message.trim()||`Activity paging failed (${P.status})`;throw new Error(ke)}const Q=Array.isArray(H.activities)?H.activities:[],ge=Q.filter(ke=>!x||Dl(ke)===x);nr("PAGE_FETCH",{cursor:z,rawCount:Q.length,afterFilter:ge.length,filteredOut:Q.length-ge.length,initiativeId:x,runId:p,nextCursor:H.nextCursor??null}),te(ke=>{const se=bo(ke,ge);return nr("PAGE_MERGE",{prevCount:ke.length,pageCount:ge.length,nextCount:se.length,added:se.length-ke.length}),se}),Ie(H.nextCursor??null),ue(H.storeUpdatedAt??null),ve(null)}catch(U){const P=U instanceof Error?U.message:"";ve(P?Wt(P):"Activity paging failed"),Ie(H=>H===""?null:H)}finally{ee(!1),Ke.current=null}})();return Ke.current=R,R},[z,u,x,d,b,p,y,I]);return o.useEffect(()=>{z===""&&(pe.current||(pe.current=!0,xe()))},[z,xe]),{items:V,hasMore:z!==null,isLoadingMore:B,error:be,storeUpdatedAt:Ae,loadMore:xe,cutoffEpoch:k,sinceIso:y,untilIso:I}}const Od="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Bd="".trim().toLowerCase()==="true"||"".trim()==="1",qd="".trim().toLowerCase()==="true"||"".trim()==="1",zd={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Gi=null,wo=!1,vo=!1,Ea=!1;function Wd(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Mi(){return Ea||!Bd?!1:qd?!0:!Wd()}function Ud(){return Mi()?(Gi||(Gi=nn(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(Ea=!0,null))),Gi):Promise.resolve(null)}function Hd(e){if(wo)return!0;try{return e.init(Od,zd),wo=!0,!0}catch{return Ea=!0,!1}}async function Ra(){const e=await Ud();return!e||!Hd(e)?null:e}function Vd(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 Kd(){!Mi()||typeof window>"u"||vo||(vo=!0,Vd(()=>{Ra()}))}function Gd(e){if(!Mi())return;const t=e.trim();t&&Ra().then(s=>{if(s)try{s.identify(t)}catch{}})}function ys(e,t){Mi()&&e.trim()&&Ra().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const Xd="https://orgx.mintlify.site/guides/openclaw-plugin-setup",Qd=1500,Xi="orgx.onboarding.skip",Jd=680,Yd=`<!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>`,pi={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Xd,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Qs(){return{...pi,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function Qi(e){if(typeof e=="string")return Wt(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Wt(t.error);if(typeof t.message=="string")return Wt(t.message)}}async function gr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:Qi(s==null?void 0:s.error)??Qi(s==null?void 0:s.message)??Qi(s)??Wt(`Request failed (${t.status})`)}}function Gr(e){if(e)try{Gd(e)}catch{}}function Zd(){const[e,t]=o.useState(()=>Gt()?Qs():pi),[s,r]=o.useState(()=>!Gt()),[i,a]=o.useState(!1),[c,l]=o.useState(!1),d=o.useRef(null),[u,p]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Xi)==="1"),x=o.useCallback(async()=>{if(Gt()){const h=Qs();return t(h),h}const N=await gr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!N.ok||!N.data){const h=N.error??"Failed to load onboarding state",C={...pi,status:"error",lastError:h,nextAction:"retry"};return t(C),C}return Gr(N.data.installationId??null),t(N.data),N.data},[]);o.useEffect(()=>{if(Gt()){t(Qs()),r(!1);return}let N=!1;return(async()=>{r(!0);const h=await x();N||(t(h),r(!1))})(),()=>{N=!0}},[x]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const h=Math.max(900,e.pollIntervalMs??Qd),C=window.setInterval(async()=>{const V=await gr(fetch("/orgx/api/onboarding/status",{method:"GET"}));V.ok&&V.data&&(Gr(V.data.installationId??null),t(V.data))},h);return()=>{window.clearInterval(C)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(Xi,"1");return}window.localStorage.removeItem(Xi)}},[u]);const b=o.useCallback(()=>{if(typeof window>"u")return null;try{const N=window.open("","_blank");return N?(N.opener=null,N.document.title="Connecting to OrgX…",N.document.open(),N.document.write(Yd),N.document.close(),N):null}catch{return null}},[]),g=o.useCallback(async()=>{if(Gt()){const h=Qs();t(h);return}const N=b();d.current=N,a(!0);try{const h=await gr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),C=h.data;if(!h.ok||!(C!=null&&C.state)){N&&!N.closed&&N.close();const te=h.error??"Could not start pairing";t(z=>({...z,status:"error",lastError:te,nextAction:"enter_manual_key"}));return}t(C.state);const V=C.connectUrl;if(V){const te=d.current;let z=!1;if(te&&!te.closed)try{window.setTimeout(()=>{if(!te.closed)try{te.location.href=V}catch{}},Jd),z=!0}catch{z=!1}z||(z=!!window.open(V,"_blank","noopener,noreferrer")),z||t(Ie=>({...Ie,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[b]),j=o.useCallback(async N=>{if(Gt()){const h=Qs();return t(h),h}l(!0);try{const h=N.trim(),C=h.replace(/^[a-z]+_/i,""),V=Array.from(new Set([h,C?`oxk_${C}`:"",C?`orgx_${C}`:""].map(z=>z.trim()).filter(z=>z.length>0)));let te="Manual key validation failed";for(const z of V){const Ie={"Content-Type":"application/json","X-OrgX-Api-Key":z,Authorization:`Bearer ${z}`},B=await gr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:Ie,body:JSON.stringify({apiKey:z})}));if(B.ok&&B.data)return Gr(B.data.installationId??null),t(B.data),B.data;te=B.error??te}throw t(z=>({...z,status:"manual_key",lastError:te,nextAction:"enter_manual_key"})),new Error(te)}finally{l(!1)}},[]),y=o.useCallback(async()=>{if(Gt()){const C=Qs();return t(C),C}const N=await gr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(N.ok&&N.data)return Gr(N.data.installationId??null),t(N.data),N.data;const h={...pi,status:"idle"};return t(h),h},[]),I=o.useCallback(()=>{t(N=>({...N,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),k=o.useMemo(()=>Gt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:k,isLoading:s,isStarting:i,isSubmittingManual:c,refreshStatus:x,startPairing:g,submitManualKey:j,disconnect:y,skipGate:()=>p(!0),resumeGate:()=>p(!1),backToPairing:I,setManualMode:()=>t(N=>({...N,status:"manual_key",nextAction:"enter_manual_key"}))}}const vs={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,r){super(s);Un(this,"code","upgrade_required");Un(this,"currentPlan");Un(this,"requiredPlan");Un(this,"actions");this.name="UpgradeRequiredError",this.currentPlan=(r==null?void 0:r.currentPlan)??null,this.requiredPlan=((r==null?void 0:r.requiredPlan)??"starter").trim()||"starter",this.actions=(r==null?void 0:r.actions)??null}}function tu(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 Ag(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 Fl extends Error{constructor(s){super(s.message);Un(this,"status");Un(this,"code");Un(this,"errorLocation");Un(this,"retryable");Un(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 nu(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Tr(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function su(e,t){if(e.status!==404)return!1;const s=Tr(t,["error"])??"",r=Tr(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${r}`)}function ru(e,t,s){if(su(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 r=Tr(t,["error","message"])??`${s} (${e.status})`;return Wt(r)}function Ji(e,t,s){const r=nu(t),i=ru(e,r,s),a=Tr(r,["code"]),c=Tr(r,["error_location","errorLocation"]),l=r==null?void 0:r.retryable,d=typeof l=="boolean"?l:!1;return new Fl({message:i,status:e.status,code:a,errorLocation:c,retryable:d,details:r})}function _g(e){return e instanceof Fl}const iu=750;async function xr(e){return await e.json().catch(()=>null)}function au(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",r=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${r}`)}function ou(e,t,s){if(au(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 r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||s;return Wt(r)}function lu(e,t){const s=e instanceof Error?e.message:"",r=s.trim().toLowerCase();return r.includes("timed out")||r.includes("timeout")||r.includes("request cancelled")||r.includes("signal is aborted")?`${t}. Request timed out while waiting for queue data.`:r.includes("failed to fetch")||r.includes("network")?`${t}. Unable to reach the queue service right now.`:s?Wt(s):t}function cu(e){const t=new Date().toISOString(),s=[{initiativeId:"init-1",initiativeTitle:"Q4 Feature Ship",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:25,workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",workstreamStatus:"active",nextTaskId:"task-1",nextTaskTitle:"Polish timeline controls",nextTaskPriority:1,nextTaskDueAt:null,runnerAgentId:"dana",runnerAgentName:"Dana",runnerAgents:[{id:"dana",name:"Dana"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",autoContinue:{status:"running",activeTaskId:"task-1",activeRunId:"run-2",stopReason:null,updatedAt:t}},{initiativeId:"init-2",initiativeTitle:"Black Friday Email",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:50,workstreamId:"ws-9",workstreamTitle:"Email campaign generation",workstreamStatus:"queued",nextTaskId:"task-2",nextTaskTitle:"Draft launch variants",nextTaskPriority:2,nextTaskDueAt:null,runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",autoContinue:{status:"stopped",activeTaskId:null,activeRunId:null,stopReason:null,updatedAt:t}}],r=typeof e=="string"&&e.trim().length>0?s.filter(i=>i.initiativeId===e.trim()):s;return fi({ok:!0,generatedAt:t,total:r.length,items:r,pagination:{offset:0,limit:r.length||1,total:r.length,nextCursor:null,hasMore:!1},degraded:[]})}function du(e){var s,r;const t=((s=e.autoContinue)==null?void 0:s.status)??"stopped";return t==="running"?"running":t==="stopping"?"stopping":((r=e.autoContinue)==null?void 0:r.stopReason)==="error"?"error":"idle"}function uu(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function La(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 $a(e,t){const s=typeof e=="string"?e.trim():"";if(!s)return t==="unassigned"?"Unassigned":t;const r=s.toLowerCase();return r==="undefined"||r==="null"||r==="main"&&t==="unassigned"?t==="unassigned"?"Unassigned":t:s}function Pl(e,t,s){if(!Array.isArray(e))return t==="unassigned"?[]:[{id:t,name:s}];const r=[],i=new Set;for(const a of e){if(!a||typeof a!="object"||Array.isArray(a))continue;const c=a,l=La(typeof c.id=="string"?c.id:null),d=$a(typeof c.name=="string"?c.name:null,l);if(l==="unassigned"&&d==="Unassigned")continue;const u=l.toLowerCase();i.has(u)||(i.add(u),r.push({id:l,name:d}))}return r.length===0&&t!=="unassigned"?[{id:t,name:s}]:r}function mu(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function pu(e){const t=La(e.runnerAgentId),s=$a(e.runnerAgentName,t),r=Pl(e.runnerAgents,t,s),i=r[0]??null,a=(i==null?void 0:i.id)??t,c=(i==null?void 0:i.name)??s,l=mu(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(p=>typeof p=="string"&&p.trim().length>0):e.nextTaskId?[e.nextTaskId]:[],u=e.sliceScope==="workstream"||e.sliceScope==="milestone"||e.sliceScope==="task"?e.sliceScope:null;return{...e,runnerAgentId:a,runnerAgentName:c,runnerAgents:r,runnerSource:l,playbackState:e.queueState,autoIntentEnabled:uu(e),autoRuntimeState:du(e),queueOrigin:e.queueOrigin??"system",sliceScope:u,sliceTaskIds:d,sliceTaskCount:typeof e.sliceTaskCount=="number"&&Number.isFinite(e.sliceTaskCount)?Math.max(0,Math.floor(e.sliceTaskCount)):d.length,executionPolicy:e.executionPolicy??null}}function fi(e){const t=e.items.map(u=>pu(u)),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(e.total,t.length):t.length,r=e.pagination&&typeof e.pagination=="object"?e.pagination:null,i=r&&Number.isFinite(r.offset)?Math.max(0,Math.floor(r.offset)):0,a=r&&Number.isFinite(r.limit)?Math.max(1,Math.floor(r.limit)):Math.max(1,t.length),c=i+a<s,l=r&&typeof r.hasMore=="boolean"?r.hasMore:c,d=r&&typeof r.nextCursor=="string"?r.nextCursor:l?String(i+a):null;return{...e,items:t,total:s,pagination:{offset:i,limit:a,total:s,nextCursor:d,hasMore:l}}}function fu(e){const t=(e.queueState??"").trim().toLowerCase();if(t==="queued"||t==="running"||t==="blocked"||t==="idle"||t==="completed")return t;const s=e.status.trim().toLowerCase();return s==="running"||s==="in_progress"||s==="dispatching"?"running":s==="active"?"queued":e.runnable===!1||s==="blocked"||s==="failed"||s==="error"?"blocked":s==="completed"||s==="done"||s==="resolved"?"completed":"queued"}function hu(e){if(!e)return"Workstream";const t=e.trim();return t.length===0?"Workstream":/^[a-f0-9-]{16,}$/i.test(t)?`Workstream ${t.slice(0,8)}`:t}function gu(e){var x,b,g,j,y,I,k,N,h,C,V,te,z,Ie,B,ee;const t=((b=(x=e.lineage)==null?void 0:x.initiativeIds)==null?void 0:b.filter(be=>typeof be=="string"&&be.trim().length>0))??[],s=((j=(g=e.lineage)==null?void 0:g.workstreamIds)==null?void 0:j.filter(be=>typeof be=="string"&&be.trim().length>0))??[],r=((y=e.initiativeId)==null?void 0:y.trim())||t[0]||null,i=((I=e.workstreamId)==null?void 0:I.trim())||((N=(k=e.sourceWorkstreamIds)==null?void 0:k.find(be=>typeof be=="string"&&be.trim().length>0))==null?void 0:N.trim())||s[0]||null;if(!r||!i)return null;const a=((C=(h=e.lineage)==null?void 0:h.taskIds)==null?void 0:C.filter(be=>typeof be=="string"&&be.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,l=La(e.runnerAgentId??null),d=$a(e.runnerAgentName??null,l),u=Pl(e.runnerAgents??null,l,d),p=u[0]??null;return{initiativeId:r,initiativeTitle:((V=e.initiativeTitle)==null?void 0:V.trim())||t[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:i,workstreamTitle:((te=e.workstreamTitle)==null?void 0:te.trim())||((z=e.title)==null?void 0:z.trim())||((Ie=e.milestoneTitle)==null?void 0:Ie.trim())||((B=e.taskTitle)==null?void 0:B.trim())||hu(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((ee=e.taskTitle)==null?void 0:ee.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(p==null?void 0:p.id)??l,runnerAgentName:(p==null?void 0:p.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(p?"inferred":"fallback"),queueState:fu(e),blockReason:e.blockReason??null,queueOrigin:"system",sliceScope:c,sliceTaskIds:a.length>0?a:e.taskId?[e.taskId]:[],sliceTaskCount:a.length>0?a.length:e.taskId?1:0,sliceMilestoneId:e.milestoneId,executionPolicy:null,autoContinue:null}}function xu(e){const t=new Map;for(const s of e){const r=t.get(s.initiativeId);if(r){r.workstreamCount+=1,r.workstreamIds.push(s.workstreamId),r.items.push(s);for(const a of s.runnerAgents??[])r.runnerAgents.some(c=>c.id===a.id)||r.runnerAgents.push(a);const i=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;i(s.queueState)>i(r.queueState)&&(r.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 yu(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 bu({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=20,authToken:i=null,embedMode:a=!1,enabled:c=!0,snapshotVersion:l=null,zoomLevel:d="workstream"}){var ue,Ke,pe,ae,ne,ie,xe;const u=Ma(),p=Gt(),x=Math.max(0,s),b=Math.max(1,Math.min(300,r)),g=o.useRef(null);o.useEffect(()=>()=>{g.current&&(clearTimeout(g.current),g.current=null)},[]);const j=o.useMemo(()=>vs.nextUpQueue({initiativeId:e,projectId:t,offset:x,limit:b,authToken:i,embedMode:a}),[e,t,x,b,i,a]),y=o.useRef(l);o.useEffect(()=>{l!==null&&y.current!==null&&l!==y.current&&u.invalidateQueries({queryKey:j}),y.current=l},[l,u,j]);const I=()=>{g.current&&(clearTimeout(g.current),g.current=null),g.current=setTimeout(()=>{g.current=null,u.invalidateQueries({queryKey:vs.liveData({authToken:i,embedMode:a,projectId:t})})},iu)},k=async({includeGraph:K=!0,includeLiveData:R=!0}={})=>{const U=[u.invalidateQueries({queryKey:j}),u.invalidateQueries({queryKey:vs.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})})];K&&U.push(u.invalidateQueries({queryKey:vs.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})),await Promise.all(U),R&&I()},N=async(K,R)=>{if(p)return cu(e);const U=new URLSearchParams;e&&U.set("initiative_id",e),Ns(U,t,{allTokenWhenMissing:!0}),U.set("offset",String(K)),U.set("limit",String(R));let P;try{P=await fetch(`/orgx/api/mission-control/next-up?${U.toString()}`,{headers:Ot({authToken:i,embedMode:a})})}catch(ye){throw new Error(lu(ye,"Failed to load next up queue"))}const H=await xr(P);if(!P.ok){const ye=ou(P,H,"Failed to load next up queue");throw new Error(ye)}const Q=H??null;if(!Q||Q.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:K,limit:R,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(Ed())return fi(Q);const ge=Q.items.filter(ye=>!zs(ye.initiativeId));let ke=fi({...Q,items:ge});if(ke.items.length>0)return ke;const se=new URLSearchParams;e&&se.set("initiative_id",e),Ns(se,t,{allTokenWhenMissing:!0}),se.set("level","workstream"),se.set("include_completed","0"),se.set("offset",String(K)),se.set("limit",String(Math.max(R,24)));try{const ye=await fetch(`/orgx/api/mission-control/slices?${se.toString()}`,{headers:Ot({authToken:i,embedMode:a})}),he=await xr(ye);if(ye.ok&&(he!=null&&he.ok)&&Array.isArray(he.items)){const L=he.items.map(q=>gu(q)).filter(q=>!!q).filter(q=>!zs(q.initiativeId));L.length>0&&(ke=fi({ok:!0,generatedAt:new Date().toISOString(),total:typeof he.total=="number"&&Number.isFinite(he.total)?Math.max(he.total,L.length):L.length,items:L,pagination:he.pagination&&typeof he.pagination=="object"?{offset:typeof he.pagination.offset=="number"?Math.max(0,Math.floor(he.pagination.offset)):K,limit:typeof he.pagination.limit=="number"?Math.max(1,Math.floor(he.pagination.limit)):Math.max(R,24),total:typeof he.pagination.total=="number"?Math.max(0,Math.floor(he.pagination.total)):L.length,nextCursor:typeof he.pagination.nextCursor=="string"?he.pagination.nextCursor:null,hasMore:typeof he.pagination.hasMore=="boolean"?he.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...Q.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return ke},h=Mc({queryKey:j,enabled:c,initialPageParam:x,queryFn:async({pageParam:K})=>{const R=typeof K=="number"&&Number.isFinite(K)?Math.max(0,Math.floor(K)):x;return await N(R,b)},getNextPageParam:K=>{const R=K.pagination;if(!(R!=null&&R.hasMore)||!R.nextCursor)return;const U=Number.parseInt(R.nextCursor,10);if(Number.isFinite(U))return Math.max(0,Math.floor(U))},refetchInterval:K=>{var P;const R=(P=K.state.data)==null?void 0:P.pages;return!R||R.length===0?1e4:R.some(H=>Array.isArray(H.items)&&H.items.some(Q=>Q.queueState==="running"))?2500:8e3}}),C=Cn({mutationFn:async K=>{if(p)return{ok:!0,initiativeId:K.initiativeId,workstreamId:K.workstreamId,dispatchMode:"slice",sessionId:null};const R=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:K.initiativeId,workstreamId:K.workstreamId,agentId:K.agentId??void 0,scope:K.scope??void 0,maxParallelSlices:typeof K.maxParallelSlices=="number"&&Number.isFinite(K.maxParallelSlices)?Math.max(1,Math.floor(K.maxParallelSlices)):void 0,parallelMode:K.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),U=await xr(R);if(!R.ok)throw Ji(R,U,"Failed to dispatch queued workstream");return U},onMutate:async K=>{await u.cancelQueries({queryKey:j});const R=u.getQueryData(j);return R?(u.setQueryData(j,{...R,pages:R.pages.map(U=>({...U,items:U.items.map(P=>P.initiativeId===K.initiativeId&&P.workstreamId===K.workstreamId?{...P,queueState:"running",playbackState:"running"}:P.queueState==="running"?{...P,queueState:"idle",playbackState:"idle"}:P)}))}),{previous:R}):{previous:R}},onError:(K,R,U)=>{U!=null&&U.previous&&u.setQueryData(j,U.previous)},onSuccess:()=>{k({includeGraph:!1})}}),V=Cn({mutationFn:async K=>{if(p)return;const R={initiativeId:K.initiativeId,agentId:K.agentId??void 0,tokenBudgetTokens:K.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};K.scope==="workstream"&&K.workstreamId&&(R.workstreamIds=[K.workstreamId]),typeof K.maxParallelSlices=="number"&&Number.isFinite(K.maxParallelSlices)&&(R.maxParallelSlices=K.maxParallelSlices),K.parallelMode==="iwmt"&&(R.parallelMode=K.parallelMode);const U=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(R)}),P=await xr(U);if(!U.ok){const H=tu(P);throw H||Ji(U,P,"Failed to start auto-continue")}},onSuccess:()=>{k({includeGraph:!1})}}),te=Cn({mutationFn:async K=>{if(p)return;const R=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:K.initiativeId})}),U=await xr(R);if(!R.ok)throw Ji(R,U,"Failed to stop auto-continue")},onSuccess:()=>{k({includeGraph:!1})}}),z=o.useMemo(()=>{var P;const K=((P=h.data)==null?void 0:P.pages)??[];if(K.length===0)return[];const R=new Set,U=[];for(const H of K)for(const Q of H.items){const ge=`${Q.initiativeId}:${Q.workstreamId}`;R.has(ge)||(R.add(ge),U.push(Q))}return U},[(ue=h.data)==null?void 0:ue.pages]),Ie=o.useMemo(()=>{var U;const K=((U=h.data)==null?void 0:U.pages)??[];let R=0;for(const P of K)typeof P.total=="number"&&Number.isFinite(P.total)&&(R=Math.max(R,P.total));return Math.max(R,z.length)},[z.length,(Ke=h.data)==null?void 0:Ke.pages]),B=o.useMemo(()=>{var ge;const K=((ge=h.data)==null?void 0:ge.pages)??[];if(K.length===0)return null;const R=K[0],U=K[K.length-1],P=R.pagination,H=U.pagination,Q=!!h.hasNextPage;return{offset:P&&Number.isFinite(P.offset)?Math.max(0,Math.floor(P.offset)):x,limit:P&&Number.isFinite(P.limit)?Math.max(1,Math.floor(P.limit)):b,total:Ie,nextCursor:Q?(H==null?void 0:H.nextCursor)??String(((H==null?void 0:H.offset)??x)+((H==null?void 0:H.limit)??b)):null,hasMore:Q}},[Ie,b,x,(pe=h.data)==null?void 0:pe.pages,h.hasNextPage]),ee=((ne=(ae=h.data)==null?void 0:ae.pages[0])==null?void 0:ne.generatedAt)??null,be=o.useMemo(()=>{var U;const K=((U=h.data)==null?void 0:U.pages)??[],R=new Set;for(const P of K)for(const H of P.degraded??[])typeof H=="string"&&H.trim().length>0&&R.add(H);return Array.from(R)},[(ie=h.data)==null?void 0:ie.pages]),ve=o.useMemo(()=>d==="initiative"?xu(z):[],[z,d]),Ae=o.useMemo(()=>d==="milestone"?yu(z):[],[z,d]);return{items:z,total:Ie,pagination:B,generatedAt:ee,degraded:be,isLoading:h.isLoading,isFetching:h.isFetching,isFetchingNextPage:h.isFetchingNextPage,hasNextPage:!!h.hasNextPage,error:((xe=h.error)==null?void 0:xe.message)??null,refetch:h.refetch,fetchNextPage:h.fetchNextPage,playWorkstream:C.mutateAsync,startWorkstreamAutoContinue:V.mutateAsync,stopInitiativeAutoContinue:te.mutateAsync,isPlaying:C.isPending,isStartingAutoContinue:V.isPending,isStoppingAutoContinue:te.isPending,zoomLevel:d,initiativeGroups:ve,milestoneGroups:Ae}}const wu=750;async function xn(e){return await e.json().catch(()=>null)}function er(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",r=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${r}`)}function yn(e,t,s){if(er(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 r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||`${s}.`;return Wt(r)}function vu(e){const t=e.authToken??null,s=e.embedMode??!1,r=Gt(),i=Ma(),a=o.useRef(null);o.useEffect(()=>()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]);const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),a.current=setTimeout(()=>{a.current=null,i.invalidateQueries({queryKey:["live-data"]})},wu)},l=async()=>{await Promise.all([i.invalidateQueries({queryKey:["mission-control-next-up"]}),i.invalidateQueries({queryKey:["mission-control-graph"]}),i.invalidateQueries({queryKey:["mission-control-slices"]})]),c()},d=async N=>{if(r)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId,placement:N.placement??"top"};const h=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(h.ok)return C;if(!er(h,C))throw new Error(yn(h,C,"Failed to move Next Up item"));const V=await fetch("/orgx/api/mission-control/next-up",{headers:Ot({authToken:t,embedMode:s})}),te=await xn(V);if(!V.ok)throw new Error(yn(V,te,"Failed to read queue for move fallback"));const Ie=(Array.isArray(te==null?void 0:te.items)?te.items:[]).map(Ae=>{const ue=typeof(Ae==null?void 0:Ae.initiativeId)=="string"?Ae.initiativeId:null,Ke=typeof(Ae==null?void 0:Ae.workstreamId)=="string"?Ae.workstreamId:null;return!ue||!Ke?null:{initiativeId:ue,workstreamId:Ke}}).filter(Ae=>!!Ae);if(Ie.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const B=Ie.findIndex(Ae=>Ae.initiativeId===N.initiativeId&&Ae.workstreamId===N.workstreamId);if(B===-1)return{ok:!0,fallback:"reorder-move-skip"};const[ee]=Ie.splice(B,1);(N.placement??"top")==="bottom"?Ie.push(ee):Ie.unshift(ee);const be=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:Ie})}),ve=await xn(be);if(!be.ok)throw new Error(yn(be,ve,"Failed to move Next Up item with reorder fallback"));return ve??{ok:!0,fallback:"reorder-move"}},u=async N=>{if(r)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(h.ok)return C;if(er(h,C)){const V=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),te=await xn(V);if(!V.ok)throw new Error(yn(V,te,"Failed to remove item from queue with legacy fallback"));return te??{ok:!0,fallback:"next-up-unpin"}}throw new Error(yn(h,C,"Failed to remove item from queue"))},p=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok)throw new Error(yn(h,C,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),x=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok)throw new Error(yn(h,C,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),b=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,updated:N.order.length};const h=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok)throw new Error(yn(h,C,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),g=Cn({mutationFn:d,onSuccess:()=>{l()}}),j=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok){if(er(h,C)){const V=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:N.initiativeId})}),te=await xn(V);if(!V.ok)throw new Error(yn(V,te,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(yn(h,C,"Failed to stop triage"))}return C},onSuccess:()=>{l()}}),y=Cn({mutationFn:u,onSuccess:()=>{l()}}),I=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,cleared:!0};const h=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok){if(er(h,C)&&N.initiativeId){const V=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:N.initiativeId})}),te=await xn(V);if(!V.ok)throw new Error(yn(V,te,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(yn(h,C,"Failed to clear Next Up lifecycle state"))}return C},onSuccess:()=>{l()}}),k=Cn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,updated:N.items.length,failed:0,errors:[],fallback:"demo"};const h=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:Ot({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),C=await xn(h);if(!h.ok){if(!er(h,C))throw new Error(yn(h,C,"Failed to apply bulk queue action"));const V=await Promise.all(N.items.map(async B=>{try{return N.action==="remove"?await u(B):await d({initiativeId:B.initiativeId,workstreamId:B.workstreamId,placement:N.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ee){return{ok:!1,error:ee instanceof Error?ee.message:"Queue action failed"}}})),te=V.filter(B=>B.ok).length,z=V.length-te,Ie=V.filter(B=>!B.ok&&B.error).map(B=>B.error);return{ok:z===0,updated:te,failed:z,errors:Ie,fallback:"sequential"}}return C},onSuccess:()=>{l()}});return{pin:p.mutateAsync,unpin:x.mutateAsync,reorder:b.mutateAsync,move:g.mutateAsync,remove:y.mutateAsync,stopTriage:j.mutateAsync,clear:I.mutateAsync,bulk:k.mutateAsync,isPinning:p.isPending,isUnpinning:x.isPending,isReordering:b.isPending,isMoving:g.isPending,isRemoving:y.isPending,isStoppingTriage:j.isPending,isClearing:I.isPending,isBulking:k.isPending}}function Ol(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function ku(e,t,s,r){const i=new URLSearchParams;e&&i.set("workspace_id",e),t&&i.set("status",t),i.set("limit","100");const a=`/orgx/api/live/triage?${i.toString()}`,c=await fetch(a,{headers:Ol(s,r)});if(!c.ok){const l=await c.json().catch(()=>null),d=(l&&typeof l=="object"&&"error"in l&&typeof l.error=="string"?l.error:null)??(l&&typeof l=="object"&&"message"in l&&typeof l.message=="string"?l.message:null)??`Triage fetch failed (${c.status})`;throw new Error(Wt(String(d)))}return c.json()}async function ju(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:Ol(s,r),body:JSON.stringify(t)});if(!c.ok){const l=await c.json().catch(()=>({})),d=l.error??l.message??`Action failed (${c.status})`;throw new Error(Wt(String(d)))}return c.json()}function Nu(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,c=Ma(),l=vs.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=qs({queryKey:l,queryFn:()=>ku(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=Cn({mutationFn:async({itemId:g,payload:j})=>ju(g,j,i,a),onSuccess:()=>{c.invalidateQueries({queryKey:l})}}),p=o.useCallback(async(g,j,y)=>u.mutateAsync({itemId:g,payload:{action:j,note:y==null?void 0:y.note,optionId:y==null?void 0:y.optionId,snoozeDurationMinutes:y==null?void 0:y.snoozeDurationMinutes}}),[u]),x=o.useMemo(()=>{var g,j,y;return{items:((g=d.data)==null?void 0:g.items)??[],total:((j=d.data)==null?void 0:j.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((y=d.data)==null?void 0:y.degraded)??[],refetch:d.refetch}},[d]),b=o.useMemo(()=>({performAction:p,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[p,u.isPending,u.error]);return{model:x,actions:b}}function le(...e){return e.filter(Boolean).join(" ")}const T={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"},Sg={active:{text:"rgba(223, 255, 156, 0.9)"},done:{text:"rgba(135, 255, 233, 0.9)"},blocked:{text:"rgba(255, 195, 208, 0.9)"},planned:{text:"rgba(236, 241, 255, 0.74)"}},Iu={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Au={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function Da(e){return Iu[e]??"rgba(255, 255, 255, 0.4)"}function Er(e){return Au[e]??null}function _u(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function Zt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Qt={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}},Cg={surfaceSwitch:{duration:Qt.durationStandard/1e3,ease:Qt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Qt.durationFast/1e3,ease:Qt.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:Qt.durationStandard/1e3,ease:Qt.easingStandard}})},Mg={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},Ti="/orgx/live/assets/Fm0FhtnV.png";function Bl({size:e=14,className:t="",stroke:s="currentColor",strokeWidth:r=1.8,withBackground:i=!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:r,children:[i?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 jn({type:e,className:t="",size:s=14,accent:r}){const i={className:t,width:s,height:s,viewBox:"0 0 24 24",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8};if(e==="initiative"){const c=r??T.iris;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${c}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:c,stroke:"none"})]})}if(e==="workstream"){const c=r??T.lime;return n.jsx(Bl,{size:s,className:t,stroke:c,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${c}1A`})}if(e==="milestone"){const c=r??T.teal;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${c}1A`})]})}if(e==="task")return n.jsxs("svg",{...i,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 c=r??T.amber;return n.jsxs("svg",{...i,stroke:c,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:`${c}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}if(e==="session"){const c=r??T.teal;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${c}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}if(e==="active"){const c=r??T.lime;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${c}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}if(e==="blocked"){const c=r??T.red;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${c}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 c=r??T.red;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${c}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}if(e==="handoff"){const c=r??T.iris;return n.jsxs("svg",{...i,stroke:c,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 c=r??T.amber;return n.jsxs("svg",{...i,stroke:c,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:`${c}12`}),n.jsx("path",{d:"M9 14h6"})]})}const a=r??T.cyan;return n.jsxs("svg",{...i,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 Su=[{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"}],hi=[{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."}],Cu=[{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",jo="orgx.demo_mode",Mu=6500;function Tu(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 Eu={hidden:{},visible:{transition:{staggerChildren:.07}}},bs={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},Ru={initiative:"text-[#A8A0FF]",workstream:"text-[#BFFF00]",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-[#BFFF00]",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function Yi(e){const t=hi.length;return(e+t)%t}function Lu({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,c=e.lastError?Wt(e.lastError):null,[l,d]=o.useState("idle"),[u,p]=o.useState("idle"),[x,b]=o.useState(0),[g,j]=o.useState(!1),y=e.hasApiKey&&e.keySource&&e.keySource!=="none",I=hi[x];o.useEffect(()=>{if(l==="idle")return;const h=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(h)},[l]),o.useEffect(()=>{if(u==="idle")return;const h=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(h)},[u]),o.useEffect(()=>{if(g)return;const h=window.setInterval(()=>{b(C=>Yi(C+1))},Mu);return()=>window.clearInterval(h)},[g]);const k=async()=>{try{await navigator.clipboard.writeText(ko),d("ok")}catch{d("error")}},N=async()=>{try{const h={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(h,null,2)),p("ok")}catch{p("error")}};return n.jsxs(ce.section,{variants:Eu,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:bs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Ti,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:bs,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(jn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ce.p,{variants:bs,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:bs,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:()=>j(!0),onMouseLeave:()=>j(!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(jn,{type:"workstream",size:14,className:"text-[#BFFF00]"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[x+1,"/",hi.length]})]}),n.jsx(vt,{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:I.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:I.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:I.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:I.highlights.map(h=>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(jn,{type:h.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:h.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:h.detail})]},`${I.id}-${h.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:I.footnote})]},I.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:hi.map((h,C)=>{const V=C===x;return n.jsx("button",{type:"button",onClick:()=>b(C),"aria-label":`View slide ${C+1}`,className:`h-1.5 rounded-full transition-all ${V?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},h.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>b(h=>Yi(h-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:()=>b(h=>Yi(h+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:Su.map(h=>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 ${Ru[h.iconType]}`,children:n.jsx(jn,{type:h.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:h.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:h.desc})]},h.label))}),n.jsxs(ce.div,{variants:bs,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-[#BFFF00] 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:r,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:bs,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(jn,{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(jn,{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:()=>{k()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:l==="ok"?"Copied":l==="error"?"Copy failed":"Copy command"})]}),y&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",Tu(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:Cu.map(h=>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(jn,{type:h.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:h.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:h.detail})]},h.label))})]})]})]}),n.jsx(ce.div,{variants:bs,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:c})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void N(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:u==="ok"?"Copied":u==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:r,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:bs,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.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.setItem(jo,"1")}catch{}i()},className:"text-left text-caption text-muted transition hover:text-secondary",children:"Explore demo dashboard"}),n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.removeItem(jo)}catch{}i()},className:"text-left text-caption text-faint transition hover:text-secondary",children:"Continue offline"})]}),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 $u={hidden:{},visible:{transition:{staggerChildren:.06}}},Es={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Du({isSubmitting:e,onSubmit:t,onBack:s}){const[r,i]=o.useState(""),[a,c]=o.useState(null),l="https://www.useorgx.com/settings#security",d=async()=>{c(null);const p=r.trim();if(!p){c("API key is required.");return}const x=/^[a-z]+_/i.test(p)?p:`oxk_${p}`;try{await t(x),i("")}catch(b){const g=b instanceof Error?b.message:"Failed to validate API key.";c(Wt(g))}},u=a!==null;return n.jsxs(ce.section,{variants:$u,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:Es,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Ti,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:Es,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ce.p,{variants:Es,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:Es,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:Es,className:"mt-3",children:n.jsxs("a",{href:l,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:Es,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-[#BFFF00]/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:r,onChange:p=>{i(p.target.value),a&&c(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(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:Es,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-[#BFFF00] 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 No="orgx.user.display-name",Io="orgx.user.avatar-seed-suffix";function Ao(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function _o(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function Fu(){const[e,t]=o.useState(()=>Ao(No)),[s,r]=o.useState(()=>Ao(Io)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();_o(No,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());_o(Io,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function Pu(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function Ou(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 So=[T.lime,T.teal,T.iris,T.cyan];function Bu(e,t,s,r,i,a){const c=C=>C*Math.PI/180,l=Math.cos,d=Math.sin,u=c(i),p=c(a),x=a-i>180?1:0,b=e+r*l(u),g=t+r*d(u),j=e+r*l(p),y=t+r*d(p),I=e+s*l(p),k=t+s*d(p),N=e+s*l(u),h=t+s*d(u);return[`M ${b} ${g}`,`A ${r} ${r} 0 ${x} 1 ${j} ${y}`,`L ${I} ${k}`,`A ${s} ${s} 0 ${x} 0 ${N} ${h}`,"Z"].join(" ")}function qu(e){const t=Ou(Pu(e)),s=3+Math.floor(t()*2),r=[],i=50,a=50;for(let c=0;c<s;c++){const l=8+c*10,d=l+9,u=6+Math.floor(t()*6),p=360/u,x=1.5+t()*2;for(let b=0;b<u;b++){if(t()<.15)continue;const g=b*p+x/2,j=(b+1)*p-x/2,y=So[Math.floor(t()*So.length)],I=.25+t()*.55;r.push({d:Bu(i,a,l,d,g,j),fill:y,opacity:I})}}return r}function zu({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>qu(e),[e]);return n.jsxs(ce.svg,{viewBox:"0 0 100 100",width:t,height:t,className:le("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Qt.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:T.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:T.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:T.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:i.map((a,c)=>n.jsx(ce.path,{d:a.d,fill:a.fill,initial:r?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:c*.012,duration:.35,ease:Qt.easingEntrance},style:{transformOrigin:"50px 50px"}},c))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function Wu({onComplete:e}){const{displayName:t,updateName:s}=Fu(),[r,i]=o.useState(t),a=o.useCallback(()=>{s(r),e()},[r,s,e]),c=o.useCallback(()=>{e()},[e]),l=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(r.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:Qt.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(zu,{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:r,onChange:u=>i(u.target.value),onKeyDown:l,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:r.trim()?"Continue":"Continue without name"}),r.trim()&&n.jsx("button",{type:"button",onClick:c,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const Uu=[{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 Hu({className:e,compact:t=!1}){return n.jsxs("div",{className:le("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"]}),Uu.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 Co="orgx.user.name-asked";function Vu(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 Ku(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 Gu(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Mo={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Zi="orgx.onboarding.mc_hint.dismissed",ea={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 Xu({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:c,onBackToPairing:l,onUseManualKey:d,onSkip:u}){const[p,x]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Zi)==="1"),[b,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Co)!=="1"),j=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Co,"1"),g(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(Zi,"1"):window.localStorage.removeItem(Zi))},[p]);const y=e.status==="manual_key",I=e.status==="awaiting_browser_auth"||e.status==="pairing",k=Gu(e.status),N=k==="active"&&e.status!=="connected",h=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 ${y?"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(vt,{mode:"wait",children:e.status==="connected"&&b?n.jsx(ce.div,{...ea,children:n.jsx(Wu,{onComplete:j})},"welcome-name"):y?n.jsx(ce.div,{...ea,children:n.jsx(Du,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(ce.div,{...ea,children:n.jsx(Lu,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(I||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:[N&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Mo[k]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Mo[k]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:Vu(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Ku(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&&I&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-[#BFFF00]/25 bg-[#BFFF00]/[0.05] px-3 py-1 text-caption font-medium text-[#D8FFA1] transition hover:bg-[#BFFF00]/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{i()},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"})]})]}),h&&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-[#BFFF00]/30 bg-[#BFFF00]/15 px-3 py-1 text-caption font-medium text-[#D8FFA1]",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>x(!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(Hu,{compact:!0})})]})})}function Qu({children:e,color:t,pulse:s,title:r}){const i=t??T.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:r,style:{backgroundColor:`${i}22`,border:`1px solid ${i}5a`,color:i},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:i}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:i}})]}),e]})}function Ei({open:e,onClose:t,children:s,maxWidth:r="max-w-2xl",fitContent:i=!1,closeOnBackdropClick:a=!0,closeOnEscape:c=!0,closeOnEscapeWhenTyping:l=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const j=d.current;if(!j)return;const y=j.querySelector('[data-modal-autofocus="true"]');if(y){y.focus();return}const I=j.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');I.length>0?I[0].focus():j.focus()})();const b=j=>{if(j.key==="Escape"){if(!c)return;if(!l){const C=j.target;if(C&&(C.tagName==="INPUT"||C.tagName==="TEXTAREA"||C.tagName==="SELECT"||C.isContentEditable))return}j.preventDefault(),t();return}if(j.key!=="Tab")return;const y=d.current;if(!y)return;const I=y.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(I.length===0){j.preventDefault(),y.focus();return}const k=I[0],N=I[I.length-1],h=document.activeElement;!j.shiftKey&&h===N?(j.preventDefault(),k.focus()):j.shiftKey&&h===k&&(j.preventDefault(),N.focus())},g=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",b),()=>{var j;document.body.style.overflow=g,document.removeEventListener("keydown",b),(j=u.current)==null||j.focus()}},[e,t,c,l]);const p=n.jsx(vt,{children:e&&n.jsxs(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},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 ${r} overflow-hidden ${i?"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:T.cardBgElevated,borderColor:T.cardBorderStrong},onClick:x=>x.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:Sc.createPortal(p,document.body)}const Ju=[{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 Yu({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:Ju.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:le("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",i?"text-lime":"text-secondary hover:text-white/72"),children:[i&&n.jsxs(n.Fragment,{children:[n.jsx(ce.span,{layoutId:"mobile-tab-active-pill",className:"absolute inset-0 rounded-[18px] border border-[#BFFF00]/28 bg-[#BFFF00]/[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:T.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:le("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",i?"border-[#BFFF00]/35 bg-[#BFFF00]/[0.12] text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03]"),children:[n.jsx("span",{className:"relative z-[1]",children:r.icon}),r.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:T.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:le("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function rr({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:le("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Zu={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"},em="/orgx/live/",bn=e=>`${em.replace(/\/+$/,"/")}${e}`,tm={pace:bn("brand/product-orchestrator.png"),eli:bn("brand/engineering-autopilot.png"),mark:bn("brand/launch-captain.png"),sage:bn("brand/pipeline-intelligence.png"),orion:bn("brand/control-tower.png"),dana:bn("brand/design-codex.png"),xandy:bn("brand/xandy-orchestrator.png"),nova:bn("brand/xandy-orchestrator.png"),openclaw:bn("brand/openclaw-mark.svg"),codex:bn("brand/openai-mark.svg"),openai:bn("brand/openai-mark.svg"),anthropic:bn("brand/anthropic-mark.svg"),orgx:bn("brand/orgx-logo.png")},nm=[{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 sm(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of nm)if(s.test.test(t))return tm[s.key];return null}function Xt({name:e,size:t="xs",hint:s,src:r}){const i=Da(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:sm(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Zu[t]} overflow-hidden rounded-full flex items-center justify-center font-semibold flex-shrink-0`,style:{backgroundColor:`${i}20`,color:i,border:`1px solid ${i}30`},children:d?n.jsx("img",{src:l??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>c(!0),loading:"lazy"}):_u(e)})}Xt.displayName="AgentAvatar";const rm={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 Rn({children:e,tone:t="muted",className:s,...r}){const i=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const c=a.type;return c.displayName==="AgentAvatar"||c.name==="AgentAvatar"});return n.jsx("span",{className:le("inline-flex h-7 items-center rounded-full border text-caption font-medium leading-none whitespace-nowrap",i?"gap-1.5 pl-[3px] pr-2.5 [&>[data-agent-avatar]]:h-5 [&>[data-agent-avatar]]:w-5":"gap-1.5 px-2.5",rm[t],s),...r,children:e})}function im(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||Fs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=ql(e.status),c={id:e.workstreamId,label:e.workstreamTitle||Fs(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 l of e.scopeProgress.milestones){const d=l.done>=l.total?"done":l.done>0?"active":"pending",u={id:l.id,label:l.title||Fs(l.id,"Milestone"),type:"milestone",status:d,progress:{done:l.done,total:l.total}};l.total>0&&(u.children=Array.from({length:l.total},(p,x)=>({id:`${l.id}-task-${x}`,label:`Task ${x+1}`,type:"task",status:x<l.done?"done":"pending"}))),c.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const l=((r=e.scopeProgress)==null?void 0:r.completedTasks)??0;c.children=e.taskIds.map((d,u)=>({id:d,label:Fs(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function Tg(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Fs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Fs(e.workstreamId,"Workstream"),type:"workstream",status:ql(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||Fs(e.taskId,"Task"),type:"task",highlight:!0}:null;return r&&i&&(r.children=[i]),s&&r?(s.children=[r],t.push(s)):r?t.push(r):s&&t.push(s),t}function Fs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function ql(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 zl(e){switch(e){case"done":return T.lime;case"active":return T.teal;case"blocked":return T.amber;case"failed":return T.red;default:return"rgba(255,255,255,0.15)"}}function am(e){const t=zl(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const om=o.memo(function({done:t,total:s,color:r}){const i=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:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),lm=16,cm=14,To=8,dm=8,um=28,mm=24,pm=24,fm=20,ta="rgba(255,255,255,0.07)";function hm(e){const t=e?cm:lm,s=t+dm+4;return{iconSz:t,colW:s,rowH:e?pm:um,rowHTask:e?fm:mm}}function Wl({node:e,depth:t,isLast:s,activeId:r,compact:i,index:a,taskLimit:c,expanded:l,onToggleExpand:d}){const u=r===e.id||e.highlight,p=e.progress&&e.progress.total>0,x=e.type==="task",{iconSz:b,colW:g,rowH:j,rowHTask:y}=hm(i),I=x?y:j,k=e.children??[],N=k.filter(B=>B.type==="task"),h=k.filter(B=>B.type!=="task"),C=N.length>c&&!l,V=C?N.slice(0,c):N,te=N.length-V.length,z=[...h,...V],Ie=z.length>0||C;return n.jsxs("div",{className:"relative",style:{minHeight:I},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ta,left:(t-1)*g+g/2,top:0,bottom:s?void 0:0,height:s?I/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:ta,left:(t-1)*g+g/2,top:I/2,width:g}})]}),n.jsxs(ce.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${u?"rounded-md bg-white/[0.03]":""}`,style:{height:I,paddingLeft:t*g},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:g,height:I},children:x?n.jsx("span",{className:"inline-block rounded-full",style:{...am(e.status),width:To,height:To}}):n.jsx(jn,{type:e.type,size:b,accent:u?T.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 ${x?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),p&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] tabular-nums leading-none text-white/20",children:[e.progress.done,"/",e.progress.total]}),e.agent&&n.jsx("span",{className:"ml-auto flex-shrink-0 rounded-full bg-white/[0.05] px-1.5 py-px text-[9px] font-medium leading-none text-white/25",children:e.agent.name})]}),p&&!x&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(om,{done:e.progress.done,total:e.progress.total,color:zl(e.status)})})]})]}),Ie&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ta,left:t*g+g/2,top:I/2,height:I/2}}),Ie&&n.jsxs("div",{children:[z.map((B,ee)=>n.jsx(Wl,{node:B,depth:t+1,isLast:ee===z.length-1&&!C,activeId:r,compact:i,index:a+ee+1,taskLimit:c,expanded:l,onToggleExpand:d},B.id)),C&&n.jsxs(ce.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+z.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:y,paddingLeft:(t+1)*g+g},children:["+",te," more · see all"]}),n.jsx(vt,{children:l&&N.length>c&&n.jsx(ce.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:y},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*g+g},children:"show less"})})]})]})}const gm=o.memo(function({nodes:t,className:s,activeId:r,compact:i,taskLimit:a=4}){const[c,l]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(Wl,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:c,onToggleExpand:()=>l(p=>!p)},d.id))})}),ka={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"}},xm=Object.keys(ka);function Eo(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of xm)if(t.includes(s))return s;return"engineering"}function Ro(e){return ka[e]??ka.engineering}const Js={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},yr={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Lo={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},$o={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 Ul(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 r=e.trim().toLowerCase(),i=$o[r];if(i){const a=yr[i]??"";return{name:i,domain:a,color:Js[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,c]of Object.entries(Lo))if(r.includes(a)){const l=yr[c]??"";return{name:c,domain:l,color:Js[c]??s.color,displayLabel:l?`${c} (${l})`:c}}}if(t){const r=t.trim();if(Js[r]){const c=yr[r]??"";return{name:r,domain:c,color:Js[r],displayLabel:c?`${r} (${c})`:r}}const i=r.toLowerCase(),a=$o[i];if(a){const c=yr[a]??"";return{name:a,domain:c,color:Js[a]??s.color,displayLabel:c?`${a} (${c})`:a}}for(const[c,l]of Object.entries(Lo))if(i.includes(c)){const d=yr[l]??"";return{name:l,domain:d,color:Js[l]??s.color,displayLabel:d?`${l} (${d})`:l}}}return s}function Eg({agents:e,max:t=4}){if(!e.length)return null;const s=e.slice(0,t),r=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(i=>n.jsx("div",{className:"relative flex-shrink-0",title:`${i.name} (${i.confidence} confidence)`,style:{borderRadius:"9999px",border:i.confidence==="high"?"1.5px solid rgba(255,255,255,0.25)":i.confidence==="medium"?"1.5px dashed rgba(255,255,255,0.15)":"1.5px dotted rgba(255,255,255,0.10)"},children:n.jsx(Xt,{name:i.name,size:"xs"})},i.id)),r>0&&n.jsxs("span",{className:"ml-1 flex-shrink-0 text-micro text-muted",children:["+",r]})]})}const ym=new Set(["running","active","in_progress","working","planning","dispatching"]),bm=new Set(["running","dispatching"]),wm=3*6e4;function vm(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=wm:!1}function km(e){const t=Zt(e.status??""),s=Zt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:ym.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?vm(e.lastHeartbeatAt):!1}function Hl(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function jm(e){const t=Zt(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-[#BFFF00]/24 bg-[#BFFF00]/[0.10] text-[#E8FFD0]"}function Nm(e){const t=Zt(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-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Vl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Qr(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Rs(e,t){const s=[],r=i=>{if(typeof i!="string")return;const a=i.trim();a&&(s.some(c=>c.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const i of e)r(i);return r(t??null),s}function ji(e,t){if(!e)return t;const s=e.trim();return s?Vn(s)?`${t} ${ws(s)}`:s:t}const Im=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),Am=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function _m(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?Im.has(t)||t.startsWith("telegram:"):!1}function Sm(e){if(!e)return!1;const t=e.trim();return t?Am.some(s=>s.test(t)):!1}function Kl({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var x,b,g,j,y,I;const r=new Map;for(const k of s)k.id&&r.set(k.id,k.name??k.id);const i=new Map;for(const k of e){const N=(x=k.runId)==null?void 0:x.trim();!N||i.has(N)||i.set(N,k)}const a=new Map;for(const k of e){const N=((b=k.initiativeId)==null?void 0:b.trim())??"",h=((g=k.workstreamId)==null?void 0:g.trim())??"";if(!N||!h)continue;const C=`${N}:${h}`;a.has(C)||a.set(C,k)}const c=new Set;for(const k of e){const N=(j=k.runId)==null?void 0:j.trim();N&&c.add(N)}const l=[];for(const k of t){if(!bm.has(k.status))continue;const N=(k.runId??k.sliceRunId??"").trim();if(!N)continue;const h=Rs(k.initiativeIds,k.initiativeId),C=Rs(k.workstreamIds,k.workstreamId),V=h[0]??null,te=C[0]??null,z=[];for(const ve of h)for(const Ae of C)!ve||!Ae||z.push(`${ve}:${Ae}`);if(!(c.has(N)||z.some(ve=>a.has(ve))))continue;const B=i.get(N)??(z.length>0?z.map(ve=>a.get(ve)??null).find(ve=>!!ve)??null:null),ee=V?r.get(V)??V:null,be=k.scopeProgress&&typeof k.scopeProgress.totalTasks=="number"&&k.scopeProgress.totalTasks>0?Math.round(k.scopeProgress.completedTasks/k.scopeProgress.totalTasks*100):null;l.push({key:`slice:${k.sliceRunId}`,source:"slice",session:B??null,runId:N,status:Zt(k.status),title:k.workstreamTitle??(B==null?void 0:B.title)??`Work slice ${k.sliceRunId.slice(0,8)}`,subtitle:k.statusExplainer??k.lastEventSummary??(B==null?void 0:B.lastEventSummary)??null,progress:be??(B==null?void 0:B.progress)??null,initiativeId:V,initiativeIds:h,initiativeTitle:ee,workstreamId:te,workstreamIds:C,iwmtId:k.iwmtId??null,iwmtIds:Rs(k.iwmtIds,k.iwmtId),workstreamTitle:k.workstreamTitle??(B==null?void 0:B.title)??null,taskIds:Array.isArray(k.taskIds)?k.taskIds:[],milestoneIds:Array.isArray(k.milestoneIds)?k.milestoneIds:[],artifactCount:k.artifactCount??0,decisionCount:k.blockingDecisionCount??k.decisionCount??0,updatedAt:k.updatedAt??k.lastEventAt??(B==null?void 0:B.updatedAt)??null,scope:k.scope,milestoneProgress:(y=k.scopeProgress)==null?void 0:y.milestones})}if(l.sort((k,N)=>Qr(N.updatedAt)-Qr(k.updatedAt)),l.length>0){const k=[],N=new Set;for(const h of l){const C=h.initiativeId??((I=h.initiativeIds)==null?void 0:I[0])??"none",te=(h.workstreamId?`scope:${C}:${h.workstreamId}`:null)??(h.runId?`run:${h.runId}`:h.key);N.has(te)||(N.add(te),k.push(h))}return k}const d=e.filter(k=>{if(!km(k))return!1;const N=(k.initiativeId??"").trim(),h=(k.workstreamId??"").trim();return N.length>0&&h.length>0});d.sort((k,N)=>{const h=Qr(k.updatedAt??k.lastEventAt??k.startedAt);return Qr(N.updatedAt??N.lastEventAt??N.startedAt)-h});const u=[],p=new Set;for(const k of d){const N=k.workstreamId&&k.workstreamId.trim().length>0?`${k.initiativeId??"none"}:${k.workstreamId}`:k.runId;p.has(N)||(p.add(N),u.push(k))}return u.map(k=>{var N;return{key:`session:${k.id}`,source:"session",session:k,runId:k.runId,status:Zt(k.status??""),title:k.title,subtitle:(N=k.lastEventSummary)!=null&&N.trim()?k.lastEventSummary.trim():null,progress:k.progress,initiativeId:k.initiativeId,initiativeIds:Rs(void 0,k.initiativeId),initiativeTitle:k.initiativeId?r.get(k.initiativeId)??k.groupLabel??null:k.groupLabel??null,workstreamId:k.workstreamId,workstreamIds:Rs(void 0,k.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:k.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:k.updatedAt??k.lastEventAt??k.startedAt??null}})}const Cm=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:r=[],title:i="In Progress",className:a,showHeader:c=!0,panelStyle:l="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:p,onFocusRunId:x,onPlayWorkstream:b,onPauseWorkstream:g,onResumeWorkstream:j,onRestartSession:y,onIntervene:I,onOpenSliceDetail:k}){const[N,h]=o.useState(null),[C,V]=o.useState(null),[te,z]=o.useState(null),[Ie,B]=o.useState(null),ee=o.useMemo(()=>{const ne=new Map;if(!Array.isArray(s))return ne;for(const ie of s){const xe=Rs(ie.initiativeIds,ie.initiativeId),K=Rs(ie.workstreamIds,ie.workstreamId);for(const U of xe)for(const P of K){if(!U||!P)continue;const H=`${U}:${P}`;ne.has(H)||ne.set(H,ie)}const R=(ie.runId??ie.sliceRunId??"").trim();R&&!ne.has(`run:${R}`)&&ne.set(`run:${R}`,ie)}return ne},[s]),be=o.useMemo(()=>Kl({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),ve=o.useMemo(()=>{const ne=new Map;for(const ie of be){const xe=Zt(ie.status);ne.set(xe,(ne.get(xe)??0)+1)}return Array.from(ne.entries()).sort((ie,xe)=>xe[1]-ie[1]).map(([ie,xe])=>({status:ie,count:xe}))},[be]),Ae=o.useMemo(()=>N?be.filter(ne=>Zt(ne.status)===N):be,[N,be]),ue=o.useMemo(()=>{var K,R;const ne=new Map,ie=[];for(const U of Ae){const P=(((K=U.initiativeIds)==null?void 0:K[0])??U.initiativeId??"").trim(),H=(((R=U.workstreamIds)==null?void 0:R[0])??U.workstreamId??"").trim();if(!P){ie.push(U);continue}let Q=ne.get(P);Q||(Q={title:U.initiativeTitle??P,wsMap:new Map},ne.set(P,Q));const ge=H||"__none__";let ke=Q.wsMap.get(ge);ke||(ke={title:U.workstreamTitle??(H||"Unassigned"),rows:[],completedCount:0,lastActivity:null},Q.wsMap.set(ge,ke));const se=Zt(U.status);if(se==="completed"||se==="done"?ke.completedCount+=1:ke.rows.push(U),U.updatedAt){const ye=Date.parse(U.updatedAt),he=ke.lastActivity?Date.parse(ke.lastActivity):0;Number.isFinite(ye)&&ye>he&&(ke.lastActivity=U.updatedAt)}}const xe=[];for(const[U,P]of ne){const H=[];for(const[Q,ge]of P.wsMap)H.push({workstreamId:Q,workstreamTitle:ge.title,rows:ge.rows,completedCount:ge.completedCount,lastActivityAt:ge.lastActivity});H.sort((Q,ge)=>{const ke=Q.lastActivityAt?Date.parse(Q.lastActivityAt):0;return(ge.lastActivityAt?Date.parse(ge.lastActivityAt):0)-ke}),xe.push({initiativeId:U,initiativeTitle:P.title,workstreams:H})}return xe.sort((U,P)=>{const H=Math.max(0,...U.workstreams.map(ge=>ge.lastActivityAt?Date.parse(ge.lastActivityAt):0));return Math.max(0,...P.workstreams.map(ge=>ge.lastActivityAt?Date.parse(ge.lastActivityAt):0))-H}),{groups:xe,ungrouped:ie}},[Ae]),[Ke,pe]=o.useState(new Set),ae=async(ne,ie,xe)=>{if(ne.session){B(null),V(ne.session.id);try{await ie(ne.session),B(xe)}catch(K){const R=K instanceof Error?K.message:"";B(R?Wt(R):"Workstream action failed")}finally{V(null)}}};return n.jsxs(rr,{surface:l==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${l==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${a??""}`,children:[c?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:be.length})]})}):null,ve.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:()=>h(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${N===null?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:be.length})]}),ve.map(({status:ne,count:ie})=>n.jsxs("button",{type:"button",onClick:()=>h(xe=>xe===ne?null:ne),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${N===ne?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[Hl(ne),n.jsx("span",{className:"tabular-nums opacity-70",children:ie})]},ne))]}),Ie&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:Ie}),Ae.length===0?be.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"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:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:be.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:[ue.groups.map(ne=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Yt(ne.initiativeTitle&&!Vn(ne.initiativeTitle)?ne.initiativeTitle:ji(ne.initiativeId,"Initiative"))}),ne.workstreams.map(ie=>{var se,ye;const xe=`${ne.initiativeId}:${ie.workstreamId}`,K=Ke.has(xe),R=ie.rows[0]??null,U=R?Ul((se=R.session)==null?void 0:se.agentId,(ye=R.session)==null?void 0:ye.agentName):null,P=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((he,L)=>he+L.total,0):null,H=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((he,L)=>he+L.done,0):null,Q=P&&P>0?`Task ${(H??0)+1} of ${P}`:null,ge=P&&P>0?Math.round((H??0)/P*100):(R==null?void 0:R.progress)!=null?Vl(R.progress):null,ke=Yt(R!=null&&R.workstreamTitle&&!Vn(R.workstreamTitle)?R.workstreamTitle:ji(ie.workstreamId,"Workstream"));return n.jsxs("div",{className:"pl-4 border-l border-white/[0.08] mb-3",children:[n.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[n.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-1.5",children:[U&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${U.color}20`,color:U.color},children:U.name.charAt(0).toUpperCase()}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-[13px] font-semibold text-white/88",title:ke,children:ke}),U?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:U.color},title:U.displayLabel,children:U.displayLabel}):null]})]}),Q&&n.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/50",children:Q}),n.jsx("div",{className:"h-1 rounded-full bg-white/10 w-24",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,ge??0)}%`,backgroundColor:(U==null?void 0:U.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:ie.rows.map((he,L)=>n.jsx(Do,{row:he,index:L,sliceRunByScope:ee,busySessionId:C,expandedRowKey:te,setExpandedRowKey:z,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:g,onResumeWorkstream:j,onRestartSession:y,onPlayWorkstream:b,onIntervene:I,onOpenSliceDetail:k,runWorkstreamAction:ae,showInitiativeLabel:!1},he.key))}),ie.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>pe(he=>{const L=new Set(he);return L.has(xe)?L.delete(xe):L.add(xe),L}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:K?`Hide ${ie.completedCount} completed`:`${ie.completedCount} completed`})})]},ie.workstreamId)})]},ne.initiativeId)),ue.ungrouped.length>0&&n.jsxs("div",{children:[ue.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:ue.ungrouped.map((ne,ie)=>n.jsx(Do,{row:ne,index:ie,sliceRunByScope:ee,busySessionId:C,expandedRowKey:te,setExpandedRowKey:z,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:g,onResumeWorkstream:j,onRestartSession:y,onPlayWorkstream:b,onIntervene:I,onOpenSliceDetail:k,runWorkstreamAction:ae,showInitiativeLabel:!0},ne.key))})]})]})})]})});function Do({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:c,onFocusRunId:l,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:p,onPlayWorkstream:x,onIntervene:b,onOpenSliceDetail:g,runWorkstreamAction:j,showInitiativeLabel:y=!0}){var ie,xe,K,R,U,P,H,Q,ge,ke;const I=Zt(e.status??""),k=e.updatedAt,N=e.subtitle?e.subtitle:k?`Updated ${$t(k)}`:null,h=y&&(e.initiativeTitle||e.initiativeId)?Yt(e.initiativeTitle&&!Vn(e.initiativeTitle)?e.initiativeTitle:ji(e.initiativeId,"Initiative")):null,C=(ie=e.title)!=null&&ie.trim()?e.title:"",V=_m(C)&&((xe=e.workstreamTitle)!=null&&xe.trim())?e.workstreamTitle:C||e.workstreamTitle||"",te=ji(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),z=Yt(V&&!Vn(V)?V:te),Ie=N&&!Sm(N)?Yt(N):null,B=Vl(e.progress),ee=["running","active","in_progress","working","planning","dispatching"].includes(I),be=["paused","blocked","queued","pending"].includes(I),ve=p??x,Ae=B===null&&["running","active","in_progress","working","planning","dispatching"].includes(I),ue=e.session?r===e.session.id:!1,Ke=i===e.key,pe=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),ae=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),ne=Ul((K=e.session)==null?void 0:K.agentId,(R=e.session)==null?void 0:R.agentName);return n.jsxs(ce.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(t,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-visible rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 cursor-pointer transition-colors hover:border-white/[0.14]",onClick:()=>g==null?void 0:g(e,ae),role:"button",tabIndex:0,onKeyDown:se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),g==null||g(e,ae))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Nm(I)}`,"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":ne.color}:void 0,children:n.jsx(Xt,{name:((U=e.session)==null?void 0:U.agentName)??"OrgX",hint:((P=e.session)==null?void 0:P.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[h?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:h}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(jn,{type:"session",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:z,children:z})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Rn,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.08em] ${jm(I)}`,children:Hl(I)}),k&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:Rc(new Date(k),{addSuffix:!0})})]}),Ie?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:Ie,children:Ie}):null,null,(B!==null||Ae)&&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:B===null?"Live":`${B}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${B===100?" shimmer-on-complete":""}`,children:B===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,B)}%`,background:`linear-gradient(90deg, ${Ro(Eo((H=e.session)==null?void 0:H.agentId)).gradient[0]}, ${Ro(Eo((Q=e.session)==null?void 0:Q.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(gm,{nodes:im({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((se,ye)=>se+ye.total,0),completedTasks:e.milestoneProgress.reduce((se,ye)=>se+ye.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ge=e.session)==null?void 0:ge.agentName)??null,agentId:((ke=e.session)==null?void 0:ke.agentId)??null}),activeId:e.workstreamId,compact:!0})}),pe?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),a(ye=>ye===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:Ke?"Hide details":"Slice details"}),Ke?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:se=>se.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){c==null||c(e.session.id);return}l==null||l(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&&ee&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ue,onClick:()=>void j(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&&be&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ue,onClick:()=>void j(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&ve&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ue,onClick:()=>void j(e,ve,`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&&b&&n.jsx("button",{type:"button",disabled:ue,onClick:()=>void j(e,b,`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 Mm={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 Ri({icon:e="inbox",headline:t,description:s,primaryAction:r,secondaryAction:i,className:a}){return n.jsxs(ce.div,{className:le("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:Mm[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}),(r||i)&&n.jsxs(ce.div,{className:"mt-5 flex items-center gap-2",variants:Xr,custom:3,children:[r&&n.jsx("button",{type:"button",onClick:r.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:r.label}),i&&n.jsx("button",{type:"button",onClick:i.onClick,className:"control-pill px-4 text-[12px] font-medium",children:i.label})]})]})}const Tm=new Set(["awaiting_input","needs_review","failed"]);function Fo(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Em(e){var i,a;const t=e.initiativeId??((i=e.initiativeIds)==null?void 0:i[0])??"none",s=e.workstreamId??((a=e.workstreamIds)==null?void 0:a[0])??"none",r=(e.statusExplainer??"").trim().toLowerCase();return[t,s,e.status,e.primaryAction,r].join("|")}function Gl(e){const t=e.filter(r=>Tm.has(r.status)).sort((r,i)=>Fo(i.updatedAt??i.lastEventAt??"")-Fo(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=Em(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function Rm(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-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]"}function Lm(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function $m(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-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Dm(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 Fm(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 ja(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Vn(s)?`${t} ${ws(s)}`:s}function Pm(e){if(!e)return null;const t=Yt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function Om(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!Vn(r)){const a=Yt(r);if(a!=="Untitled session")return a}const i=Pm(e.statusExplainer);return i||(s?ja(s,"Workstream"):ja(e.sliceRunId,"Slice"))}const Bm=o.memo(function({sliceRuns:t,initiatives:s=[],title:r="Needs Input",className:i,showHeader:a=!0,panelStyle:c="card",onOpenDecisions:l,onFocusRunId:d,onReviewActivity:u,onOpenSliceDetail:p}){const x=o.useMemo(()=>Gl(t),[t]),b=o.useMemo(()=>{const y=new Map;for(const I of s)I.id&&y.set(I.id,I.name??I.id);return y},[s]),g=o.useMemo(()=>{const y=new Map;for(const I of s)for(const k of I.workstreams??[])k.id&&(y.has(k.id)||y.set(k.id,k.name??k.id));return y},[s]),j=y=>{var I;if(y.primaryAction==="resolve_decision"){l==null||l();return}if(y.primaryAction==="review_output"||y.primaryAction==="retry_slice"){u==null||u(y);return}if(y.primaryAction==="open_artifact"){const k=(I=y.artifacts.find(N=>N.url))==null?void 0:I.url;if(k&&typeof window<"u"){window.open(k,"_blank","noopener,noreferrer");return}u==null||u(y);return}if(y.runId){d==null||d(y.runId);return}y.sliceRunId&&(d==null||d(y.sliceRunId))};return n.jsxs(rr,{surface:c==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${c==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${i??""}`,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:r}),n.jsx("span",{className:"chip text-micro",children:x.length})]})}):null,x.length===0?n.jsx(Ri,{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:x.map(({item:y,duplicateCount:I},k)=>{var Ae;const N=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,h=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,C=(N?b.get(N):null)??ja(N,"Initiative"),V=y.workstreamTitle??(h?g.get(h)??null:null),te=Om(y,V,h),z=(Ae=y.statusExplainer)!=null&&Ae.trim().length?y.statusExplainer:"Review this slice to continue execution.",Ie=Yt(Fm(y)),B=Yt(z),ee=Yt(C),be=y.scope?y.scope.replace(/_/g," "):null,ve=y.updatedAt??y.lastEventAt??null;return n.jsxs(ce.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(k,7)*.022,ease:[.22,1,.36,1]},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] ${y.status==="failed"?"border-red-400/20":y.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>p==null?void 0:p(y),onKeyDown:ue=>{(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),p==null||p(y))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${$m(y.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(jn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:ee})]}),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:te,children:[n.jsx(jn,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:te})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:Ie,children:Ie}),B!==Ie&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:B,children:B})]}),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] ${Rm(y.status)}`,children:Lm(y.status)}),be?n.jsx("span",{className:"chip text-micro capitalize",children:be}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[I>1&&n.jsxs("span",{className:"chip text-micro",children:[I," similar updates"]}),typeof y.blockingDecisionCount=="number"&&y.blockingDecisionCount>0&&n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",y.blockingDecisionCount," task",y.blockingDecisionCount===1?"":"s"]}),typeof y.decisionCount=="number"&&y.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.decisionCount," decision",y.decisionCount===1?"":"s"]}),typeof y.artifactCount=="number"&&y.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.artifactCount," artifact",y.artifactCount===1?"":"s"]}),ve&&n.jsxs("span",{children:["Updated ",$t(ve)]})]}),y.decisionOptions&&y.decisionOptions.length>0&&y.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:ue=>ue.stopPropagation(),children:y.decisionOptions.slice(0,3).map(ue=>n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(y),className:"chip text-micro font-medium hover:bg-white/[0.08] transition-colors cursor-pointer",title:ue.description??ue.label,children:ue.label},ue.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:ue=>ue.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(y),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>j(y),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":y.status==="failed"?"teal":void 0,children:Dm(y)})]})]},y.sliceRunId)})})]})});function qm(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function zm(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 Wm(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Um(e){return{id:e.id,name:e.title,status:qm(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:zm(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 Po=150,Hm=12;function Oo(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Vm(){const e=new Date,t=864e5;return[{id:"init-1",name:"Q4 Feature Ship",status:"active",rawStatus:"active",priority:"high",health:38,daysRemaining:16,targetDate:new Date(e.getTime()+16*t).toISOString(),createdAt:new Date(e.getTime()-18*t).toISOString(),updatedAt:new Date(e.getTime()-5*6e4).toISOString(),activeAgents:2,totalAgents:3,description:"Finalize launch readiness for the Q4 initiative."},{id:"init-2",name:"Black Friday Email",status:"active",rawStatus:"active",priority:"medium",health:55,daysRemaining:10,targetDate:new Date(e.getTime()+10*t).toISOString(),createdAt:new Date(e.getTime()-22*t).toISOString(),updatedAt:new Date(e.getTime()-15*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Generate and validate campaign assets for holiday launch."}]}function Xl(e,t=null){return qs({queryKey:vs.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if(Gt())return Vm();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<Hm;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(Po),offset:String(i)});r&&Ns(u,r);const p=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:Ot({workspaceId:r})});if(!p.ok)break;const x=await p.json(),b=x.data??[];if(s.push(...b),!!!((l=x.pagination)!=null&&l.has_more)||b.length===0)break;i+=Po}const a=r.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),c=new Map;for(const d of s){const u=c.get(d.id);if(!u){c.set(d.id,d);continue}Oo(d.updated_at??d.created_at)>Oo(u.updated_at??u.created_at)&&c.set(d.id,d)}return Array.from(c.values()).filter(d=>!r||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===r).filter(d=>Wm(d.status)).sort((d,u)=>{const p=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-p}).map(Um)},enabled:e,staleTime:6e4})}const Jr=50,Bo=8;function Km(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Gm(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Xm(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Qm(e){const t=Xm(e.sequence);return{id:e.id,name:e.title,status:Km(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 Jm(e,t=null){return qs({queryKey:vs.liveInitiatives({limit:Jr*Bo,projectId:t}),queryFn:async()=>{var c;if(Gt())return[];const s=[];let r=0;for(let l=0;l<Bo;l+=1){const d=new URLSearchParams({limit:String(Jr),offset:String(r)});t&&t.trim().length>0&&Ns(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:Ot({workspaceId:t})});if(!u.ok)break;const p=await u.json(),x=p.initiatives??[];s.push(...x);const b=typeof p.total=="number"?p.total:null,g=(c=p.pagination)==null?void 0:c.has_more;if(!(typeof g=="boolean"?g:b!==null?r+x.length<b:x.length===Jr)||x.length===0)break;r+=Jr}const i=(t==null?void 0:t.trim())??"",a=i.length>0&&s.some(l=>(l.command_center_id??l.commandCenterId??"").trim().length>0);return s.filter(l=>!i||!a?!0:(l.command_center_id??l.commandCenterId??"").trim()===i).filter(l=>Gm(l.status)).map(Qm)},enabled:e,staleTime:3e4})}const Ql=o.createContext(null);function Ym({children:e}){const[t,s]=o.useState({artifactId:null}),r=o.useCallback((a,c)=>{s({artifactId:a,context:c})},[]),i=o.useCallback(()=>{s({artifactId:null})},[]);return n.jsx(Ql.Provider,{value:{state:t,open:r,close:i},children:e})}function Jl(){const e=o.useContext(Ql);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Zm(e){const{running:t,blocked:s,decisionsCount:r,completedToday:i,onDecisionsClick:a,onBlockedClick:c,onNewInitiative:l}=e,d=r+s;if(t===0&&d===0&&i===0)return{key:"idle-empty",segments:[{text:"All caught up. "},l?{text:"Start something new?",color:T.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]};if(t===0&&d===0)return{key:"idle-done",segments:[{text:`${i} done today`,color:T.teal},{text:" · all caught up"}]};if(s>0&&r>0){const u=s>20?"20+ blocked":`${s} blocked`;return{key:`blocked-decisions-${s}-${r}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:u,color:T.textMuted,clickable:!0,onClick:c},{text:" · "},{text:`${r} decisions`,color:T.amber,clickable:!0,onClick:a}]}}if(s>0){const u=s>20?"20+ blocked":`${s} blocked`;return{key:`blocked-${s}-${t}`,segments:[{text:u,color:T.textMuted,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}}return r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:T.lime},{text:" · "}]:[],{text:`${r} decisions`,color:T.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:T.lime},{text:" · all systems go"}]}}function qo(e){const{className:t}=e,{key:s,segments:r}=Zm(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(vt,{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:r.map((i,a)=>i.clickable&&i.onClick?n.jsx("button",{onClick:i.onClick,className:"font-semibold underline decoration-dotted underline-offset-4 transition-opacity hover:opacity-80",style:{color:i.color},children:i.text},a):n.jsx("span",{className:i.color?"font-semibold":"text-secondary",style:i.color?{color:i.color}:void 0,children:i.text},a))},s)})})}const Rg={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"},ep={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"},Lg=e=>ep[Zt(e)]??"text-white/60 bg-white/5 border-white/10",$g=e=>{const t=Zt(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"},Dg=e=>{const t=Zt(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"},Fg=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Pg=e=>{const t=Zt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},Ls=e=>{const t=Zt(e);return t==="blocked"||t==="failed"||t==="cancelled"?T.red:t==="active"||t==="in_progress"||t==="running"?T.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?T.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?T.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Ni={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:T.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:T.teal,tint:"rgba(20, 184, 166, 0.18)"}},tp=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function gi(e,t,s,r){if(!(e==null||s>2)){if(typeof e=="string"){const i=e.trim();i.length>0&&t.push(i);return}if(Array.isArray(e)){for(const i of e)gi(i,t,s+1,r);return}if(typeof e=="object"){if(r.has(e))return;r.add(e);for(const[i,a]of Object.entries(e)){const c=i.toLowerCase();typeof a=="string"?(tp.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&gi(a,t,s+1,r):typeof a=="object"&&a!==null&&gi(a,t,s+1,r)}}}}function np(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 ks(...e){const t=[],s=new Set;for(const r of e)gi(r,t,0,s);for(const r of t){const i=np(r);if(i)return Ni[i]}return Ni.unknown}function sp(e){return Ni[e]??Ni.unknown}const rp={xs:18,sm:24,md:30};function ip({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:Ti,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 ir({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=sp(e),a=rp[t];return n.jsx("span",{className:le("inline-flex items-center justify-center rounded-md",s),style:{width:a,height:a,color:i.accent,backgroundColor:i.tint,border:r?`1px solid ${i.accent}55`:"none"},title:i.label,"aria-label":i.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(ip,{provider:e})})})}function Yl({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=is(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const g=[];return e>0&&g.push({color:T.lime,fraction:e/c}),t>0&&g.push({color:T.red,fraction:t/c}),s>0&&g.push({color:T.amber,fraction:s/c}),g},[e,t,s,c]),d=2.5,u=(r-d)/2,p=2*Math.PI*u,x=r/2;if(c===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsx("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:i})]});let b=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsxs("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),l.map((g,j)=>{const y=g.fraction*p,I=-b;return b+=y,n.jsx(ce.circle,{cx:x,cy:x,r:u,fill:"none",stroke:g.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${y} ${p-y}`,strokeDashoffset:I,initial:a?!1:{strokeDasharray:`0 ${p}`},animate:{strokeDasharray:`${y} ${p-y}`},transition:{duration:.5,delay:j*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},j)})]}),n.jsx("div",{className:"relative z-10",children:i})]})}const Yr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function Fa(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Pa(e,t){if(typeof t=="number")return`${e}${t+1}`}const ap=(e,t)=>{const s=Fa(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:Pa("W",s)}},op=(e,t)=>{const s=Fa(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:Pa("M",s)}},lp=(e,t)=>{const s=Fa(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:Pa("T",s)}};function na(e){return[...e].sort((t,s)=>{const r=typeof t.sequenceIndex=="number"?t.sequenceIndex:Number.POSITIVE_INFINITY,i=typeof s.sequenceIndex=="number"?s.sequenceIndex:Number.POSITIVE_INFINITY;if(r!==i)return r-i;const a=t.createdAt?Date.parse(t.createdAt):0,c=s.createdAt?Date.parse(s.createdAt):0;return a!==c?a-c:0})}function cp(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 dp({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var l;const i=Rd(e),a=o.useMemo(()=>vs.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=qs({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Yr;if(Gt())return cp(e);if(!i)return{...Yr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,p=async k=>{try{const N=new URLSearchParams({type:k,initiative_id:e,limit:"100"}),h=await fetch(`/orgx/api/entities?${N.toString()}`,{headers:u});return h.ok?await h.json():{data:[]}}catch{return{data:[]}}},[x,b,g]=await Promise.all([p("workstream"),p("milestone"),p("task")]),j=Array.isArray(x.data)?na(x.data.map(k=>ap(k,e))):[],y=Array.isArray(b.data)?na(b.data.map(k=>op(k,e))):[],I=Array.isArray(g.data)?na(g.data.map(k=>lp(k,e))):[];return{initiativeId:e,workstreams:j,milestones:y,tasks:I}}});return{details:(i?c.data:null)??(e?{...Yr,initiativeId:e}:Yr),isLoading:i?c.isLoading:!1,error:i?((l=c.error)==null?void 0:l.message)??null:null,refetch:c.refetch}}function up(){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 Oa({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return qs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Gt())return up();const r=await fetch("/orgx/api/agents/catalog");if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(i||`Agent catalog failed (${r.status})`)}return await r.json()},enabled:e,staleTime:t,refetchInterval:s??(e?8e3:!1)})}function br(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:T.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:T.iris,bg:"rgba(124,124,255,0.10)"}}function mp(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function pp(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function fp({open:e,onClose:t,onLaunched:s}){var Q,ge,ke,se,ye,he;const r=Oa({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=Xl(e),[a,c]=o.useState(""),[l,d]=o.useState(""),[u,p]=o.useState(""),[x,b]=o.useState(""),[g,j]=o.useState("auto"),[y,I]=o.useState(""),[k,N]=o.useState(null),[h,C]=o.useState(null),[V,te]=o.useState("starter"),[z,Ie]=o.useState(!1),[B,ee]=o.useState(1),be=Gt(),ve=o.useMemo(()=>{const L=l.trim();return L?(i==null?void 0:i.find(q=>q.id===L))??null:null},[i,l]),{details:Ae}=dp({initiativeId:ve?ve.id:null,enabled:e&&!!ve}),ue=o.useMemo(()=>mp(Ae),[Ae]),Ke=o.useMemo(()=>pp(Ae,u||null),[Ae,u]),pe=((Q=r.data)==null?void 0:Q.agents)??[],ae=o.useMemo(()=>{const L=a.trim();return L?pe.find(q=>q.id===L)??null:null},[pe,a]);o.useEffect(()=>{var q,G;if(!e)return;const L=((q=pe.find(re=>re.isDefault))==null?void 0:q.id)??((G=pe[0])==null?void 0:G.id)??"";!a&&L&&c(L)},[pe,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const L=i??[],q=L.length===1?L[0]:null;q&&d(q.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const L=(ae==null?void 0:ae.model)??"",q=L.includes("openrouter")?"openrouter":L.includes("anthropic")?"anthropic":L.includes("openai")?"openai":"auto";j(q)},[e,ae==null?void 0:ae.model,a]),o.useEffect(()=>{e&&(N(null),C(null),te("starter"),ee(1))},[e]),o.useEffect(()=>{p(""),b("")},[l]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(y.trim().length>0||ve&&I(`Kick off: ${ve.name}`))},[y,e,ve]);const ne=!!a.trim()&&!!l.trim(),ie=B===1?!!a.trim():B===2?!!l.trim():ne,xe=async()=>{var Ge;const L=(h==null?void 0:h.checkout)??"/orgx/api/billing/checkout",q=V&&V.trim().length>0?V.trim():"starter",re=await(await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:q,billingCycle:"monthly"})})).json().catch(()=>null),Re=((Ge=re==null?void 0:re.data)==null?void 0:Ge.url)??(re==null?void 0:re.url)??null;if(!Re)throw new Error((re==null?void 0:re.error)??"Checkout unavailable");window.open(Re,"_blank","noopener,noreferrer")},K=async()=>{var Re;const L=(h==null?void 0:h.portal)??"/orgx/api/billing/portal",G=await(await fetch(L,{method:"POST"})).json().catch(()=>null),re=((Re=G==null?void 0:G.data)==null?void 0:Re.url)??(G==null?void 0:G.url)??null;if(!re)throw new Error((G==null?void 0:G.error)??"Billing portal unavailable");window.open(re,"_blank","noopener,noreferrer")},R=async()=>{if(!(!ne||z)){if(be){t(),s==null||s();return}N(null),C(null),Ie(!0);try{const L={agentId:a.trim(),message:y.trim()?y.trim():void 0,initiativeId:l.trim(),initiativeTitle:(ve==null?void 0:ve.name)??null,workstreamId:u.trim()?u.trim():null,taskId:x.trim()?x.trim():null,provider:g!=="auto"?g:null},q=new URLSearchParams;q.set("agentId",L.agentId),q.set("initiativeId",L.initiativeId),L.initiativeTitle&&q.set("initiativeTitle",L.initiativeTitle),L.workstreamId&&q.set("workstreamId",L.workstreamId),L.taskId&&q.set("taskId",L.taskId),L.message&&q.set("message",L.message),L.provider&&q.set("provider",L.provider);const G=await fetch(`/orgx/api/agents/launch?${q.toString()}`,{method:"POST"}),re=await G.json().catch(()=>null);if(!G.ok||!(re!=null&&re.ok))throw(re==null?void 0:re.code)==="upgrade_required"&&(C(re.actions??null),te(re.requiredPlan??"starter")),new Error((re==null?void 0:re.error)??`Launch failed (${G.status})`);t(),s==null||s()}catch(L){N(L instanceof Error?L.message:"Launch failed")}finally{Ie(!1)}}},U=!!((ge=ae==null?void 0:ae.run)!=null&&ge.runId)&&!!((ke=ae==null?void 0:ae.run)!=null&&ke.pid),P=async()=>{var L;if(!(!((L=ae==null?void 0:ae.run)!=null&&L.runId)||!U||z)&&!be){N(null),Ie(!0);try{const q=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(ae.run.runId)}`,{method:"POST"}),G=await q.json().catch(()=>null);if(!q.ok||!(G!=null&&G.ok))throw new Error((G==null?void 0:G.error)??`Stop failed (${q.status})`);await r.refetch()}catch(q){N(q instanceof Error?q.message:"Stop failed")}finally{Ie(!1)}}},H=async()=>{var L;if(!(!((L=ae==null?void 0:ae.run)!=null&&L.runId)||z)){if(be){t(),s==null||s();return}N(null),Ie(!0);try{const q=new URLSearchParams;q.set("runId",ae.run.runId),y.trim()&&q.set("message",y.trim()),g&&g!=="auto"&&q.set("provider",g);const G=await fetch(`/orgx/api/agents/restart?${q.toString()}`,{method:"POST"}),re=await G.json().catch(()=>null);if(!G.ok||!(re!=null&&re.ok))throw new Error((re==null?void 0:re.error)??`Restart failed (${G.status})`);t(),s==null||s()}catch(q){N(q instanceof Error?q.message:"Restart failed")}finally{Ie(!1)}}};return e?n.jsx(Ei,{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(([L,q])=>n.jsxs("button",{type:"button",onClick:()=>ee(L),className:le("rounded-full px-3 py-1 transition-colors",B===L?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[L,". ",q]},L))})]}),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:[r.isLoading&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading agent catalog…"}),r.error&&n.jsx("div",{className:"rounded-xl border border-rose-300/20 bg-rose-400/10 p-4 text-body text-rose-100",children:r.error.message}),n.jsx(vt,{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:[B===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:L=>c(L.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-[#BFFF00]/30",children:pe.map(L=>{const q=br(L.status);return n.jsxs("option",{value:L.id,children:[L.name," (",L.id,") · ",q.label]},L.id)})})]}),ae&&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:ae.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${br(ae.status).color}55`,color:br(ae.status).color,backgroundColor:br(ae.status).bg},children:br(ae.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:"})," ",ae.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",ae.workspace??"unknown"]}),((se=ae.context)==null?void 0:se.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",ae.context.initiativeTitle??ae.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:g,onChange:L=>j(L.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-[#BFFF00]/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."})]}),ae.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",ae.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",ae.run.status,")"]})]}),ae.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:P,disabled:!U||z,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:H,disabled:z,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"})]})]})]})]}),B===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:l,onChange:L=>d(L.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-[#BFFF00]/30",children:[n.jsx("option",{value:"",children:"Select an initiative…"}),(i??[]).map(L=>n.jsx("option",{value:L.id,children:L.name},L.id))]})]}),n.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream (optional)"}),n.jsxs("select",{value:u,onChange:L=>p(L.target.value),disabled:!ve,className:le("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-[#BFFF00]/30",!ve&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),ue.map(L=>n.jsx("option",{value:L.id,children:L.name},L.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:x,onChange:L=>b(L.target.value),disabled:!ve,className:le("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-[#BFFF00]/30",!ve&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),Ke.slice(0,80).map(L=>n.jsx("option",{value:L.id,children:L.title},L.id))]}),Ke.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),B===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:y,onChange:L=>I(L.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-[#BFFF00]/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:((ae==null?void 0:ae.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:((ve==null?void 0:ve.name)??l.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((ye=ue.find(L=>L.id===u))==null?void 0:ye.name)??u:"Any"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:x.trim()?((he=Ke.find(L=>L.id===x))==null?void 0:he.title)??x:"Any"})]})]})]})]})]},B)}),k&&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:k}),h&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void xe().catch(L=>N(L instanceof Error?L.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 K().catch(L=>N(L instanceof Error?L.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"}),h.pricing&&n.jsx("a",{href:h.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:B===1?"Pick an agent to configure.":B===2?"Select an initiative scope (required).":ne?"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:[B>1&&n.jsx("button",{type:"button",onClick:()=>ee(L=>L>1?L-1:L),disabled:z,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"}),B<3?n.jsx("button",{type:"button",onClick:()=>ee(L=>L<3?L+1:L),disabled:!ie||z,className:le("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ie&&!z?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ie&&!z?{backgroundColor:T.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:R,disabled:!ne||z,className:le("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ne&&!z?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ne&&!z?{backgroundColor:T.lime}:void 0,children:z?"Launching…":"Launch"})]})]})]})}):null}function hp({breadcrumbs:e,typeBadge:t,onClose:s,footer:r,children:i}){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,c)=>n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[c>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 ${c===e.length-1?"text-primary font-medium":""}`,children:a.label}):n.jsx("span",{className:`truncate ${c===e.length-1?"text-primary font-medium":""}`,children:a.label})]},c)),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(jn,{type:t.icon,size:11,className:"opacity-90"}),t.label]})]}),n.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",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:i}),r&&n.jsx("div",{className:"flex-shrink-0 border-t border-subtle px-5 py-3 sm:px-6",children:r})]})}const sa=10,gp=20;function xp(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:T.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:T.iris,bg:"rgba(124,124,255,0.10)"}}function yp(e){return e?e.includes("error")||e.includes("fail")?T.red:e.includes("decision")||e.includes("block")?T.amber:e.includes("complete")||e.includes("success")?T.teal:e.includes("start")||e.includes("launch")?T.lime:T.iris:T.iris}const bp={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},Zr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function wp(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function vp({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var ee,be,ve,Ae,ue,Ke;const[d,u]=o.useState(!1),[p,x]=o.useState(!1),[b,g]=o.useState(null),j=Er(s),y=xp((r==null?void 0:r.status)??null),I=Da(s),k=o.useMemo(()=>{let pe=0,ae=0,ne=0,ie=0;for(const xe of i)xe.status==="running"||xe.status==="queued"||xe.status==="pending"?pe++:xe.status==="blocked"?ae++:xe.status==="failed"||xe.status==="cancelled"?ne++:(xe.status==="completed"||xe.status==="archived")&&ie++;return{running:pe,blocked:ae,failed:ne,completed:ie}},[i]),N=o.useMemo(()=>[...i].sort((pe,ae)=>Date.parse(ae.updatedAt??ae.lastEventAt??ae.startedAt??"")-Date.parse(pe.updatedAt??pe.lastEventAt??pe.startedAt??"")),[i]),h=d?N:N.slice(0,sa),C=N.length>sa,V=o.useMemo(()=>[...a].sort((pe,ae)=>Date.parse(ae.timestamp)-Date.parse(pe.timestamp)).slice(0,gp),[a]),te=!!((ee=r==null?void 0:r.run)!=null&&ee.runId)&&!!((be=r==null?void 0:r.run)!=null&&be.pid),z=async()=>{var pe;if(!(!((pe=r==null?void 0:r.run)!=null&&pe.runId)||!te||p)){g(null),x(!0);try{const ae=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),ne=await ae.json().catch(()=>null);if(!ae.ok||!(ne!=null&&ne.ok))throw new Error((ne==null?void 0:ne.error)??`Stop failed (${ae.status})`);l==null||l()}catch(ae){g(ae instanceof Error?ae.message:"Stop failed")}finally{x(!1)}}},Ie=async()=>{var pe;if(!(!((pe=r==null?void 0:r.run)!=null&&pe.runId)||p)){g(null),x(!0);try{const ae=new URLSearchParams;ae.set("runId",r.run.runId);const ne=await fetch(`/orgx/api/agents/restart?${ae.toString()}`,{method:"POST"}),ie=await ne.json().catch(()=>null);if(!ne.ok||!(ie!=null&&ie.ok))throw new Error((ie==null?void 0:ie.error)??`Restart failed (${ne.status})`);l==null||l()}catch(ae){g(ae instanceof Error?ae.message:"Restart failed")}finally{x(!1)}}};if(!e)return null;const B=r!=null&&r.run?n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"text-caption text-secondary",children:["Run ",r.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-1",children:["(",r.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:z,disabled:!te||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:Ie,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(Ei,{open:e,onClose:t,maxWidth:"max-w-3xl",children:[n.jsx("div",{className:"h-[2px] rounded-t-xl",style:{background:`linear-gradient(90deg, ${I}, transparent)`}}),n.jsx(hp,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:B,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(ce.div,{className:"flex items-start gap-5",variants:bp,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(Yl,{running:k.running,blocked:k.blocked+k.failed,paused:0,size:72,children:n.jsx(Xt,{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-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"status-pill",style:{color:y.color,backgroundColor:y.bg,borderColor:`${y.color}30`},children:y.label})]}),j&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:j})]})]}),n.jsx(ce.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:Zr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:k.running,color:T.lime},{label:"Blocked",value:k.blocked,color:T.red},{label:"Failed",value:k.failed,color:T.amber},{label:"Completed",value:k.completed,color:T.teal}].map(pe=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:pe.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:pe.value>0?pe.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:pe.value})]},pe.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(ce.div,{variants:Zr,initial:"hidden",animate:"visible",custom:2,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Sessions"}),i.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:[h.map(pe=>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:Ls(pe.status)}}),n.jsxs("button",{onClick:()=>{c(pe.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:pe.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:$t(pe.updatedAt??pe.lastEventAt??pe.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:pe.status}),pe.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(pe.progress),"%"]})]})]})]})]},pe.id)),C&&n.jsx("button",{type:"button",onClick:()=>u(pe=>!pe),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${N.length-sa} older sessions`})]})]}),n.jsxs(ce.div,{variants:Zr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),V.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:V.map((pe,ae)=>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:yp(pe.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:pe.title??pe.summary??pe.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:$t(pe.timestamp)})]})]},pe.id??ae))})]})]}),n.jsx(wp,{}),r&&n.jsxs(ce.div,{variants:Zr,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:(ve=r.model)!=null&&ve.includes("openrouter")?"OpenRouter":(Ae=r.model)!=null&&Ae.includes("anthropic")?"Anthropic":(ue=r.model)!=null&&ue.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:le("text-[14px] truncate",r.model?"text-primary":"text-muted"),children:r.model??"Not configured"})]}),r.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:r.workspace})]}),((Ke=r.context)==null?void 0:Ke.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:r.context.initiativeTitle})]})]})]}),b&&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:b})]})})]})}const ei=120,zo=10,kp=24,Wo=520,jp=58,Np=56,Ip=20,Ap=8,Ba=new Set(["running","active","in_progress","working","planning","handoff","review"]),_p=new Set(["blocked","failed"]),Sp=10,Cp=[{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"}],Mp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Na=[{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 it(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function vn(e,t){const s=it(e),r=it(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of Na)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Tp(e){const t=vn(e.agentId,e.agentName);if(t)return t;const s=[e.groupLabel,e.title,e.runtimeLabel,e.lastEventSummary];for(const r of s){const i=vn(null,r);if(i)return i}return null}function Ep(e){const t=it(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(r=>typeof r=="string"&&r.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 Zl(e){const t=Tp(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=it(e.agentId),r=it(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=Ep(e);return i==="codex"?{agentId:"runtime:codex",agentName:"Codex"}:i==="claude-code"?{agentId:"runtime:claude-code",agentName:"Claude Code"}:i==="openclaw"?{agentId:"runtime:openclaw",agentName:"OpenClaw"}:i==="api"?{agentId:"runtime:api",agentName:"OrgX API"}:{agentId:null,agentName:null}}function Rp(e){const t=Zl(e),s=it(t.agentId);if(s)return`id:${s}`;const r=it(t.agentName);return r?`name:${r}`:"unassigned"}function Lp(e){const t=e.trim();return t?Mp.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function Ii(e){const t=(e??"").trim();return t?zs(t):!1}function $p(e){var t,s;return!!(Ii((t=e.context)==null?void 0:t.initiativeId)||Ii(((s=e.run)==null?void 0:s.initiativeId)??null))}function ti(e){if(vn(e.agentId,e.agentName))return!0;const s=it(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function wn(e){const t=it(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=it(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=it(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":Ba.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function Ia(e){const t=it(e);return t?Ba.has(t)||_p.has(t):!1}function Uo(e){const t=it(e);return t?Ba.has(t):!1}function Ys(e){return e?!!(Ia(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function Dp(e){return e?e.state==="active":!1}function Fp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Ln(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ni(e,t){return Ln(t.updatedAt??t.lastEventAt??t.startedAt)-Ln(e.updatedAt??e.lastEventAt??e.startedAt)}function Pp({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=Ls(e),l=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:c}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",l," sessions"]}),n.jsx(ce.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(vt,{children:i&&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,u)=>{const p=r===d.id,x=ks(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(u*.02,.1)},className:le("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(ir,{provider:x.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:$t(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const Op=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:c,agentFilter:l,onReconnect:d,onLaunched:u,connectionStatus:p,runtimeInstances:x=[],showSyntheticEntities:b=!1,autopilotState:g=null}){var Nt;const[j,y]=o.useState(new Set),[I,k]=o.useState(!1),[N,h]=o.useState(!1),[C,V]=o.useState(0),[te,z]=o.useState(null),[Ie,B]=o.useState(!1),ee=Oa({enabled:!0}),be=((Nt=ee.data)==null?void 0:Nt.agents)??[],ve=o.useMemo(()=>Lr(a),[a]),Ae=o.useMemo(()=>ve===null?s:s.filter(O=>Ln(O.timestamp)>=ve),[s,ve]);o.useMemo(()=>{var fe,Te,Qe;const O=new Map,_e=[...Ae].sort((tt,Y)=>Ln(Y.timestamp)-Ln(tt.timestamp));for(const tt of _e){const Y=tt.runId;if(!Y||O.has(Y))continue;const We=((fe=tt.summary)==null?void 0:fe.trim())??((Te=tt.description)==null?void 0:Te.trim())??((Qe=tt.title)==null?void 0:Qe.trim())??"";We.length>0&&O.set(Y,We)}return O},[Ae]);const{agents:ue,hiddenGroupCount:Ke,filteredOutGroupsByDate:pe,filteredOutSessionsByDate:ae,visibleSessionCount:ne,archivedGroups:ie,sessionCountInScope:xe}=o.useMemo(()=>{var Dt;const O=b?t.nodes:t.nodes.filter(W=>!Ii(W.initiativeId)),_e=b?be:be.filter(W=>!$p(W)),fe=b?x:x.filter(W=>!Ii(W.initiativeId)),Te=new Map,Qe=new Map,tt=[...fe].sort((W,Ne)=>Ln(Ne.lastEventAt??Ne.lastHeartbeatAt)-Ln(W.lastEventAt??W.lastHeartbeatAt));for(const W of tt){W.runId&&!Te.has(W.runId)&&Te.set(W.runId,W);const Ne=vn(W.agentId,W.agentName??W.displayName),Ue=it((Ne==null?void 0:Ne.agentId)??W.agentId);if(Ue){const Ve=Qe.get(Ue)??[];Ve.push(W),Qe.set(Ue,Ve)}}const Y=new Map;for(const W of O){const Ne=Zl(W),Ue=Rp(W),Ve=it(Ne.agentId),ze=it(Ne.agentName);let qe=Y.get(Ue)??null;if(!qe&&Ve&&ze){const Oe=`name:${ze}`,ut=Y.get(Oe);ut&&(Y.delete(Oe),ut.groupKey=Ue,Y.set(Ue,ut),qe=ut)}if(!qe&&ze){const Oe=Array.from(Y.values()).find(ut=>it(ut.agentName)===ze);Oe&&(qe=Oe)}qe?(qe.nodes.push(W),!qe.agentId&&Ne.agentId&&(qe.agentId=Ne.agentId),(qe.agentName==="OrgX"||!qe.agentName)&&Ne.agentName&&(qe.agentName=Ne.agentName)):Y.set(Ue,{groupKey:Ue,agentId:Ne.agentId,agentName:Ne.agentName??Ne.agentId??"OrgX",nodes:[W],latest:W,runtime:null,runtimeActiveCount:0})}for(const W of _e){const Ne=vn(W.id,W.name),Ue=(Ne==null?void 0:Ne.agentId)??W.id,Ve=(Ne==null?void 0:Ne.agentName)??W.name,ze=it(Ue),qe=it(Ve),Oe=ze?`id:${ze}`:null,ut=qe?`name:${qe}`:null;let Ft=null;if(Oe&&Y.has(Oe))Ft=Oe;else if(ut&&Y.has(ut))Ft=ut;else{const pt=Array.from(Y.entries()).find(([,bt])=>ze&&it(bt.agentId)===ze||qe&&it(bt.agentName)===qe);Ft=(pt==null?void 0:pt[0])??null}if(Ft){const pt=Y.get(Ft);pt.catalogAgent=W,!pt.agentId&&Ue&&(pt.agentId=Ue),(pt.agentName==="OrgX"||!pt.agentName)&&Ve&&(pt.agentName=Ve),Oe&&pt.groupKey!==Oe&&!Y.has(Oe)&&(Y.delete(pt.groupKey),pt.groupKey=Oe,Y.set(Oe,pt))}else{const pt=Oe??ut??`catalog:${Ve.toLowerCase()}`;Y.set(pt,{groupKey:pt,agentId:Ue,agentName:Ve,nodes:[],latest:null,catalogAgent:W,runtime:null,runtimeActiveCount:0})}}for(const W of Na){const Ne=`orgx:${W.id}`,Ue=`id:${Ne}`;let Ve=Y.get(Ue)??null;if(!Ve){const ze=Array.from(Y.entries()).find(([,qe])=>{const Oe=vn(qe.agentId,qe.agentName);return it(Oe==null?void 0:Oe.agentId)===it(Ne)});ze&&(Y.delete(ze[0]),Ve=ze[1],Ve.groupKey=Ue,Y.set(Ue,Ve))}if(Ve||(Ve={groupKey:Ue,agentId:Ne,agentName:W.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Y.set(Ue,Ve)),Ve.agentId=Ne,Ve.agentName=W.name,!Ve.catalogAgent){const ze=_e.find(qe=>{const Oe=vn(qe.id,qe.name);return it(Oe==null?void 0:Oe.agentId)===it(Ne)});ze&&(Ve.catalogAgent=ze)}}const We=new Map(Na.map((W,Ne)=>[it(`orgx:${W.id}`),Ne]));for(const W of Y.values()){W.nodes.length>0&&(W.nodes.sort(ni),W.latest=W.nodes[0]);const Ne=[],Ue=new Set;if((Dt=W.latest)!=null&&Dt.runId){const ze=Te.get(W.latest.runId);ze&&!Ue.has(ze.id)&&(Ne.push(ze),Ue.add(ze.id))}for(const ze of W.nodes){if(!ze.runId)continue;const qe=Te.get(ze.runId);qe&&!Ue.has(qe.id)&&(Ne.push(qe),Ue.add(qe.id))}const Ve=it(W.agentId);if(Ve)for(const ze of Qe.get(Ve)??[])Ue.has(ze.id)||(Ne.push(ze),Ue.add(ze.id));Ne.sort((ze,qe)=>Ln(qe.lastEventAt??qe.lastHeartbeatAt)-Ln(ze.lastEventAt??ze.lastHeartbeatAt)),W.runtime=Ne[0]??null,W.runtimeActiveCount=Ne.filter(ze=>Dp(ze)).length}const we=Array.from(Y.values()).sort((W,Ne)=>{const Ue=ti(W),Ve=ti(Ne);if(Ue!==Ve)return Ue?-1:1;if(Ue&&Ve){const ze=W.nodes.length>0||(W.runtimeActiveCount??0)>0,qe=Ne.nodes.length>0||(Ne.runtimeActiveCount??0)>0;if(ze!==qe)return ze?-1:1;if(ze&&qe){if(W.latest&&Ne.latest)return ni(W.latest,Ne.latest);if(W.latest&&!Ne.latest)return-1;if(!W.latest&&Ne.latest)return 1}const Oe=vn(W.agentId,W.agentName),ut=vn(Ne.agentId,Ne.agentName),Ft=We.get(it((Oe==null?void 0:Oe.agentId)??W.agentId))??999,pt=We.get(it((ut==null?void 0:ut.agentId)??Ne.agentId))??999;if(Ft!==pt)return Ft-pt}return W.latest&&Ne.latest?ni(W.latest,Ne.latest):W.latest&&!Ne.latest?-1:!W.latest&&Ne.latest?1:W.agentName.localeCompare(Ne.agentName)}),X=Ll(a),$e=X.id==="live",He=X.minutes===null||$e?null:Date.now()-X.minutes*6e4,De=[],st=[];let dt=0,Ct=0;for(const W of we){const Ne=(W.runtimeActiveCount??0)>0,Ue=ti(W);if(W.nodes.length===0){const Oe=Ys(W.catalogAgent);(Ue||$e&&(Oe||Ne))&&De.push(W);continue}if($e){const Oe=W.nodes.filter(pt=>Ia(wn(pt))),ut=W.nodes.filter(pt=>!Ia(wn(pt))),Ft=Ys(W.catalogAgent);if(Oe.length===0){Ue||Ft||Ne?De.push({...W,nodes:[],latest:null}):(dt+=1,Ct+=W.nodes.length,st.push(W));continue}Ct+=ut.length,ut.length>0&&st.push({...W,nodes:ut,latest:ut[0]??null}),De.push({...W,nodes:Oe,latest:Oe[0]??null});continue}if(He===null){De.push(W);continue}const Ve=W.nodes.filter(Oe=>Uo(wn(Oe))?!0:Ln(Oe.updatedAt??Oe.lastEventAt??Oe.startedAt)>=He),ze=Ys(W.catalogAgent);if(Ve.length===0){Ue||ze||Ne?De.push({...W,nodes:[],latest:null}):(dt+=1,Ct+=W.nodes.length,st.push(W));continue}const qe=W.nodes.filter(Oe=>Uo(wn(Oe))?!1:Ln(Oe.updatedAt??Oe.lastEventAt??Oe.startedAt)<He);Ct+=qe.length,qe.length>0&&st.push({...W,nodes:qe,latest:qe[0]}),De.push({...W,nodes:Ve,latest:Ve[0]})}return{agents:De.slice(0,ei),hiddenGroupCount:Math.max(0,De.length-ei),filteredOutGroupsByDate:dt,filteredOutSessionsByDate:Ct,visibleSessionCount:De.slice(0,ei).reduce((W,Ne)=>W+Ne.nodes.length,0),archivedGroups:st,sessionCountInScope:O.length}},[a,t.nodes,be,x,b]);o.useEffect(()=>{h(!1),V(0)},[a]);const K=o.useMemo(()=>ie.reduce((O,_e)=>O+_e.nodes.length,0),[ie]),R=o.useMemo(()=>ue.filter(O=>O.nodes.length>0).map(O=>O.groupKey),[ue]),{activeAgents:U,idleOrgxAgents:P,activeAgentCount:H}=o.useMemo(()=>{const O=[],_e=[];for(const fe of ue)fe.nodes.length>0||(fe.runtimeActiveCount??0)>0||Ys(fe.catalogAgent)?O.push(fe):ti(fe)?_e.push(fe):O.push(fe);return{activeAgents:O,idleOrgxAgents:_e,activeAgentCount:O.filter(fe=>fe.nodes.length>0||(fe.runtimeActiveCount??0)>0||Ys(fe.catalogAgent)).length}},[ue]),Q=o.useMemo(()=>{if(R.length===0)return{allCollapsed:!1,allExpanded:!0};let O=0;for(const _e of R)j.has(_e)&&(O+=1);return{allCollapsed:O===R.length,allExpanded:O===0}},[j,R]),ge=o.useMemo(()=>{const O=[];for(const _e of ie)for(const fe of _e.nodes)O.push({node:fe,agentName:_e.agentName});return O.sort((_e,fe)=>ni(_e.node,fe.node)),O.slice(0,(C+1)*Sp)},[ie,C]),ke=O=>{y(_e=>{const fe=new Set(_e);return fe.has(O)?fe.delete(O):fe.add(O),fe})},se=()=>{y(()=>Q.allCollapsed?new Set:new Set(R))},ye=o.useMemo(()=>te?ue.find(O=>O.groupKey===te)??null:null,[ue,te]),he=o.useMemo(()=>(ye==null?void 0:ye.nodes)??[],[ye]),L=o.useMemo(()=>{if(!ye)return[];const O=it(ye.agentName),_e=it(ye.agentId),fe=vn(ye.agentId,ye.agentName);return Ae.filter(Te=>{const Qe=it(Te.agentName),tt=it(Te.agentId),Y=vn(Te.agentId,Te.agentName);return O!==null&&Qe===O||_e!==null&&tt===_e||fe!==null&&Y!==null&&it(fe.agentId)===it(Y.agentId)})},[Ae,ye]),q=xe===0,G=be.length>0,re=o.useRef(null),[Re,Ge]=o.useState(0),[Ee,$]=o.useState(0),rt=o.useCallback(O=>{const _e=O.currentTarget.scrollTop;Ge(fe=>Math.abs(fe-_e)<1?fe:_e)},[]);o.useEffect(()=>{const O=re.current;if(!O)return;const _e=()=>{const fe=O.clientHeight,Te=O.scrollTop;$(Qe=>Qe===fe?Qe:fe),Ge(Qe=>Math.abs(Qe-Te)<1?Qe:Te)};if(_e(),typeof ResizeObserver<"u"){const fe=new ResizeObserver(()=>_e());return fe.observe(O),()=>fe.disconnect()}return window.addEventListener("resize",_e),()=>window.removeEventListener("resize",_e)},[U.length]);const{visibleAgentGroups:Le,topVirtualSpacerPx:Xe,bottomVirtualSpacerPx:kt,virtualizationEnabled:jt}=o.useMemo(()=>{if(!(U.length>kp&&Ee>0))return{visibleAgentGroups:U,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const _e=U.map(we=>{const $e=j.has(we.groupKey)?0:Math.min(we.nodes.length,zo);let He=jp;return $e>0&&(He+=Ip+$e*Np,we.nodes.length>$e&&(He+=20)),He+Ap}),fe=new Array(_e.length+1).fill(0);for(let we=0;we<_e.length;we+=1)fe[we+1]=fe[we]+_e[we];const Te=fe[fe.length-1],Qe=Math.max(0,Re-Wo),tt=Re+Ee+Wo;let Y=0;for(;Y<U.length&&fe[Y+1]<Qe;)Y+=1;let We=Y;for(;We<U.length&&fe[We]<tt;)We+=1;return We<=Y&&(We=Math.min(U.length,Y+1)),{visibleAgentGroups:U.slice(Y,We),topVirtualSpacerPx:fe[Y],bottomVirtualSpacerPx:Math.max(0,Te-fe[We]),virtualizationEnabled:!0}},[U,j,Re,Ee]);return n.jsxs(rr,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(fp,{open:I,onClose:()=>k(!1),onLaunched:()=>{ee.refetch(),u==null||u()}}),n.jsx(vp,{open:te!==null,onClose:()=>z(null),agentName:(ye==null?void 0:ye.agentName)??"",catalogAgent:(ye==null?void 0:ye.catalogAgent)??null,sessions:he,activity:L,onSelectSession:i,onRefresh:()=>ee.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:[H," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:se,disabled:R.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Q.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Q.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>k(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:re,onScroll:rt,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[ue.length===0&&!q&&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."})]}),ue.length===0&&q&&!d&&n.jsx(Ri,{icon:"agents",headline:"No active sessions yet",description:"Start a session to see agent conversations here."}),l&&c&&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: ",l]}),n.jsx("button",{type:"button",onClick:()=>c(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[jt&&Xe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Xe}}),Le.map(O=>{var pt;const _e=O.groupKey,fe=j.has(_e),Te=O.latest,Qe=Te?wn(Te):null,tt=(g==null?void 0:g.activeRunId)!=null&&(Te==null?void 0:Te.runId)!=null&&g.activeRunId===Te.runId,Y=tt&&(g==null?void 0:g.state)==="running"?"running":Qe,We=tt&&(g==null?void 0:g.state)==="running"&&g.activeWorkstreamTitle?`Working on ${g.activeWorkstreamTitle}`:null,we=O.nodes.length>0,X=O.nodes.length===1,$e=Ys(O.catalogAgent),He=O.runtime??null,De=(O.runtimeActiveCount??0)>0,st=!we&&De&&He!==null,dt=we||st,Ct=Te?r===Te.id:!1,Dt=O.agentName||((pt=O.catalogAgent)==null?void 0:pt.name)||O.agentId||"OrgX",W=vn(O.agentId,Dt),Ne=(W==null?void 0:W.agentName)??Lp(Dt),Ue=(W==null?void 0:W.role)??Er(Ne),Ve=ks(O.agentId,Ne,He==null?void 0:He.displayName,Te==null?void 0:Te.runtimeProvider,Te==null?void 0:Te.runtimeClient),ze=W===null&&(Ve.id==="codex"||Ve.id==="openai"||Ve.id==="anthropic"||Ve.id==="openclaw"),qe=Ue?`${Dt} — ${Ue}`:Dt,Oe=fe?[]:we?O.nodes.slice(0,zo):[],ut=Math.max(0,we?O.nodes.length-Oe.length:0),Ft=it(l)===it(Ne)||it(l)===it(qe);return n.jsxs(ce.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:le("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",Ct&&"border-white/20 bg-white/[0.05]",Ft&&"border-[#0AD4C4]/30",!we&&!$e&&!De&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{X?i(O.nodes[0].id):st?ke(_e):!we&&$e?z(_e):c?c(Ft?null:Ne):Te&&i(Te.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:[ze?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(ir,{provider:Ve.id,size:"sm",showRing:!1})}):n.jsx(Yl,{running:O.nodes.filter(bt=>{const At=wn(bt);return At==="running"||At==="handoff"||At==="review"}).length,blocked:O.nodes.filter(bt=>{const At=wn(bt);return At==="blocked"||At==="failed"}).length,paused:O.nodes.filter(bt=>{const At=wn(bt);return At==="paused"||At==="cancelled"}).length,size:36,children:n.jsx(Xt,{name:Ne,size:"sm",hint:`${O.agentId??""} ${Ne}`})}),W&&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"})}),Te&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ls(Y??Te.status),borderColor:T.cardBg}}),!Te&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:$e?Ls("running"):"rgba(255,255,255,0.2)",borderColor:T.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:Ue?`${Dt} — ${Ue}`:Dt,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[Ne,Ue&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Ue]})]})}),We&&n.jsx("p",{className:"truncate text-micro text-teal-400",title:We,children:We}),n.jsx("div",{className:"flex items-center gap-1.5",children:we?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const bt={};for(const At of O.nodes){const nt=wn(At);bt[nt]=(bt[nt]??0)+1}return Object.entries(bt).map(([At,nt])=>`${nt} ${At}`).join(" · ")})(),children:(()=>{const bt={};for(const nt of O.nodes){const Pt=wn(nt);bt[Pt]=(bt[Pt]??0)+1}const At=O.nodes.length;return Object.entries(bt).map(([nt,Pt])=>n.jsx("span",{style:{width:`${Pt/At*100}%`,backgroundColor:Ls(nt)}},nt))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:O.nodes.length})]}):$e||De?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:Ls("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,O.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:()=>z(_e),"aria-label":`View ${Ne} 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:()=>{dt&&ke(_e)},disabled:!dt,"aria-label":dt?fe?"Expand sessions":"Collapse sessions":"No sessions to expand",className:le("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",dt?"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:le("transition-transform",dt&&!fe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(vt,{initial:!1,children:dt&&!fe&&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 bt=new Map,At=[];for(const Je of Oe){const qt=wn(Je);if(qt==="blocked"||qt==="paused"||qt==="failed"){const Mt=`${qt}:${Je.blockerReason??""}`,_t=bt.get(Mt)??[];_t.push(Je),bt.set(Mt,_t)}else At.push(Je)}const nt=[];for(const[Je,qt]of bt)qt.length>3?nt.push({status:Je.split(":")[0],nodes:qt}):At.push(...qt);const Pt=(Je,qt)=>{const Mt=r===Je.id,_t=wn(Je),Ut=ks(Je.agentName,Je.title,Je.lastEventSummary,Je);return n.jsx(ce.button,{onClick:()=>i(Je.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(qt*.015,.12)},className:le("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Mt?"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(ir,{provider:Ut.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Je.title,children:Je.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:Ut.accent},children:Ut.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:_t}),n.jsx("span",{title:wi(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now()),children:$t(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now())})]}),Je.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(Je.progress)}%`,background:`linear-gradient(90deg, ${T.lime}, ${T.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:Ls(_t)},"aria-label":_t,title:_t})]})},Je.id)};return n.jsxs(n.Fragment,{children:[At.map((Je,qt)=>Pt(Je,qt)),nt.map(Je=>n.jsx(Pp,{status:Je.status,nodes:Je.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Je.status}-${Je.nodes.length}`))]})})(),ut>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",ut," older sessions hidden"]})]})})})]},_e)}),jt&&kt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:kt}})]}),P.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>B(O=>!O),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:le("transition-transform",Ie?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[P.length," idle agent",P.length===1?"":"s"]})]}),n.jsx(vt,{initial:!1,children:Ie&&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:P.map(O=>{const _e=vn(O.agentId,O.agentName),fe=(_e==null?void 0:_e.agentName)??O.agentName,Te=(_e==null?void 0:_e.role)??Er(fe);return n.jsxs("button",{type:"button",onClick:()=>z(O.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(Xt,{name:fe,size:"sm",hint:`${O.agentId??""} ${fe}`}),_e&&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:[fe,Te&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Te]})]})}),n.jsx("span",{className:"text-micro text-muted",children:"Idle"})]},O.groupKey)})})})})]}),Ke>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",ei," most recent agent groups (",Ke," older groups omitted)."]}),d&&p!=="connected"&&!G&&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:Cp.map(O=>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:O.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:O.name}),n.jsx("p",{className:"text-micro text-muted",children:O.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"})]},O.id))})]}),ae>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{h(O=>!O),N&&V(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:le("transition-transform",N?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[K," archived session",K===1?"":"s",pe>0?` across ${pe} agent${pe===1?"":"s"}`:""]})]}),n.jsx(vt,{initial:!1,children:N&&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:[ge.map(({node:O,agentName:_e})=>{const fe=wn(O),Te=O.runtimeProvider?{id:Fp(O.runtimeProvider)}:ks(O.agentName,O.title,O.lastEventSummary,O);return n.jsxs("button",{onClick:()=>i(O.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(ir,{provider:Te.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:_e}),n.jsx("span",{className:"text-micro text-muted",title:wi(O.updatedAt??O.lastEventAt??O.startedAt??Date.now()),children:$t(O.updatedAt??O.lastEventAt??O.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:O.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:fe})]})]},O.id)}),ge.length<K&&n.jsxs("button",{onClick:()=>V(O=>O+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 (",K-ge.length," remaining)"]})]})})})]})]})]})}),Bp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),qp=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),zp=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),Wp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Up=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function Zs(e){return e?Zt(e):""}function ra(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Hp(e){return e.some(t=>Bp.has(t))}function Vp(e){return e.some(t=>qp.has(t))}function Kp(e){return e.some(t=>zp.has(t))}function Gp(e){return e.some(t=>Wp.has(t))}function Xp(e){return e.some(t=>Up.has(t))}function ts(e,t,s){const r=e==="in_progress"?"In progress":e==="needs_attention"?"Needs attention":e==="completed"?"Completed":e==="failed"?"Failed":"Update",i=(s==null?void 0:s.tone)??(e==="completed"?"positive":e==="failed"?"critical":e==="needs_attention"?"warning":"neutral"),a=e==="completed"||e==="failed",c=e==="needs_attention"||e==="failed";return{status:e,label:r,sentence:t,nextAction:(s==null?void 0:s.nextAction)??null,tone:i,isTerminal:a,isActionRequired:c}}function Qp(e){const t=Zs(e.sessionStatus),s=Zs(e.sessionPhase),r=Zs(e.sessionState),i=Zs(e.sliceStatus),a=Zs(e.activityStatus),c=Zs(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(C=>C.length>0),u=ra(e.blockingDecisionCount),p=ra(e.nonBlockingDecisionCount),x=ra(e.blockerCount),b=l==="run_failed",g=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",j=b||Hp(d),y=Vp(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,I=Kp(d)||x>0,k=g||Gp(d),N=Xp(d)||l==="run_started";if(j)return ts("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(k&&!y&&!j&&x===0&&!e.blockerReason)return p>0?ts("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ts("completed","Execution completed successfully.",{tone:"positive"});if(y||I)return u>0||e.decisionRequired===!0||l==="decision_requested"?ts("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):ts("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:I?"critical":"warning"});if(k)return p>0?ts("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ts("completed","Execution completed successfully.",{tone:"positive"});if(N){const C=p>0?`Running with ${p} optional decision${p===1?"":"s"} available.`:"Running.";return ts("in_progress",C,{tone:"neutral"})}return ts("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const ia=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Jp(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function $s(e,t){const s=[];let r=0,i=0;ia.lastIndex=0;for(let a=ia.exec(e);a;a=ia.exec(e)){const[c]=a,l=a.index;l>r&&s.push(e.slice(r,l));const d=`${t}-${i++}`,u=a[1],p=a[2],x=a[3],b=a[4],g=a[5],j=a[6],y=a[7];u&&p&&Jp(p)?s.push(n.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):x?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:x},d)):b||g?s.push(n.jsx("strong",{className:"font-semibold text-white",children:b??g},d)):j||y?s.push(n.jsx("em",{className:"italic text-bright",children:j??y},d)):s.push(c),r=l+c.length}return r<e.length&&s.push(e.slice(r)),s}function Yp(e,t){const s=e.split(`
204
- `),r=[];return s.forEach((i,a)=>{r.push(...$s(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function xi(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Zp(e){const t=xi(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function ef(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function tf(e){const t=e.replace(/\r\n/g,`
205
- `).split(`
206
- `),s=[];let r=0;for(;r<t.length;){const i=t[r]??"",a=i.trim();if(!a){r+=1;continue}const c=i.includes("|"),l=t[r+1]??"";if(c&&l.includes("|")&&Zp(l)){const b=xi(i),j=xi(l).map(I=>ef(I));r+=2;const y=[];for(;r<t.length;){const I=t[r]??"";if(!I.trim()||!I.includes("|"))break;y.push(xi(I)),r+=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:b.map((I,k)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:j[k]??"left"},children:$s(I,`tbl-h-${r}-${k}`)},`tbl-h-${k}`))})}),n.jsx("tbody",{children:y.map((I,k)=>n.jsx("tr",{className:k<y.length-1?"border-b border-subtle":void 0,children:b.map((N,h)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:j[h]??"left"},children:$s(I[h]??"",`tbl-r-${r}-${k}-${h}`)},`tbl-r-${k}-c-${h}`))},`tbl-r-${k}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const b=a.slice(3).trim(),g=[];for(r+=1;r<t.length&&!(t[r]??"").trim().startsWith("```");)g.push(t[r]??""),r+=1;r<t.length&&(r+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[b&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:b}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:g.join(`
207
- `)})})]},`code-${r}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const b=d[1].length,g=d[2],j=b===1?"text-title font-semibold":b===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:le("tracking-[-0.01em] text-white",j),children:$s(g,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const b=[];for(;r<t.length;){const j=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!j)break;b.push(j[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:b.map((g,j)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:$s(g,`ul-${r}-${j}`)},`ul-${r}-${j}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const b=[];for(;r<t.length;){const j=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!j)break;b.push(j[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:b.map((g,j)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:$s(g,`ol-${r}-${j}`)},`ol-${r}-${j}`))},`ol-${r}`));continue}const x=[];for(;r<t.length;){const b=t[r]??"",g=b.trim();if(!g||/^(#{1,3})\s+/.test(g)||/^\s*[-*]\s+/.test(b)||/^\s*\d+\.\s+/.test(b)||g.startsWith("```"))break;x.push(b),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Yp(x.join(`
208
- `),`p-${r}`)},`p-${r}`))}return s}function _r({text:e,mode:t="inline",className:s}){const r=e.replace(/\r\n/g,`
209
- `);return r.trim()?t==="inline"?n.jsx("span",{className:s,children:$s(r,"inline")}):n.jsx("div",{className:le("space-y-2",s),children:tf(r)}):null}function ec(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function nf(e){if(!e)return;const t=ec(e.metadata);return t?{...e,...t}:e}const tc={run_started:{icon:"play",label:"Run started",color:T.teal},run_completed:{icon:"check_circle",label:"Run completed",color:T.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:T.red},artifact_created:{icon:"file",label:"Artifact",color:T.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:T.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:T.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:T.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:T.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:T.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:T.red},milestone_completed:{icon:"flag",label:"Milestone",color:T.cyan},delegation:{icon:"workflow",label:"Delegation",color:T.iris}};function Hn(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Aa(e){return e?e.toLowerCase():""}function sf(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Hn(t,["source","event","eventType","artifact_type","action","kind"]),Hn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function rf(e,t){const s=Aa(Hn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:T.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:T.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:T.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:T.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:T.cyan}:tc.artifact_created}function af(e){const t=nf(ec(e.metadata)),s=sf(e,t),r=Aa(Hn(t,["source"])),i=Aa(Hn(t,["action"])),a=Hn(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"&&Hn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:T.teal};if(a==="auto_continue_stopped"){const l=Hn(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Needs attention",color:T.red}:l==="budget_exhausted"?{icon:"infinity",label:"Paused",color:T.amber}:{icon:"infinity",label:"Paused",color:T.amber}}if(a==="autopilot_transition"){const l=Hn(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Needs attention",color:T.red}:{icon:"infinity",label:"In progress",color:T.teal}}const c=Hn(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Completed",color:T.lime}:c==="blocked"||c==="needs_decision"?{icon:"infinity",label:"Needs attention",color:T.amber}:{icon:"infinity",label:"In progress",color:T.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:T.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:T.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:T.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:T.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:T.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:T.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:T.teal};if(e.type==="artifact_created")return rf(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:T.red}:{icon:"shield_check",label:"Decision approved",color:T.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:T.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:T.teal}}return tc[e.type]??{icon:"message",label:"Activity",color:T.textMuted}}function of({icon:e,size:t=14,className:s}){const r={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",{...r,children:n.jsx("path",{d:"m8 6 10 6-10 6z"})});case"check_circle":return n.jsxs("svg",{...r,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",{...r,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",{...r,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",{...r,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",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M3 12h6M15 12h6"})]});case"shield":return n.jsxs("svg",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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(Bl,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...r,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",{...r,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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",{...r,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 Ai(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function _a(e){if(!e)return;const t=Ai(e.metadata);return t?{...e,...t}:e}function lf(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function cf(e){let t=0;for(const s of e){const r=_a(Ai(s.metadata)),i=r==null?void 0:r.costTotal;typeof i=="number"&&(t+=i)}return t<=0?null:t<.01?"<$0.01":`$${t.toFixed(2)}`}const df=o.memo(function({items:t,session:s,agentName:r,onBack:i,onOpenItem:a}){const[c,l]=o.useState(!1),d=o.useMemo(()=>[...t].sort((g,j)=>Date.parse(g.timestamp)-Date.parse(j.timestamp)),[t]),u=o.useMemo(()=>cf(d),[d]),p=o.useMemo(()=>{if(d.length<2)return null;const g=Date.parse(d[0].timestamp),y=Date.parse(d[d.length-1].timestamp)-g;return y<6e4?`${Math.round(y/1e3)}s`:y<36e5?`${Math.round(y/6e4)}m`:`${(y/36e5).toFixed(1)}h`},[d]),x=o.useMemo(()=>{let g=null,j=null,y=null,I=null,k=null;for(const h of d){const C=_a(Ai(h.metadata));if(C&&(!g&&typeof C.domain=="string"&&(g=C.domain),!j&&typeof C.provider=="string"&&(j=C.provider),!y&&typeof C.model=="string"&&(y=C.model),!I&&typeof C.spawn_guard_model_tier=="string"&&(I=C.spawn_guard_model_tier),!k&&typeof C.kickoff_context_hash=="string"&&(k=C.kickoff_context_hash),g&&(j||y)&&I&&k))break}return!(g||j||y||I||k)?null:{domain:g,provider:j,model:y,modelTier:I,kickoffContextHash:k}},[d]),b=(s==null?void 0:s.title)??r??"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:i,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:T.lime,boxShadow:`0 0 12px ${T.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:at(b)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-micro text-secondary",children:[r&&n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-subtle px-1 py-0.5",children:[n.jsx(Xt,{name:r,hint:(s==null?void 0:s.id)??(s==null?void 0:s.runId)??null,size:"xs"}),n.jsx("span",{children:r})]}),n.jsxs("span",{children:[d.length," turn",d.length!==1?"s":""]}),p&&n.jsx("span",{children:p}),u&&n.jsx("span",{className:"text-muted",children:u}),(x==null?void 0:x.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:at(x.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"?`${T.lime}20`:s.status==="failed"?`${T.red}20`:`${T.teal}20`,color:s.status==="running"?T.lime:s.status==="failed"?T.red:T.teal},children:s.status}),x&&(x.provider||x.model||x.modelTier||x.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>l(g=>!g),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${c?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),c&&x&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(x.provider||x.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[x.provider?`${at(x.provider)} · `:"",x.model?Cr(x.model):"—"]}),x.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",at(x.modelTier)]}),x.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 ",x.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(vt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${T.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((g,j)=>{var z;const y=af(g),I=y.color,k=(z=_a(Ai(g.metadata)))==null?void 0:z.model,N=typeof k=="string"?Cr(k):null,h=at(g.title??""),C=g.type==="run_failed",V=g.type==="artifact_created",te=g.type==="decision_requested"||g.type==="decision_resolved";return n.jsxs(ce.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:j*.02},onClick:()=>a==null?void 0:a(g),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-1 focus-visible:ring-offset-[#02040A]",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:`${I}20`,color:I,border:`1px solid ${I}40`},children:n.jsx(of,{icon:y.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${C?"text-red-400":te?"text-amber-300":V?"text-cyan-300":"text-bright"}`,children:h}),g.summary&&g.summary!==h&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:at(g.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:wi(g.timestamp),children:lf(g.timestamp)}),N&&n.jsx("span",{className:"text-micro text-faint",children:N})]})]},g.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",p?` over ${p}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:wi(d[d.length-1].timestamp),children:$t(d[d.length-1].timestamp)})]})]})]})});function uf({completedCount:e,decisionsCount:t,blockerCount:s,visible:r,onDismiss:i}){if(!(e>0||t>0||s>0))return null;const c=[];return e>0&&c.push(`${e} task${e===1?"":"s"} completed`),t>0&&c.push(`${t} need${t===1?"s":""} decisions`),s>0&&c.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(vt,{children:r&&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:`${T.teal}08`,border:`1px solid ${T.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:c.join(" · ")})]}),n.jsx("button",{onClick:i,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 mf={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}},Nr={pr:"#BFFF00",commit:"#BFFF00",test:"#67e8f9",doc:"#0AD4C4",artifact:"#F5B700"};function Ho(e){if(!e)return"#67e8f9";const t=e.toLowerCase();return t.includes("code")||t.includes("pull")||t.includes("commit")||t.includes("pr")?Nr.pr:t.includes("doc")||t.includes("spec")?Nr.doc:t.includes("test")?Nr.test:Nr.artifact}const pf={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 ff({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,statusColor:l,userStateLabel:d,userStateWhy:u,relativeTime:p,timeLabel:x,isRecent:b,enableMotion:g,onOpen:j,ariaLabel:y,artifactSnippet:I,evidenceChips:k,actorCategory:N,queuePosition:h}){const C=(k==null?void 0:k.slice(0,2))??[],V=((k==null?void 0:k.length)??0)-C.length,te="group w-full rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 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-[#BFFF00]/45 cv-auto",z=N==="system",Ie=n.jsxs("div",{className:le("flex items-start gap-3",z&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Xt,{name:N==="user"?"You":a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:le("absolute inset-y-0 left-0 w-[2px] rounded-full",b&&!z&&"pulse-soft"),style:{backgroundColor:c,boxShadow:z?"none":`0 0 14px ${c}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:le("truncate text-caption",z?"text-muted italic":"text-secondary"),title:r,children:z?`OrgX · ${r}`:r}),n.jsx("p",{className:le("mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug",z?"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:x}),n.jsx("span",{className:"text-micro text-muted",children:p})]})]}),I?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5",style:{borderColor:`${Ho(I.typeBadge)}33`,backgroundColor:`${Ho(I.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:[I.typeBadge&&n.jsxs("span",{className:"mr-1.5 text-micro font-semibold uppercase tracking-wider opacity-70",children:["[",I.typeBadge,"]"]}),n.jsx("span",{className:"font-semibold text-bright",children:I.title??I.label}),I.preview&&!I.title&&n.jsx("span",{className:"ml-1.5 opacity-60",children:I.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"})})]}):i?n.jsx("div",{className:"mt-1.5 line-clamp-2 text-caption leading-relaxed text-secondary",children:n.jsx(_r,{mode:"inline",text:i})}):null,C.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[C.map(B=>{const ee=Nr[B.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:ee,backgroundColor:`${ee}14`,border:`1px solid ${ee}30`},children:[B.kind==="pr"&&"PR",B.kind==="commit"&&"Commit",B.kind==="test"&&"Tests",B.kind==="doc"&&"Doc",B.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${ee}CC`},children:B.label})]},`${B.kind}-${B.label}`)}),V>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",V," 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:`${l??c}55`,backgroundColor:`${l??c}1A`,color:l??c},title:u,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:l??c}}),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})}),h&&(()=>{const B=pf[h.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:`${B}55`,backgroundColor:`${B}1A`,color:B},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:B}}),h.state==="running"?"Active":`#${h.rank}`]})})()]})]})]});return g?n.jsx(ce.button,{type:"button",variants:mf,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:j,className:te,"aria-label":y,children:Ie},e):n.jsx("button",{type:"button",onClick:j,className:le(te,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":y,children:Ie},e)}function hf({open:e,onClose:t,children:s}){return n.jsx(Ei,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function gf(e){const t=e.metadata??{},s=e.phase??e.state??t.phase??"",r=e.state??"",i=t.event??t.event_name??"";if(s==="completed"||i==="auto_continue_started"||r==="completed")return"teal";if(s==="blocked"||r==="blocked"||r==="error"||i==="auto_continue_stopped"){const a=t.stop_reason??"";return a==="error"||a==="blocked"?"red":a==="budget_exhausted"||a==="stopped"?"amber":s==="blocked"||r==="error"?"red":"amber"}return e.decisionRequired||r==="needs_input"?"amber":"neutral"}const xf={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 yf({item:e,className:t}){var u,p,x;const s=o.useMemo(()=>Uc(e),[e]),r=gf(e),i=xf[r],a=typeof((u=e.metadata)==null?void 0:u.agent_name)=="string"?e.metadata.agent_name:typeof((p=e.metadata)==null?void 0:p.agentName)=="string"?e.metadata.agentName:e.agentName??"OrgX",c=((x=e.type)==null?void 0:x.replace(/_/g," "))??"activity",d=s.taskDescription||s.outcomeDescription||s.nextStep?null:`${a} recorded a ${c}`;return n.jsxs("div",{className:`rounded-lg border ${i.border} ${i.bg} p-6 space-y-5 ${t??""}`,children:[(s.taskDescription||d)&&n.jsx(aa,{label:"Task",value:s.taskDescription??d,styles:i}),s.outcomeDescription&&n.jsx(aa,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(aa,{label:"Next step",value:s.nextStep,styles:i})]})}function aa({label:e,value:t,styles:s}){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 ${s.label}`,children:e}),n.jsx("p",{className:"text-body leading-relaxed text-primary mt-1",children:t})]})})}const Vo=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),bf=[{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"}],wr=[{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"}],Ko={type:"spring",stiffness:400,damping:25},Go={scale:.985};function cn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function wf(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 vr(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?Yt(Wt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function vf(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function kf(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 _i(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function ar(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 nc(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function jf(e){return e==="agent"?"assistant":e}function Nf(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function If(e,t){return t.map(s=>({id:s.id,role:jf(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function sc(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function or(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function yi(e){const t=or(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=or(t.latestMessage),i=or(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:r?{id:typeof r.id=="string"?r.id:`msg_${s}`,threadId:typeof r.threadId=="string"?r.threadId:s,role:r.role==="agent"||r.role==="system"?r.role:"user",body:typeof r.body=="string"?r.body:"",senderId:typeof r.senderId=="string"?r.senderId:null,senderName:typeof r.senderName=="string"?r.senderName:null,createdAt:typeof r.createdAt=="string"?r.createdAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),attachments:Array.isArray(r.attachments)?r.attachments.filter(a=>!!a&&typeof a=="object"):[],metadata:r.metadata&&typeof r.metadata=="object"?r.metadata:{}}:null,latestLaunch:i?{id:typeof i.id=="string"?i.id:`launch_${s}`,threadId:typeof i.threadId=="string"?i.threadId:s,messageId:typeof i.messageId=="string"?i.messageId:typeof t.lastMessageAt=="string"?`msg_${t.lastMessageAt}`:`msg_${s}`,assigneeId:typeof i.assigneeId=="string"?i.assigneeId:null,assigneeName:typeof i.assigneeName=="string"?i.assigneeName:null,watcherIds:Array.isArray(i.watcherIds)?i.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(i.watcherNames)?i.watcherNames.filter(a=>typeof a=="string"):[],executionMode:i.executionMode==="cloud"||i.executionMode==="hybrid"?i.executionMode:"local_queue",provider:typeof i.provider=="string"?i.provider:null,runId:typeof i.runId=="string"?i.runId:null,status:i.status==="queued"||i.status==="running"||i.status==="blocked"||i.status==="completed"||i.status==="failed"||i.status==="requested"?i.status:"requested",blockedReason:typeof i.blockedReason=="string"?i.blockedReason:null,warnings:Array.isArray(i.warnings)?i.warnings.filter(a=>typeof a=="string"):[],requestedAt:typeof i.requestedAt=="string"?i.requestedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),updatedAt:typeof i.updatedAt=="string"?i.updatedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),metadata:i.metadata&&typeof i.metadata=="object"?i.metadata:{}}:null}}function Af(e){const t=or(e);if(!t)return null;const s=yi({...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 r=Array.isArray(t.messages)?t.messages.map(a=>or(a)).filter(a=>!!a).map(a=>{const c=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:c,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(l=>!!l&&typeof l=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],i=Array.isArray(t.launches)?t.launches.map(a=>or(a)).filter(a=>!!a).map(a=>{const c=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",l=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:c,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:l,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:r.sort((a,c)=>cn(a.createdAt)-cn(c.createdAt)),launches:i.sort((a,c)=>cn(c.requestedAt)-cn(a.requestedAt))}}function _f(e,t,s){const r=cn(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=cn(s.startIso),c=cn(s.endIso);return!(a&&r<a||c&&r>c)}const i=Lr(t,Date.now());return i?r>=i:!0}async function kr(e,t){try{const s=await fetch(e,t),r=await s.json().catch(()=>null);return s.ok?{ok:!0,status:s.status,data:r,error:null}:{ok:!1,status:s.status,data:null,error:(r&&typeof r.error=="string"?r.error:null)??`Request failed (${s.status})`}}catch(s){return{ok:!1,status:0,data:null,error:s instanceof Error?s.message:"Network error"}}}function oa(e,t){const s=new Map;for(const r of e)s.set(r.id,r);return s.set(t.id,t),Array.from(s.values()).sort((r,i)=>cn(i.lastActivityAt??i.updatedAt)-cn(r.lastActivityAt??r.updatedAt))}function Sf(e,t){const s=new Map;for(const r of e)s.set(r.id,r);for(const r of t)s.set(r.id,r);return Array.from(s.values()).sort((r,i)=>cn(i.lastActivityAt??i.updatedAt)-cn(r.lastActivityAt??r.updatedAt))}const rc=o.createContext(null),ic=o.createContext(null);function qa(){const e=o.useContext(rc);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function za(){const e=o.useContext(ic);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function Cf({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:c,timeFilterId:l,customTimeRange:d,snapshot:u,onRequestRefresh:p}){const[x,b]=o.useState((u==null?void 0:u.threads)??[]),[g,j]=o.useState(null),[y,I]=o.useState(null),[k,N]=o.useState(!1),[h,C]=o.useState(null),[V,te]=o.useState("resting"),[z,Ie]=o.useState(""),[B,ee]=o.useState(!1),[be,ve]=o.useState(!1),[Ae,ue]=o.useState(null),[Ke,pe]=o.useState(null),[ae,ne]=o.useState([]),[ie,xe]=o.useState(""),[K,R]=o.useState([]),[U,P]=o.useState(""),[H,Q]=o.useState(null),[ge,ke]=o.useState(""),[se,ye]=o.useState(!1),[he,L]=o.useState(""),[q,G]=o.useState([]),[re,Re]=o.useState(!1),[Ge,Ee]=o.useState("auto"),[$,rt]=o.useState(!1),[Le,Xe]=o.useState(!1),[kt,jt]=o.useState(!1),Nt=o.useRef(null),O=o.useRef(null),_e=o.useRef(null),fe=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b(D=>Sf(D,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{g&&b(D=>D.sort((de,me)=>cn(me.lastActivityAt)-cn(de.lastActivityAt)))},[g]);const{data:Te}=Oa({enabled:!0,refetchInterval:8e3}),Qe=o.useMemo(()=>{var de,me;const D=new Map;for(const Ce of bf)D.set(Ce.id,{id:Ce.id,name:Ce.name,handle:Ce.handle,domain:Ce.domain,domainLabel:Ce.domainLabel,role:Ce.role,status:"idle",currentTask:null,isSystem:!1});if(Te!=null&&Te.agents)for(const Ce of Te.agents){const xt=D.get(Ce.id);xt?(xt.status=Ce.status==="running"?"running":(de=Ce.blockers)!=null&&de.length?"blocked":"idle",xt.currentTask=Ce.currentTask??null):D.set(Ce.id,{id:Ce.id,name:Ce.name,handle:Ce.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Ce.status==="running"?"running":(me=Ce.blockers)!=null&&me.length?"blocked":"idle",currentTask:Ce.currentTask??null,isSystem:Vo.has(Ce.id)})}for(const Ce of t){const xt=(Ce.agentId??"").trim(),Bt=(Ce.agentName??"").trim();!xt||!Bt||D.has(xt)||D.set(xt,{id:xt,name:Bt,handle:xt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:Vo.has(xt)})}return Array.from(D.values()).filter(Ce=>!Ce.isSystem).sort((Ce,xt)=>Ce.name.localeCompare(xt.name))},[Te,t]),tt=o.useMemo(()=>s.map(D=>({id:D.id,name:D.name})).sort((D,de)=>D.name.localeCompare(de.name)),[s]),Y=o.useMemo(()=>Qe.find(D=>D.id===ie)??null,[Qe,ie]),We=o.useMemo(()=>{const D=new Set(K);return Qe.filter(de=>D.has(de.id))},[Qe,K]),we=o.useMemo(()=>tt.find(D=>D.id===U)??null,[tt,U]);o.useEffect(()=>{ie&&R(D=>D.filter(de=>de!==ie))},[ie]);const X=o.useMemo(()=>Qe.slice(0,8),[Qe]),$e=o.useMemo(()=>{const D=ge.trim().toLowerCase();return D?Qe.filter(de=>de.name.toLowerCase().includes(D)||de.handle.toLowerCase().includes(D)||de.domain.toLowerCase().includes(D)||de.role.toLowerCase().includes(D)):Qe},[Qe,ge]),He=o.useMemo(()=>{const D=he.trim().toLowerCase();return D?tt.filter(de=>de.name.toLowerCase().includes(D)):tt},[tt,he]),De=o.useMemo(()=>{const D=i.trim().toLowerCase(),de=x.filter(me=>!kf(me,a)||!_f(me,l,d)?!1:D.length===0?!0:vf(me).includes(D));return de.sort((me,Ce)=>{const xt=cn(Ce.lastActivityAt)-cn(me.lastActivityAt);return c==="newest"?xt:-xt}),de},[d,i,c,a,x,l]),st=o.useMemo(()=>{if(!g||De.some(de=>de.id===g))return De;const D=x.find(de=>de.id===g);return D?[D,...De]:De},[g,De,x]),dt=o.useMemo(()=>x.find(D=>D.id===g)??null,[g,x]),Ct=o.useMemo(()=>ae.filter(D=>D.status!=="ready").length,[ae]),W=z.trim().length>0&&!B,Ne=o.useMemo(()=>Ct>0?`${Ct} attachment(s) still processing.`:"Press Enter to send.",[Ct]),Ue=o.useMemo(()=>B?"Sending…":be?"Launching…":"Send",[be,B]),Ve=o.useMemo(()=>new Lc({api:"/orgx/api/chat/usechat"}),[]),{messages:ze,setMessages:qe,sendMessage:Oe,status:ut,error:Ft,clearError:pt}=$c({id:`orgx-chat-guidance-${r??"global"}`,transport:Ve,onError:D=>{ue(vr((D==null?void 0:D.message)??null,"send"))}});o.useEffect(()=>{if(!y){qe([]);return}qe(If(y.id,y.messages))},[y,qe]);const bt=o.useMemo(()=>{const D=[...ze].reverse().find(me=>me.role==="assistant");if(!D)return null;const de=Nf(D);return de.length>0?de:null},[ze]),At=o.useRef(null);o.useEffect(()=>{if(ut!=="ready"&&ut!=="error"||!bt)return;const D=[...ze].reverse().find(de=>de.role==="assistant");!D||D.id===At.current||(At.current=D.id,G(de=>[...de,{id:`guidance_${D.id}`,role:"agent",body:bt,timestamp:new Date().toISOString()}]))},[ut,bt,ze]);const nt=o.useCallback(()=>{Ie(""),ne([]),Xe(!1),jt(!1),ue(null),pe(null)},[]),Pt=o.useCallback(D=>{G(de=>[...de,{...D,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Je=o.useCallback(()=>G([]),[]),qt=o.useCallback(()=>Re(D=>!D),[]),Mt=o.useMemo(()=>wr.find(D=>D.id===Ge)??wr[0],[Ge]),_t=o.useCallback(()=>{Ee(D=>{const de=wr.findIndex(me=>me.id===D);return wr[(de+1)%wr.length].id})},[]),Ut=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),It=o.useCallback(async D=>{var Ce;N(!0),C(null);const de=await kr(`/orgx/api/chat/threads/${encodeURIComponent(D)}`);if(!de.ok||!((Ce=de.data)!=null&&Ce.thread))return N(!1),C(vr(de.error,"load")),null;const me=Af(de.data.thread);return me?(I(me),N(!1),me):(N(!1),C("Thread detail payload was invalid."),null)},[]),on=o.useCallback(async(D,de)=>{de&&(_e.current=de),j(D),await It(D),requestAnimationFrame(()=>{var me;return(me=O.current)==null?void 0:me.focus()})},[It]),as=o.useCallback(()=>{var D;j(null),I(null),C(null),N(!1),(D=_e.current)==null||D.focus()},[]),os=o.useCallback(D=>{window.setTimeout(()=>{ne(de=>de.map(me=>me.id===D?{...me,status:"indexing",updatedAt:new Date().toISOString()}:me))},80),window.setTimeout(()=>{ne(de=>de.map(me=>{var Bt;if(me.id!==D)return me;const Ce=((Bt=me.mimeType)==null?void 0:Bt.toLowerCase())==="application/x-msdownload"||me.name.toLowerCase().endsWith(".exe"),xt=(me.sizeBytes??0)>25*1024*1024;return Ce?{...me,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:xt?{...me,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...me,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Is=o.useCallback(D=>{if(!D||D.length===0)return;const de=new Date().toISOString(),me=Array.from(D).map(Ce=>({id:`draft_att_${crypto.randomUUID()}`,name:Ce.name,mimeType:Ce.type||null,sizeBytes:Number.isFinite(Ce.size)?Ce.size:null,status:"preparing",error:null,masked:!1,createdAt:de,updatedAt:de}));ne(Ce=>Ce.concat(me)),me.forEach(Ce=>os(Ce.id)),ys("chat_attachment_state_changed",{count:me.length,state:"preparing"})},[os]),$n=o.useCallback(D=>{ne(de=>de.map(me=>me.id===D?{...me,status:"preparing",error:null,updatedAt:new Date().toISOString()}:me)),os(D),ys("chat_attachment_state_changed",{state:"retry"})},[os]),Ht=o.useCallback(D=>{xe(de=>de===D?"":D),R(de=>de.filter(me=>me!==D)),Q(null),ke("")},[]),Nn=o.useCallback(D=>{R(de=>de.includes(D)?de.filter(me=>me!==D):de.concat(D))},[]),As=o.useCallback(()=>{ye(!1),L(""),Q(D=>D==="assignee"?null:"assignee"),ke("")},[]),sn=o.useCallback(()=>{ye(!1),L(""),Q(D=>D==="watcher"?null:"watcher"),ke("")},[]),ls=o.useCallback(()=>{Q(null),ke(""),ye(D=>!D),L("")},[]),Tn=o.useCallback(async(D,de)=>{var Bt;rt(!0);const me=tt.find(ft=>ft.id===de)??null,Ce=await kr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:D,project_id:r??void 0,initiativeId:(me==null?void 0:me.id)??null,initiativeTitle:(me==null?void 0:me.name)??null,relinked:!0})});if(rt(!1),!Ce.ok||!((Bt=Ce.data)!=null&&Bt.thread)){C(Ce.error??"Scope link failed.");return}const xt=yi(Ce.data.thread);xt&&b(ft=>oa(ft,xt)),await It(D),await Ut(),ys("chat_thread_linked_initiative",{threadId:D,initiativeId:(me==null?void 0:me.id)??null})},[tt,It,Ut,r]),Kn=o.useCallback(async D=>{pt(),await Oe({text:D.prompt},{body:{threadId:D.thread.id,project_id:r??void 0,initiativeId:D.thread.initiativeId??(we==null?void 0:we.id)??void 0,initiativeTitle:D.thread.initiativeTitle??(we==null?void 0:we.name)??void 0,assigneeId:(Y==null?void 0:Y.id)??D.thread.assigneeId??void 0,assigneeName:(Y==null?void 0:Y.name)??D.thread.assigneeName??void 0,watcherIds:We.map(de=>de.id),watcherNames:We.map(de=>de.name)}}),await Ut(),await It(D.thread.id)},[pt,It,Ut,Y==null?void 0:Y.id,Y==null?void 0:Y.name,we==null?void 0:we.id,we==null?void 0:we.name,We,Oe,r]),Dn=o.useCallback(async()=>{var xt,Bt;const D=z.trim();if(!D)return ue("Write a message before sending."),{thread:null,messageId:null};ue(null),pe(null),ee(!0);const de=await kr("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:g??void 0,project_id:r??void 0,initiativeId:(we==null?void 0:we.id)??(y==null?void 0:y.initiativeId)??void 0,initiativeTitle:(we==null?void 0:we.name)??(y==null?void 0:y.initiativeTitle)??void 0,assigneeId:(Y==null?void 0:Y.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(Y==null?void 0:Y.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:We.map(ft=>ft.id),watcherNames:We.map(ft=>ft.name),body:D,attachments:ae.map(ft=>({id:ft.id,name:ft.name,mimeType:ft.mimeType,sizeBytes:ft.sizeBytes,status:ft.status,error:ft.error,masked:ft.masked}))})});if(ee(!1),!de.ok||!((xt=de.data)!=null&&xt.thread))return ue(vr(de.error,"send")),ys("chat_message_send_failed",{reason:de.error??"unknown"}),{thread:null,messageId:null};const me=yi(de.data.thread);if(!me)return ue("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(ft=>oa(ft,me)),Pt({role:"user",body:D}),Ge!=="auto"&&Y&&Pt({role:"system",body:`Routing to ${Y.name} via ${Mt.label}`}),ys("chat_message_sent",{threadId:me.id,watcherCount:me.watcherIds.length}),await Ut();const Ce=de.data.message&&typeof de.data.message.id=="string"?de.data.message.id:((Bt=me.latestMessage)==null?void 0:Bt.id)??null;return j(me.id),await It(me.id),Kn({thread:me,prompt:D}).catch(ft=>{Pt({role:"error",body:vr(ft instanceof Error?ft.message:String(ft??""),"send")})}),nt(),te("reviewing"),{thread:me,messageId:Ce}},[y==null?void 0:y.assigneeId,y==null?void 0:y.assigneeName,y==null?void 0:y.initiativeId,y==null?void 0:y.initiativeTitle,g,z,ae,It,Ut,nt,Kn,Y==null?void 0:Y.id,Y==null?void 0:Y.name,we==null?void 0:we.id,we==null?void 0:we.name,Ge,Mt,We,r]),Gn=o.useCallback(async(D,de)=>{var St,Tt,In,Et,An,_n,_s;if(!de){Pt({role:"error",body:"Send a message first to launch."});return}if(!Y){Pt({role:"error",body:"Pick an agent with @ before launching."});return}if(Ct>0&&!kt){Xe(!0),Pt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ve(!0),ue(null),pe(null);const me=await kr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:Y.id,message:z.trim().length>0?z.trim():D.lastSnippet??D.title,initiativeId:D.initiativeId??(we==null?void 0:we.id)??void 0,initiativeTitle:D.initiativeTitle??(we==null?void 0:we.name)??void 0,workstreamId:D.workstreamId??void 0,taskId:D.taskId??void 0,provider:Ge!=="auto"?Ge:void 0})}),Ce=((St=me.data)==null?void 0:St.sessionId)??((Tt=me.data)==null?void 0:Tt.runId)??null,xt=me.ok&&Ce?"running":me.ok?"queued":"blocked",Bt=me.ok?null:me.error??"Launch request failed before queueing.",ft=await kr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:D.id,messageId:de,assigneeId:Y.id,assigneeName:Y.name,watcherIds:We.map(hn=>hn.id),watcherNames:We.map(hn=>hn.name),executionMode:"local_queue",provider:((In=me.data)==null?void 0:In.provider)??(Ge!=="auto"?Ge:"openclaw"),runId:Ce??void 0,status:xt,blockedReason:Bt??void 0,warnings:Ct>0?[`${Ct} attachment(s) were not ready at launch.`]:[]})});if(ve(!1),jt(!1),Xe(!1),!ft.ok||!((Et=ft.data)!=null&&Et.thread)){ue(ft.error?vr(ft.error,"launch"):Bt??"Launch state could not be persisted. Message remained saved."),ys("chat_launch_failed",{threadId:D.id,reason:ft.error??Bt??"unknown"});return}const zt=yi(ft.data.thread);if(zt&&b(hn=>oa(hn,zt)),await It(D.id),await Ut(),!me.ok){ue(`Launch blocked: ${Bt??"Set assignee and retry."}`),ys("chat_launch_blocked",{threadId:D.id,reason:Bt??"unknown"});return}const rn=((An=me.data)==null?void 0:An.provider)==="anthropic"?"Claude Code":((_n=me.data)==null?void 0:_n.provider)==="openai"?"Codex":Mt.shortLabel,Pn=(_s=me.data)!=null&&_s.model?` (${me.data.model})`:"";pe(Ce?`Launch started via ${rn}${Pn}. Thread timeline now tracks execution state.`:`Launch queued locally via ${rn}. Run starts when a worker is available.`),ys(Ce?"chat_launch_started":"chat_launch_queued",{threadId:D.id,runId:Ce,assigneeId:Y.id})},[z,kt,It,Ut,Y,we==null?void 0:we.id,we==null?void 0:we.name,Ge,Mt,We,Ct]),cs=o.useCallback(async()=>{var de;const D=await Dn();(de=D.thread)!=null&&de.id&&await on(D.thread.id)},[on,Dn]),Jt=o.useCallback(async()=>{const D=await Dn();D.thread&&(await Gn(D.thread,D.messageId),await on(D.thread.id))},[Gn,on,Dn]),ds=o.useCallback(async()=>{if(W){if(Y){await Jt();return}await cs()}},[W,Jt,cs,Y]),fn=o.useMemo(()=>({threads:x,activeThreadId:g,activeThread:y,activeThreadSummary:dt,displayedThreads:st,composerMode:V,draft:z,draftAttachments:ae,sending:B,launching:be,composerError:Ae,composerNotice:Ke,selectedAssigneeId:ie,selectedAssignee:Y,selectedWatcherIds:K,selectedWatchers:We,selectedInitiativeId:U,selectedInitiative:we,agentOptions:Qe,quickAssigneeOptions:X,initiativeOptions:tt,agentPickerMode:H,agentPickerQuery:ge,filteredAgentOptions:$e,scopePickerOpen:se,scopePickerQuery:he,filteredInitiativeOptions:He,panelLoading:k,panelError:h,scopeSaving:$,launchWarningOpen:Le,launchWarningAccepted:kt,unresolvedAttachmentCount:Ct,canSend:W,composerGuidance:Ne,primaryActionLabel:Ue,guidanceStatus:ut,guidancePreview:bt,guidanceError:Ft??null,inlineMessages:q,threadSidebarOpen:re,workspaceId:r,selectedProvider:Ge,selectedProviderDef:Mt}),[x,g,y,dt,st,V,z,ae,B,be,Ae,Ke,ie,Y,K,We,U,we,Qe,X,tt,H,ge,$e,se,he,He,k,h,$,Le,kt,Ct,W,Ne,Ue,ut,bt,Ft,q,re,r,Ge,Mt]),Fn=o.useMemo(()=>({setDraft:Ie,setComposerMode:te,setDraftAttachments:ne,selectAssignee:Ht,toggleWatcher:Nn,setSelectedInitiativeId:P,toggleAssigneePicker:As,toggleWatcherPicker:sn,toggleScopePicker:ls,setAgentPickerQuery:ke,setScopePickerQuery:L,setAgentPickerMode:Q,setScopePickerOpen:ye,handlePrimaryAction:ds,handleFilesAdded:Is,handleRetryAttachment:$n,openThreadPanel:on,closeThreadPanel:as,loadThreadDetail:It,applyScopeLink:Tn,resetComposer:nt,setComposerError:ue,setComposerNotice:pe,setLaunchWarningAccepted:jt,pushInlineMessage:Pt,clearInlineMessages:Je,toggleThreadSidebar:qt,setSelectedProvider:Ee,cycleProvider:_t,fileInputRef:Nt,panelHeadingRef:O,composerShellRef:fe}),[Ht,Nn,As,sn,ls,ds,Is,$n,on,as,It,Tn,nt,Pt,Je,qt,_t]);return n.jsx(rc.Provider,{value:fn,children:n.jsx(ic.Provider,{value:Fn,children:e})})}const Mf={type:"spring",stiffness:500,damping:35,mass:.5};function Tf({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=is(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(l=e[e.length-1])==null?void 0:l.body]);const c=s?e.slice(-2):e;return c.length===0?null:n.jsx(ce.div,{initial:i?!1:{opacity:0,height:0},animate:i?{}:{opacity:1,height:"auto"},exit:i?{}:{opacity:0,height:0},transition:i?void 0:{duration:.25,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{ref:a,onClick:r,role:r?"button":void 0,tabIndex:r?0:void 0,className:le("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(vt,{initial:!1,children:c.map(d=>n.jsx(ce.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:Mf,className:le("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:le("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:le("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:$t(d.timestamp)})]}),n.jsxs("p",{className:le("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===c[c.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 Xo({open:e,onClose:t}){const s=is(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:p}=qa(),{openThreadPanel:x,closeThreadPanel:b,loadThreadDetail:g,applyScopeLink:j,panelHeadingRef:y}=za(),I=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,k=o.useCallback((h,C)=>{x(h,C)},[x]),N=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(vt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:N,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:Qt.durationEntrance/1e3,ease:Qt.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:r.length})]}),n.jsx("button",{type:"button",onClick:N,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:le("grid min-h-0 flex-1 overflow-hidden",i&&"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:r.length===0?n.jsx(Ri,{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:r.map(h=>n.jsxs("button",{type:"button",onClick:C=>k(h.id,C.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===h.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:h.lastSnippet?`"${h.lastSnippet.length>40?h.lastSnippet.slice(0,40)+"...":h.lastSnippet}"`:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:$t(h.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",h.assigneeName]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",ar(h.status)),children:_i(h.status)})]})]},h.id))})}),n.jsx(vt,{initial:!1,children:i&&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:Qt.durationStandard/1e3,ease:Qt.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:y,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(c==null?void 0:c.title)??"Thread"}),n.jsx("span",{className:le("rounded-full border px-2 py-0.5 text-micro font-semibold",ar((c==null?void 0:c.status)??"message_only")),children:_i((c==null?void 0:c.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:l?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}),I&&n.jsx("button",{type:"button",onClick:()=>void g(I),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(h=>n.jsx("article",{className:le("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.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:h.senderName??nc(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:$t(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.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(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",ar(sc(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:$t(h.requestedAt)})]},h.id))]})]})})]})]})]})})}function Qo(){const e=is(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=qa(),{openThreadPanel:p,closeThreadPanel:x,loadThreadDetail:b,applyScopeLink:g,setComposerMode:j,toggleThreadSidebar:y,panelHeadingRef:I}=za(),k=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,N=o.useCallback(()=>{y()},[y]);return u?n.jsx(vt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:N,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:Qt.durationEntrance/1e3,ease:Qt.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:N,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:Go,transition:Ko,onClick:()=>{N(),j("focused"),requestAnimationFrame(()=>{const h=document.getElementById("chat-dock-input");h instanceof HTMLTextAreaElement&&h.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((h,C)=>n.jsxs(ce.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:Ko,delay:e?0:Math.min(C*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Go,onClick:V=>void p(h.id,V.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===h.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:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:$t(h.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:h.lastSnippet??h.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Xt,{name:h.assigneeName,hint:h.assigneeName,size:"xs"}),n.jsx("span",{children:h.assigneeName})]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",ar(h.status)),children:_i(h.status)})]})]},h.id))})}),n.jsx(vt,{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:Qt.durationStandard/1e3,ease:Qt.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:I,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(r==null?void 0:r.title)??(i==null?void 0:i.title)??"Thread"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:le("rounded-full border px-2 py-0.5 text-micro font-semibold",ar((i==null?void 0:i.status)??"message_only")),children:_i((i==null?void 0:i.status)??"message_only")}),n.jsx("button",{type:"button",onClick:x,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]"})]}):c?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:c}),k&&n.jsx("button",{type:"button",onClick:()=>void b(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"})]}):r&&r.messages.length>0?n.jsx("div",{className:"space-y-2",children:r.messages.map(h=>n.jsx("article",{className:le("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.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:h.senderName??nc(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:$t(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),r&&r.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:[r.launches.length," launch",r.launches.length===1?"":"es"]}),r.launches.slice(0,2).map(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",ar(sc(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:$t(h.requestedAt)})]},h.id))]})]})})]},"sidebar-panel")]})}):null}const Ef={type:"spring",stiffness:500,damping:30,mass:.5};function Rf({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=is(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>{const p=s.toLowerCase();return u.name.toLowerCase().includes(p)||u.handle.toLowerCase().includes(p)||u.domain.toLowerCase().includes(p)||u.role.toLowerCase().includes(p)}):t;if(!e||l.length===0)return null;const d=l.slice(0,6);return n.jsx(vt,{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:Ef,className:le("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:c,className:"space-y-px",children:d.map((u,p)=>{const x=p===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:le("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Xt,{name:u.name,hint:u.name,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-caption font-medium",children:u.name}),u.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime","aria-label":"Running"})]}),n.jsx("span",{className:"text-micro text-muted",children:u.domainLabel})]})]},u.id)})})})})}const Lf={type:"spring",stiffness:500,damping:30,mass:.5};function $f({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=is(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=l.slice(0,6);return n.jsx(vt,{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:Lf,className:le("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:c,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":r===0,"data-active":r===0,onClick:()=>i(null),onMouseDown:u=>u.preventDefault(),className:le("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",r===0?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:"Unscoped"}),d.map((u,p)=>{const x=p+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:le("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function Df({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:c,onQueryChange:l,onSelectAssignee:d,onToggleWatcher:u,onClose:p,onSwitchMode:x,anchorRef:b}){const g=is();return n.jsx(vt,{children:e&&n.jsxs(ce.div,{initial:g?!1:{opacity:0,scale:.95,y:8},animate:g?{}:{opacity:1,scale:1,y:0},exit:g?{}:{opacity:0,scale:.95,y:8},transition:g?void 0:Qt.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:()=>x("assignee"),className:le("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:()=>x("watcher"),className:le("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"})]}),r.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:r.map(j=>{const y=a===j.id;return n.jsx("button",{type:"button",onClick:()=>d(j.id),title:j.name,className:le("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",y?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":y,"aria-label":`Select ${j.name} as assignee`,children:n.jsx(Xt,{name:j.name,hint:j.name,size:"xs"})},j.id)})}),n.jsx("input",{value:i,onChange:j=>l(j.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(j=>{const y=a===j.id,I=c.includes(j.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(j.id);return}y||u(j.id)},className:le("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",y?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":I?"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(Xt,{name:j.name,hint:j.name,size:"xs"}),n.jsx("span",{children:j.name})]}),n.jsx("span",{className:"text-micro",children:y?"Assignee":I?"Watcher":"Select"})]},j.id)})})]})})}const Jo=24,Yo=200;function Zo(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 Ff(e,t){var r;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=(r=t.split(".").pop())==null?void 0:r.toUpperCase();return s&&s.length<=5?s:"File"}function el({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 Sa="orgx-chat-dock-collapsed";function Pf(){try{return localStorage.getItem(Sa)==="1"}catch{return!1}}function Of(){const e=qa(),t=za(),s=is(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState(Pf),l=o.useCallback(()=>{c(X=>{const $e=!X;try{localStorage.setItem(Sa,$e?"1":"0")}catch{}return $e})},[]),[d,u]=o.useState(!1),[p,x]=o.useState(!1),b=o.useRef(null),[g,j]=o.useState(!1),[y,I]=o.useState(""),[k,N]=o.useState(0),[h,C]=o.useState(-1),[V,te]=o.useState(!1),[z,Ie]=o.useState(""),[B,ee]=o.useState(0),[be,ve]=o.useState(-1),{composerMode:Ae,draft:ue,draftAttachments:Ke,sending:pe,launching:ae,selectedAssigneeId:ne,selectedAssignee:ie,selectedWatcherIds:xe,selectedInitiative:K,agentOptions:R,quickAssigneeOptions:U,agentPickerMode:P,agentPickerQuery:H,filteredAgentOptions:Q,initiativeOptions:ge,canSend:ke,activeThreadId:se,guidanceStatus:ye,inlineMessages:he,displayedThreads:L,launchWarningOpen:q,launchWarningAccepted:G,selectedProvider:re,selectedProviderDef:Re}=e,Ge=ue.trim(),Ee=he.length>0;Ge.length>0;const $=o.useCallback(()=>{const X=r.current;if(!X)return;X.style.height="0";const $e=Math.min(Math.max(X.scrollHeight,Jo),Yo);X.style.height=`${$e}px`},[]);o.useLayoutEffect(()=>{$()},[ue,$]);const rt=o.useMemo(()=>{if(!g)return R;const X=y.toLowerCase();return X?R.filter($e=>$e.name.toLowerCase().includes(X)||$e.handle.toLowerCase().includes(X)||$e.domain.toLowerCase().includes(X)||$e.role.toLowerCase().includes(X)):R},[R,g,y]),Le=o.useMemo(()=>{if(!V)return ge;const X=z.toLowerCase();return X?ge.filter($e=>$e.name.toLowerCase().includes(X)):ge},[ge,V,z]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),he.length<=2){x(!1);return}return x(!1),b.current=window.setTimeout(()=>{x(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[he.length]),o.useEffect(()=>{const X=$e=>{if(($e.metaKey||$e.ctrlKey)&&$e.key==="k"){if($e.preventDefault(),a){c(!1);try{localStorage.setItem(Sa,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var He;return(He=r.current)==null?void 0:He.focus()})}};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,a]);const Xe=o.useCallback(()=>{Ae==="resting"&&t.setComposerMode("focused")},[Ae,t]),kt=o.useCallback(()=>{window.setTimeout(()=>{Ge.length===0&&!Ee&&!g&&!V&&Ke.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),j(!1),te(!1))},100)},[Ge,Ee,g,V,Ke.length,t]),jt=o.useCallback(X=>{const $e=X.target.value,He=X.target.selectionStart??$e.length;t.setDraft($e),(Ae==="resting"||Ae==="focused")&&t.setComposerMode("composing");const De=$e.slice(0,He),st=De.match(/@(\w*)$/);if(st){j(!0),I(st[1]),N(0),C(He-st[0].length),te(!1);return}const dt=De.match(/#(\w*)$/);if(dt){te(!0),Ie(dt[1]),ee(0),ve(He-dt[0].length),j(!1);return}g&&j(!1),V&&te(!1)},[Ae,t,g,V]),Nt=o.useCallback(X=>{var st;const $e=ue.slice(0,h),He=ue.slice(((st=r.current)==null?void 0:st.selectionStart)??ue.length),De=`${$e}@${X.name} ${He}`;t.setDraft(De),t.selectAssignee(X.id),j(!1),I(""),requestAnimationFrame(()=>{if(r.current){const dt=$e.length+X.name.length+2;r.current.setSelectionRange(dt,dt),r.current.focus()}})},[ue,h,t]),O=o.useCallback(X=>{var De;const $e=ue.slice(0,be),He=ue.slice(((De=r.current)==null?void 0:De.selectionStart)??ue.length);if(X){const st=`${$e}#${X.name} ${He}`;t.setDraft(st),t.setSelectedInitiativeId(X.id),requestAnimationFrame(()=>{if(r.current){const dt=$e.length+X.name.length+2;r.current.setSelectionRange(dt,dt),r.current.focus()}})}else{const st=`${$e}${He}`;t.setDraft(st),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange($e.length,$e.length),r.current.focus())})}te(!1),Ie("")},[ue,be,t]),_e=o.useCallback(X=>{if(g&&rt.length>0){if(X.key==="ArrowDown"){X.preventDefault(),N($e=>($e+1)%rt.length);return}if(X.key==="ArrowUp"){X.preventDefault(),N($e=>($e-1+rt.length)%rt.length);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),Nt(rt[k]);return}if(X.key==="Escape"){X.preventDefault(),j(!1);return}}if(V){const $e=Le.length+1;if(X.key==="ArrowDown"){X.preventDefault(),ee(He=>(He+1)%$e);return}if(X.key==="ArrowUp"){X.preventDefault(),ee(He=>(He-1+$e)%$e);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),O(B===0?null:Le[B-1]);return}if(X.key==="Escape"){X.preventDefault(),te(!1);return}}if(X.key==="Enter"&&!X.shiftKey){X.preventDefault(),t.handlePrimaryAction();return}X.key==="Escape"&&(X.preventDefault(),P?t.setAgentPickerMode(null):Ee?t.clearInlineMessages():(t.setComposerMode("resting"),X.target.blur()))},[t,P,Ee,g,rt,k,Nt,V,Le,B,O]),fe=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),Te=pe||ae?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"})]}),Qe=(Ae==="reviewing"||Ee)&&he.length>0,tt=ye==="submitted"||ye==="streaming",Y=o.useRef(he.length),[We,we]=o.useState(0);return o.useEffect(()=>{if(!a){Y.current=he.length,we(0);return}const X=he.length-Y.current;X>0&&we(X)},[a,he.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(Xo,{open:d,onClose:()=>u(!1)}),n.jsx(Qo,{}),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:()=>{l(),requestAnimationFrame(()=>{var X;return(X=r.current)==null?void 0:X.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:le("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(vt,{children:We>0&&n.jsx(ce.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:le("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:We>9?"9+":We},"unread")}),se&&We===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(Xo,{open:d,onClose:()=>u(!1)}),n.jsx(Qo,{}),n.jsxs("div",{ref:X=>{t.composerShellRef.current=X},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(vt,{children:q&&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:G,onChange:X=>t.setLaunchWarningAccepted(X.target.checked)}),n.jsx("span",{children:"I understand unresolved attachment extraction may reduce context quality."})]})]},"launch-warning")}),n.jsx("div",{className:"relative",children:n.jsx(Df,{open:P!==null,mode:P??"assignee",agents:Q,quickAgents:U,query:H,selectedAssigneeId:ne,selectedWatcherIds:xe,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(ce.section,{"data-testid":"chat-dock","data-state":Ae,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Qt.durationEntrance/1e3,ease:Qt.easingEntrance},className:le("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",Ae!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:l,className:le("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:X=>{t.fileInputRef.current=X},type:"file",multiple:!0,className:"hidden",onChange:X=>{t.handleFilesAdded(X.target.files),X.currentTarget.value=""}}),n.jsx(vt,{children:Qe&&n.jsx(Tf,{messages:he,isStreaming:tt,collapsed:p,onClick:fe})}),n.jsxs("div",{className:"relative",children:[n.jsx(Rf,{open:g,agents:rt,query:y,activeIndex:k,anchorRect:null,onSelect:Nt,onClose:()=>j(!1)}),n.jsx($f,{open:V,initiatives:Le,query:z,activeIndex:B,onSelect:O,onClose:()=>te(!1)})]}),n.jsx(vt,{initial:!1,children:Ke.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:Ke.map(X=>n.jsxs("div",{className:le("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",X.status==="failed"?"border-rose-400/30 bg-rose-400/[0.08]":"border-white/[0.1] bg-white/[0.04]"),children:[n.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${Zo(X.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Zo(X.mimeType),strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"max-w-[180px] truncate text-caption font-medium text-primary",children:X.name}),n.jsxs("p",{className:"text-micro text-muted",children:[Ff(X.mimeType,X.name),X.sizeBytes?` · ${wf(X.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments($e=>$e.filter(He=>He.id!==X.id)),className:le("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${X.name}`,children:"×"}),X.status!=="ready"&&X.status!=="failed"&&n.jsx("div",{className:"absolute bottom-0.5 left-3 right-3 h-0.5 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("div",{className:"h-full w-1/2 animate-pulse rounded-full bg-white/[0.2]"})}),X.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(X.id),className:"ml-1 rounded-md border border-rose-300/20 bg-rose-400/[0.12] px-1.5 py-0.5 text-micro text-rose-200 hover:bg-rose-400/[0.2]",children:"Retry"})]},X.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var X;return(X=t.fileInputRef.current)==null?void 0:X.click()},className:le("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:le("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",re==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":re==="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: ${Re.label}. Click to switch.`,"aria-label":`Current provider: ${Re.label}. Click to cycle.`,children:[n.jsx(el,{icon:Re.icon}),n.jsx("span",{children:Re.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:r,id:"chat-dock-input",value:ue,onFocus:Xe,onBlur:kt,onChange:jt,onKeyDown:_e,placeholder:"Ask anything",rows:1,className:le("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:Jo,maxHeight:Yo,overflowY:"auto"},"aria-expanded":Ae!=="resting"})]}),L.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:le("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":`${L.length} thread${L.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"})}),L.length]}),n.jsx(ce.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!ke,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:le("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",ke?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:ie?`Send to ${ie.name} via ${Re.shortLabel}`:`Send via ${Re.shortLabel}`,"aria-label":ie?`Send to ${ie.name} via ${Re.shortLabel}`:`Send message via ${Re.shortLabel}`,children:Te})]}),n.jsx(vt,{children:(ie||K)&&Ae!=="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:[ie&&n.jsxs("button",{ref:X=>{i.current=X},type:"button",onClick:t.toggleWatcherPicker,className:le("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(Xt,{name:ie.name,hint:ie.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",ie.name]}),ie.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),K&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",K.name]}),re!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:Re.accent},children:[n.jsx(el,{icon:Re.icon}),Re.shortLabel]})]})})]})]})]})}const tl={completed:T.lime,needs_attention:T.amber,in_progress:T.teal,blocked:T.red,unknown:"rgba(255,255,255,0.4)"};function nl({workstreamTitle:e,items:t,firstTimestamp:s,lastTimestamp:r,onExpandItem:i}){const[a,c]=o.useState(!1),l=t.reduce((p,x)=>(p[x.status]=(p[x.status]??0)+1,p),{}),d=new Date(s).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),u=new Date(r).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:()=>c(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:T.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:[l.completed&&l.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:T.lime}}),l.completed," completed"]}),l.needs_attention&&l.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:T.amber}}),l.needs_attention," needs attention"]}),l.in_progress&&l.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:T.teal}}),l.in_progress," in progress"]}),l.blocked&&l.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:T.red}}),l.blocked," blocked"]})]}),n.jsxs("p",{className:"mt-1 text-micro text-muted tabular-nums",children:[d," — ",u]})]}),n.jsx("span",{className:"mt-1.5 text-micro text-muted",children:a?"Hide":"Show details"})]}),n.jsx(vt,{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,x)=>n.jsxs(ce.button,{type:"button",initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:x*.04,duration:.15},onClick:()=>i==null?void 0:i(x),className:"flex w-full items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-left hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:tl[p.status]??tl.unknown}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-caption text-primary",children:p.title}),n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:$t(p.timestamp)})]},`burst-${x}`))})})})]})}const la=50,Bf=50,jr=20,sl=3600,rl=12e3,si={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},il=["live","24h","7d","all"];function al(e){if(e==="custom"||e==="all")return null;const t=il.indexOf(e);return t<0?null:il[t+1]??null}function ol(e,t){if(e.size!==t.size)return!1;for(const[s,r]of e){const i=t.get(s);if(!i)return!1;for(const a of Object.keys(r))if(r[a]!==i[a])return!1}return!0}function qf(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 rs(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ri(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function ii(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function ca(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function cl(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Bs(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Wa(e){if(!e)return;let t={...e},s=Bs(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=Bs(s.metadata),r+=1;return t}function lt(e){const t=Bs(e==null?void 0:e.metadata);return Wa(t)}function zf(e){const t=Wa(e);if(!t)return"";const s=[];for(const[r,i]of Object.entries(t))typeof i=="string"&&(r.toLowerCase().includes("type")||r.toLowerCase().includes("kind")||r.toLowerCase().includes("summary")||r.toLowerCase().includes("message")||r.toLowerCase().includes("artifact")||r.toLowerCase().includes("decision")||r.toLowerCase().includes("run")||r.toLowerCase().includes("title")||r.toLowerCase().includes("task")||r.toLowerCase().includes("workstream")||r.toLowerCase().includes("milestone"))&&s.push(i);return s.join(" ")}function bi(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 r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function sr(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),r=(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:r}}function dl(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Wf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Uf=/^[0-9a-f]{20,}$/i,ac=/^\d+$/,oc=/^(user|usr|clerk)_[a-z0-9]+$/i;function pn(e){if(!e)return null;const t=e.trim();return!t||Wf.test(t)||Uf.test(t)||ac.test(t)||oc.test(t)?null:t}const Hf=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Vf(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Hf.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function ul(e,t,s){if(!e)return null;let r=null;for(const a of t){const c=pn(dl(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=pn(dl(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Kf(e,t){var s,r;if(!e||!t)return!1;if(e.id&&t.id){const i=e.id.trim().toLowerCase(),a=t.id.trim().toLowerCase();if(i===a){const c=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,l=((r=t.name)==null?void 0:r.trim().toLowerCase())??null;return c&&l&&c!==l?!1:["unknown","system","agent","none","null","undefined"].includes(i)?!!(c&&l&&c===l):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function ml(e){const t=lt(e),s=sr(e),r=Rr(e),i=pn(s.agentId),a=pn(s.agentName),c=pn(e.requesterAgentId??null),l=pn(e.requesterAgentName??null),u=(c||l?{id:c,name:l,label:l??c??"OrgX"}:null)??ul(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=pn(e.executorAgentId??null),x=pn(e.executorAgentName??null),g=(p||x?{id:p,name:x,label:x??p??"Agent"}:null)??ul(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"])??(i||a?{id:i,name:a,label:a??i??"Agent"}:null);return u&&g?Kf(u,g)?{requester:u,executor:g,mode:"single",primaryLabel:g.label,subtitle:g.label}:{requester:u,executor:g,mode:"handoff",primaryLabel:g.label,subtitle:`${u.label} handed off to ${g.label}`}:u&&!g?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested a run`}:!u&&g?{requester:null,executor:g,mode:"single",primaryLabel:g.label,subtitle:g.label}:r.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:pn(e.agentName??null)??pn(e.agentId??null)??"OrgX",subtitle:pn(e.agentName??null)??pn(e.agentId??null)??"OrgX"}}function pl(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const Gf=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Xf=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Qf(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=lt(e),r=Se(s,["event","event_name","eventName"])??"";return(Se(s,["source"])??"")==="user"?"user":Gf.has(r)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Xf.has(r)?"system":"agent"}const Jf={user:T.lime,system:"rgba(255,255,255,0.15)",orchestrator:T.iris,agent:""};function Yf(e){switch(e){case"user":return"You";case"system":return"OrgX";case"orchestrator":return"Xandy";case"agent":return""}}function tr(e){const t=lt(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const i of s){const a=t[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const r=t.orgx_context;if(r&&typeof r=="object"&&!Array.isArray(r)){const i=r,a=i.workstreamId??i.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function ai(e){const t=lt(e);if(!t)return null;const s=["artifact_id","artifactId","work_artifact_id"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.length>0)return i}return null}const fl=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 oi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function lc(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="boolean")return r;if(typeof r=="string"){const i=r.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}}return null}function Ps(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,r);if(typeof r=="string"){const i=Number(r);if(Number.isFinite(i))return Math.max(0,i)}}return null}function Zf(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 eh(e){const t=lt(e),s=oi(e.kind)??oi(t==null?void 0:t.activity_bucket)??oi(t==null?void 0:t.activityBucket)??oi(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 r=Zf(t),i=e.decisionRequired===!0||lc(t,["decision_required","decisionRequired"])===!0,a=Ps(t,["artifacts","artifact_count","artifactCount"])??0,c=Ps(t,["decisions","decision_count","decisionCount"])??0,l=Ps(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ps(t,["non_blocking_decisions","nonBlockingDecisions","non_blocking_decision_count","nonBlockingDecisionCount"])??0;if(r==="autopilot_slice_result")return i||l>0?"decision":a>0?"artifact":c>0||d>0?"decision":"message";if(r==="auto_continue_stopped"){const p=Mn(Se(t,["stop_reason","stopReason"])??"");if(p==="blocked"||p==="error")return"decision"}return r&&fl.has(r)?fl.get(r):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":i||c>0||l>0||d>0?"decision":"message"}function th(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=Se(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if($r(s))return!0;const r=Se(t,["stop_reason","stopReason"]);if(Mn(r)==="completed")return!0;const i=t?cc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||lc(t,["decision_required","decisionRequired"])===!0,c=Ps(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0;return i!==null&&i>=100&&!a&&c===0}function Si(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 nh(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 sh(e){const t=Number(e);if(!Number.isFinite(t))return"Unknown day";const s=new Date(t),r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()),a=new Date(i);return a.setDate(i.getDate()-1),s.getTime()===i.getTime()?"Today":s.getTime()===a.getTime()?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:s.getFullYear()===r.getFullYear()?void 0:"numeric"})}function da(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function ua(e){return e==="completed"?T.lime:e==="needs_input"?T.amber:e==="issue"?T.red:T.teal}function rh(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 hl(e){let t="Workstream";const s=e.allItems.map(r=>{const i=lt(r.item),a=Se(i,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const l=Se(i,["task_title","taskTitle","dispatch_task_title"])??Rr(r.item).title;let d="unknown";return r.userState==="completed"?d="completed":r.userState==="needs_input"||r.userState==="issue"?d="needs_attention":r.userState==="in_progress"&&(d="in_progress"),{title:l,status:d,timestamp:r.item.timestamp}});return{workstreamTitle:t,items:s}}function gl(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function js(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 ns(e){const t=js(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,r=js(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function ih(e){const t=js(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 cc(e,t){for(const s of t){const r=ih(e[s]);if(r!==null)return r}return null}function li(e,t){const s=[],r=new Set,i=a=>{if(typeof a!="string")return;const c=a.trim();!c||r.has(c)||(r.add(c),s.push(c))};for(const a of t){const c=e[a];if(Array.isArray(c)){for(const l of c)i(l);continue}i(c)}return s}function dc(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=li(e,["blocking_decision_ids","blockingDecisionIds"]),s=li(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=li(e,["decision_id","decisionId","decision_ids","decisionIds"]),i=new Set([...r,...t,...s]),a=e.decisions_needed??e.decisionsNeeded;if(Array.isArray(a))for(const c of a){if(!c||typeof c!="object"||Array.isArray(c))continue;const l=c,d=li(l,["id","decision_id","decisionId"]),u=l.blocking!==!1;for(const p of d)i.add(p),u?t.includes(p)||t.push(p):s.includes(p)||s.push(p)}return{decisionIds:Array.from(i),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function uc(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,r=s??"",i=r.startsWith("autopilot_slice")&&!r.includes("artifact")||r.startsWith("autopilot_autofix");if(!s||!i&&s!=="auto_continue_started"&&s!=="auto_continue_stopped"&&s!=="next_up_manual_dispatch_started")return null;const a=sr(e),c=(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,l=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,p=Array.isArray(u)?u.filter(G=>typeof G=="string"&&G.trim().length>0):[],x=ph(p),b=t.task_ids??t.taskIds,g=Array.isArray(b)?b.filter(G=>typeof G=="string"&&G.trim().length>0):[],j=t.milestone_ids??t.milestoneIds,y=Array.isArray(j)?j.filter(G=>typeof G=="string"&&G.trim().length>0):[],I=Se(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),k=Se(t,["initiative_title","initiativeTitle"]),N=Se(t,["initiative_status","initiativeStatus"]),h=tr(e),C=Se(t,["workstream_title","workstreamTitle"]),V=Se(t,["workstream_status","workstreamStatus"]),te=Se(t,["task_title","taskTitle"]),z=Se(t,["milestone_title","milestoneTitle"]),Ie=Se(t,["domain"]),B=Se(t,["phase","slice_phase","slicePhase"]),ee=Se(t,["next_step","nextStep"]),be=cc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),ve=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,Ae=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,ue=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,Ke=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,pe=typeof t.error=="string"?t.error:null,ae=ns(t.artifacts??t.artifact_count??t.artifactCount),ne=ns(t.decisions??t.decision_count??t.decisionCount),ie=dc(t),xe=t.decisions_needed??t.decisionsNeeded;let K=ns(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),R=ns(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((K===null||R===null)&&Array.isArray(xe)){let G=0,re=0;for(const Re of xe){if(!Re||typeof Re!="object"||Array.isArray(Re))continue;Re.blocking===!1?re+=1:G+=1}K===null&&(K=G),R===null&&(R=re)}K===null&&ne!==null&&e.decisionRequired===!0&&(K=ne>0?ne:1),R===null&&ne!==null&&K!==null&&(R=Math.max(0,ne-K)),K===null&&ne!==null&&R!==null&&(K=Math.max(0,ne-R));const U=ns(t.status_updates_applied??t.statusUpdatesApplied),P=ns(t.task_updates??t.taskUpdates),H=ns(t.milestone_updates??t.milestoneUpdates),Q=U??(P!==null||H!==null?(P??0)+(H??0):null),ge=ns(t.status_updates_buffered??t.statusUpdatesBuffered),ke=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,se=js(t.token_budget??t.tokenBudget),ye=js(t.tokens_used??t.tokensUsed),he=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),L=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)??x,q=x&&!a.agentName?null:he;return{event:s,agentId:q,agentName:L,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:I,domain:Ie,phase:B,progressPct:be,nextStep:ee,requiredSkills:p,initiativeStatus:N,initiativeTitle:k,workstreamId:h,workstreamStatus:V,workstreamTitle:C,taskTitle:te,milestoneTitle:z,taskIds:g,milestoneIds:y,parsedStatus:ve,hasOutput:Ae,artifacts:ae,decisions:ne,blockingDecisions:K,nonBlockingDecisions:R,decisionIds:ie.decisionIds,blockingDecisionIds:ie.blockingDecisionIds,nonBlockingDecisionIds:ie.nonBlockingDecisionIds,statusUpdatesApplied:Q,statusUpdatesBuffered:ge,stopReason:ke,tokenBudget:se,tokensUsed:ye,logPath:ue,outputPath:Ke,error:pe}}function ma(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function ah(e){const t=Wa(e);if(!t)return null;const s=t,r=s.orgx_provenance,i=r&&typeof r=="object"&&!Array.isArray(r)?r:null,a=i!=null&&i.skill_pack&&typeof i.skill_pack=="object"&&!Array.isArray(i.skill_pack)?i.skill_pack:null,c=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(i==null?void 0:i.plugin_version)=="string"?i.plugin_version:null),l=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),p=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),x=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,b=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,g=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,j=typeof s.provider=="string"?s.provider:null,y=typeof s.model=="string"?s.model:null,I=typeof s.domain=="string"?s.domain:null,k=s.required_skills??s.requiredSkills,N=Array.isArray(k)?k.filter(C=>typeof C=="string"&&C.trim().length>0):[];return!!c||!!(l||d||u)||!!x||!!(g||j||y||I)||N.length>0?{pluginVersion:c,skillPack:l||d||u||p?{name:l,version:d,checksum:u,source:p}:null,kickoffContextHash:x,kickoffContextSource:b,modelTier:g,provider:j,model:y,domain:I,requiredSkills:N}:null}function mc(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 r of s){const i=t[r];if(i!=null)return{source:r,value:i}}return e.type==="artifact_created"?{source:"metadata",value:t}:null}function oh(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":at(e)}function lh(e){const t=lt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=mc(e);if(!r&&!s)return null;const i=Se(t,["artifact_type","artifactType","atomic_unit_type"]),a=Se(t,["artifact_title","title","name"]),c=Se(t,["url","pr_url","commit_url"]),l=oh(i);let d=l;i||(e.type==="artifact_created"?d="Created artifact":(r==null?void 0:r.source)==="toolOutput"||(r==null?void 0:r.source)==="toolOutputs"?d="Tool output":(r==null?void 0:r.source)==="toolResult"||(r==null?void 0:r.source)==="toolResults"?d="Result":(r==null?void 0:r.source)==="output"||(r==null?void 0:r.source)==="outputs"?d="Output":s?d="Registered artifact":d="Artifact");let u="";if(a)u=a;else if(r){const p=r.value;if(typeof p=="string")u=p.length>80?p.slice(0,80)+"…":p;else if(Array.isArray(p))u=`${p.length} item${p.length===1?"":"s"}`;else if(p&&typeof p=="object"){const x=Object.keys(p);u=x.length<=4?x.join(", "):`${x.length} fields`}}return{label:d,preview:u,hasRegisteredId:s,title:a,typeBadge:l,url:c}}function ch(e){const t=lt(e);if(!t)return[];const s=[],r=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,i=Se(t,["pr_url"])??(r?Se(r,["pr_url"]):null),a=Se(t,["pr_number"])??(r?Se(r,["pr_number"]):null);(a||i)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:i});const c=Se(t,["commit_sha"])??(r?Se(r,["commit_sha"]):null),l=Se(t,["commit_url"])??(r?Se(r,["commit_url"]):null);(c||l)&&s.push({kind:"commit",label:c?c.slice(0,7):"linked",url:l});const d=r==null?void 0:r.tests;if(d&&typeof d=="object"){const x=d,b=typeof x.passed=="number"?x.passed:null,g=typeof x.failed=="number"?x.failed:null;if(b!==null||g!==null){const j=[];b!==null&&j.push(`${b} passed`),g!==null&&g>0&&j.push(`${g} failed`),s.push({kind:"test",label:j.join(", ")})}}const u=typeof t.task_updates=="number"?t.task_updates:r&&typeof r.task_updates=="number"?r.task_updates:null;u&&u>0&&s.push({kind:"artifact",label:`${u} task${u===1?"":"s"} updated`});const p=Array.isArray(t.artifacts)?t.artifacts:null;if(p&&p.length>0&&s.length<2){const x=p[0],b=x&&typeof x=="object"&&typeof x.title=="string"?x.title:null;s.push({kind:"doc",label:b??`${p.length} artifact${p.length===1?"":"s"}`})}return s}function dh(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 pc(e){const t=lt(e);if(!t)return[];const s=[],r=new Set,i=(c,l)=>{if(typeof l!="string")return;const d=l.trim();if(!d||!dh(d))return;const u=`${c}:${d}`;r.has(u)||(r.add(u),s.push({key:c,path:d}))},a=(c,l="",d=0)=>{if(!(d>2))for(const[u,p]of Object.entries(c)){const x=l?`${l}.${u}`:u,b=u.toLowerCase();if(b.includes("path")||b==="url"||b==="uri"||b.endsWith("url")||b.endsWith("_file")||b.endsWith("file")||b.includes("artifact"))if(Array.isArray(p))for(const j of p)i(x,j);else i(x,p);p&&typeof p=="object"&&!Array.isArray(p)&&a(p,x,d+1)}};return a(t),s}function Se(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Ir(e,t){if(typeof e!="string")return null;const s=e.trim();if(!s)return null;const r=typeof t=="string"?t.trim().toLowerCase():"";return r&&s.toLowerCase()===r||Vn(s)?null:s}function ci(e){for(const t of e){const s=Ir(t.value,t.idHint);if(s)return s}return null}function uh(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 mh(e,t){if(!e)return null;const s=lt(e);if(!s)return null;const r=Se(s,["event","event_name","eventName"]),i=Bs(s.spawn_guard),a=Bs(i==null?void 0:i.checks),c=Bs((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=Se(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=uh(l),u=js(c==null?void 0:c.current)??d.domainCurrent,p=js(c==null?void 0:c.max)??d.domainMax,x=d.totalCurrent,b=d.totalMax,g=typeof(c==null?void 0:c.passed)=="boolean"?c.passed:null,j=((r==null?void 0:r.includes("rate_limited"))??!1)||!!(l&&/rate limit/i.test(l))||g===!1;return!((r==null?void 0:r.includes("spawn_guard"))??!1)&&!j&&!i&&!l?null:{event:r,blockedReason:l,domain:Se(s,["domain"])??Se(i,["domain","task_domain"]),modelTier:Se(s,["spawn_guard_model_tier","model_tier"])??Se(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:p,totalCurrent:x,totalMax:b,retryAt:Se(s,["next_retry_at","nextRetryAt"]),retryInMs:js(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:j}}function ph(e){var r;if(e.length!==1)return null;const t=(r=e[0])==null?void 0:r.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 i=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return i.length===0?null:`OrgX ${at(i)}`}return null}function fh(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 pa(e,t,s){const r=typeof e=="string"&&e.trim().length>0?e.trim():null,i=typeof t=="string"&&t.trim().length>0?t.trim():null,a=i?(s==null?void 0:s.get(i))??null:null,c=r&&a&&fh(r)?a:r??a;if(c)return qi(c);if(!i)return"OrgX";const l=i.toLowerCase();return l==="main"||l==="system"||l==="unknown"||l==="runtime"||l==="orgx"||l==="openclaw"||l==="null"||l==="undefined"?qi(i):Ar.test(i)||hh.test(i)||ac.test(i)||oc.test(i)?"OrgX":qi(i)}const Ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hh=/^[0-9a-f]{20,}$/i,gh=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function Ci(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 c of a.match(gh)??[]){const l=c.trim().toLowerCase();Ar.test(l)&&t.add(l)}typeof e.runId=="string"&&Ar.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=lt(e);if(!s)return t;const r=["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"],i=["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 r){const c=s[a];if(typeof c=="string"){const l=c.trim().toLowerCase();Ar.test(l)&&t.add(l)}}for(const a of i){const c=s[a];if(Array.isArray(c))for(const l of c){if(typeof l!="string")continue;const d=l.trim().toLowerCase();Ar.test(d)&&t.add(d)}}return t}function xh(e){if(!e)return[];const t=lt(e);return dc(t).decisionIds}function yh(e,t,s){if(!e)return[];const r=lt(e),i=Se(r,["workstream_id","workstreamId"]),a=Se(r,["initiative_id","initiativeId"]),c=Ci(e);if(!i&&!a&&c.size===0)return[];const l=rs(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const g=lt(b);if(!g)continue;const j=Se(g,["workstream_id","workstreamId"]),y=Se(g,["initiative_id","initiativeId"]),I=Ci(b),k=c.size>0&&Array.from(c).some(z=>I.has(z)),N=!!i&&!!j&&i===j;if(!k&&!N&&!(!!a&&!!y&&a===y))continue;const C=pc(b).filter(z=>!s.has(z.path));if(C.length===0)continue;const V=Math.abs(rs(b.timestamp)-l);if(!k&&V>7200*1e3)continue;const te=k?0:N?1:2;!k&&V>1200*1e3||d.push({priority:te,delta:V,evidence:C})}if(d.length===0)return[];d.sort((b,g)=>b.priority!==g.priority?b.priority-g.priority:b.delta-g.delta);const u=[],p=new Set(s),x=d[0].priority;for(const b of d){if(b.priority!==x)break;for(const g of b.evidence)if(!p.has(g.path)&&(p.add(g.path),u.push({key:`related.${g.key}`,path:g.path}),u.length>=8))return u}return u}function bh(e,t){if(!e)return null;const s=lt(e),r=Se(s,["workstream_id","workstreamId"]),i=Se(s,["initiative_id","initiativeId"]),a=Ci(e);if(!r&&!i&&a.size===0)return null;const c=rs(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const p=uc(u);if(!p)continue;const x=lt(u);if(!x)continue;const b=Se(x,["workstream_id","workstreamId"]),g=Se(x,["initiative_id","initiativeId"]),j=Ci(u),y=a.size>0&&Array.from(a).some(V=>j.has(V)),I=!!r&&!!b&&r===b;if(!y&&!I&&!(!!i&&!!g&&i===g))continue;const N=Math.abs(rs(u.timestamp)-c);if(!y&&N>1200*1e3)continue;const h=y?"shared_id":I?"workstream":"initiative",C=h==="shared_id"?0:h==="workstream"?1:2;l.push({priority:C,delta:N,relation:h,detail:p})}if(l.length===0)return null;l.sort((u,p)=>u.priority!==p.priority?u.priority-p.priority:u.delta-p.delta);const d=l[0];return{detail:d.detail,relation:d.relation}}function Mn(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function $r(e){const t=Mn(e);return["done","complete","completed","stopped","success"].includes(t)}function wh(e){const t=Mn(e.parsedStatus),s=Mn(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":$r(t)||e.stopReason==="completed"?"positive":"neutral"}function vh(e){if($r(e.parsedStatus)||e.stopReason==="completed")return 100;const t=Mn(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 fc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function kh(e,t){if(!e&&t===null)return null;const s=e?wh(e):"neutral",r=l=>l>=100&&(s==="warning"||s==="critical"),i="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 l=fc(e.progressPct)??0,d=r(l);return{pct:l,source:"metadata",label:d?i:"Progress",tone:s,terminalStop:d}}if(t!==null){const l=r(t);return{pct:t,source:"session",label:l?i:"Progress",tone:s,terminalStop:l}}if(!e)return null;const a=vh(e);if(a===null)return null;const c=r(a);return{pct:a,source:"lifecycle",label:c?i:"Progress",tone:s,terminalStop:c}}function jh(e,t,s,r=null){var k;const i=lt(e),a=Mn(Se(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=Mn(e.state??e.phase??e.kind??e.type),l=Mn((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=Mn((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=Se(i,["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),x=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,p):0)),b=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,p-x)),g=e.decisionRequired===!0||e.type==="decision_requested"||x>0||l==="needs_decision"&&b===0,j=e.type==="run_completed"||e.type==="milestone_completed"||$r(l)||d==="completed",y=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),I=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:tn(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 N=typeof(i==null?void 0:i.tasks_completed)=="number"?i.tasks_completed:null;return{label:"All done",summary:N?`All queued work complete — ${N} task${N===1?"":"s"} finished`:"All queued work complete",hint:null,tone:"positive"}}if(d==="stopped")return{label:"Stopped",summary:tn(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:g?"Needs decision":"Blocked",summary:tn(e.title)??(g?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:g?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:g?"warning":"critical"};if(d==="error")return{label:"Error",summary:tn(e.title)??u??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const N=String((i==null?void 0:i.new_state)??"");return N==="running"?{label:"Resumed",summary:"Resumed — dispatching work",hint:"Autopilot is actively working through the queue.",tone:"positive"}:N==="blocked"||N==="error"?{label:"Paused",summary:"Paused — waiting for input",hint:"Review blockers and resolve to continue.",tone:"critical"}:null}if(y)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(I)return{label:"Waiting on system",summary:u?tn(u)??"Waiting for system capacity.":"Waiting for system capacity.",hint:"Capacity will become available automatically, or adjust limits in settings.",tone:"critical"};if(r){if(r.status==="completed")return{label:b>0?"Completed + follow-up":"Completed",summary:b>0?`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`:r.sentence,hint:r.nextAction,tone:"positive"};if(r.status==="failed")return{label:"Failed",summary:u?tn(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const N=g||(((k=r.nextAction)==null?void 0:k.toLowerCase().includes("decision"))??!1);return{label:N?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(N?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:N?"warning":"critical"}}if(r.status==="in_progress")return{label:"In progress",summary:r.sentence,hint:null,tone:"neutral"}}return e.type==="run_failed"||e.type==="blocker_created"||l==="blocked"||l==="failed"||l==="error"||d==="blocked"||d==="error"?{label:g?"Waiting on you":"Blocked",summary:u?tn(u)??"Execution is blocked.":g?"Blocked waiting on decision from you":"Paused after top queue item blocked",hint:g?"Resolve the pending decision in the Decisions panel to continue.":"Review blocker details, then retry or skip to continue.",tone:"critical"}:g?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:j&&b>0?{label:"Completed + follow-up",summary:`Execution completed. ${b} non-blocking decision${b===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"}:j?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||c==="running"||c==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function hc(e){if(typeof e=="string")return n.jsx(_r,{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:hc(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:t.map(([s,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:at(s)}),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"}`:"—"})]},s))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function tn(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=Cr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:at(t)}const Nh=[/^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];function Ih(e){return Nh.some(t=>t.test(e))}function gc(e){const t=lt(e);if(!t)return null;const s=Se(t,["user_summary","userSummary"]);if(s)return s;const r=Se(t,["task_title","taskTitle","dispatch_task_title"])??Se(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),i=Se(t,["event","event_name","eventName"]),a=Se(t,["parsed_status","status"]),c=Se(t,["stop_reason","stopReason"]),l=Se(t,["artifact_type","artifactType"]),d=Se(t,["artifact_title","title","name"]),u=Se(t,["agent_name","agentName","requested_by_agent_name"]);switch(i){case"autopilot_slice_dispatched":case"autopilot_slice_started":return`Working on ${r??"queued task"}`;case"autopilot_slice_result":case"autopilot_slice_finished":return a==="completed"||a==="success"?r?`Finished ${r}`:"Task completed":a==="blocked"||a==="needs_decision"?r?`Needs help with ${r}`:"Needs your input":r?`Worked on ${r}`:null;case"auto_continue_started":return"Autopilot started";case"auto_continue_stopped":return c==="budget_exhausted"?"Paused — budget reached":c==="completed"?"All queued work complete":c==="blocked"?"Paused — needs your input":c==="error"?"Paused — hit an error":"Autopilot paused";case"autopilot_transition":return null;case"autopilot_item_skipped":return`Skipped ${r??"blocked item"}, continuing`}if(e.type==="run_started")return r?`Started ${r}`:null;if(e.type==="run_completed")return r?`Completed ${r}`:null;if(e.type==="run_failed")return r?`Hit an issue with ${r}`:null;if(e.type==="artifact_created"){const p=l?at(l):"artifact";return d?`Created ${p}: ${d}`:`Created ${p}`}if(e.type==="artifact_updated")return d?`Updated ${d}`:"Updated artifact";if(e.type==="delegation"&&u&&r)return`${u} is handling ${r}`;if(i==="decision_needed"){const p=Se(t,["decision_title","decisionTitle","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(i==="decision_resolved"){const p=Se(t,["decision_title","decisionTitle","title"]);return p?`Decision resolved: ${p}`:"Decision resolved"}return i==="spawn_guard_blocked"||i==="spawn_guard_rate_limited"?"Waiting for capacity":null}function Ah(e,t,s){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")),(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 Rr(e){const t=gc(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";return Ih(s)?/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}:{title:at(s)||at(Si(e.type)),isSystem:!1}}const _h=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),Sh=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 Sr(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),r=(typeof t.source_client=="string"?t.source_client:null)??(typeof t.sourceClient=="string"?t.sourceClient:null),i=(r==null?void 0:r.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)??"",c=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),l=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&Sh.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function xl(e){var d;if(!e||!Sr(e))return null;const t=lt(e),s=ns((t==null?void 0:t.applied_count)??(t==null?void 0:t.appliedCount)??(t==null?void 0:t.applied)??null),r=(typeof(t==null?void 0:t.idempotency_key)=="string"?t.idempotency_key:null)??(typeof(t==null?void 0:t.idempotencyKey)=="string"?t.idempotencyKey:null),i=((d=r==null?void 0:r.match(/sentinel:([a-z_]+):/i))==null?void 0:d[1])??null,a=Se(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),c=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",l=a?` for ${at(a).toLowerCase()}`:"";return`${c}${l} were synced from local replay.`}function fa(e){if(!Sr(e))return null;const t=lt(e);if(!t)return null;const s=Se(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=Se(t,["event","event_name","eventName"])??"",i=Se(t,["changeset_id","changesetId"])??"",a=Se(t,["entity_type","entityType"])??"",c=Se(t,["entity_id","entityId"])??"",l=bi(e)??"",d=Rr(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function Ch(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():"",r=typeof t.turnId=="string"?t.turnId.trim():"";if(s!=="local_openclaw"||!r)return null;const i=typeof t.sessionKey=="string"&&t.sessionKey.trim().length>0?t.sessionKey.trim():null;return{turnId:r,sessionKey:i,runId:e.runId??null}}function yl(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 Mh=[/^Autopilot dispatched slice for\s*/i,/^Orchestrator (selected|dispatched)\s*/i,/^Auto[-_]?continue.*?dispatching\s*/i,/^Slice (started|dispatched) for\s*/i];function bl(e,t){const s=gc(e);if(s)return s;let i=(tn(t??e.summary)??tn(e.description)??at(e.title||Si(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 l of Mh)i=i.replace(l,"");i=i.trim();const a=i.split(`
211
- `).map(l=>yl(l).trim()).filter(l=>l.length>0&&!/^\|?[:\-| ]+\|?$/.test(l));let c=a[0]??yl(i);return c.length<24&&a.length>1&&(c=`${c} ${a[1]}`.trim()),c.length>108?`${c.slice(0,107).trimEnd()}…`:c}const Th=o.memo(function({activity:t,sessions:s,sliceRuns:r=[],initiatives:i=[],timelineNarrative:a=[],selectedRunIds:c,selectedSessionLabel:l=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:p=null,timeFilterId:x="live",onTimeFilterChange:b,customTimeRange:g={startIso:null,endIso:null},onCustomTimeRangeChange:j,hasMore:y=!1,isLoadingMore:I=!1,onLoadMore:k,onClearSelection:N,onClearWorkstreamFilter:h,onClearAgentFilter:C,onFocusRunId:V,onOpenDecision:te,requestedActivityItemId:z=null,onActivityItemRequestHandled:Ie,onPlayNextUp:B,onStartAutopilot:ee,onPauseWorkstream:be,onCreateInitiative:ve,onOpenMissionControl:Ae,onOpenSettings:ue,workspaceId:Ke=null,chatSnapshot:pe,onRefreshData:ae,isLoading:ne=!1,onOpenNextUp:ie,devMode:xe=!1,nextUpQueue:K,autopilotState:R=null}){var Ha;const U=is(),{open:P}=Jl(),H=o.useMemo(()=>{if(!K)return new Map;const f=new Map;for(let v=0;v<K.length;v++){const w=K[v];f.set(w.workstreamId,{rank:v+1,title:w.workstreamTitle,state:w.queueState})}return f},[K]),[Q,ge]=o.useState("all"),[ke,se]=o.useState(!1),[ye,he]=o.useState(""),[L,q]=o.useState(new Set),[G,re]=o.useState({}),[Re,Ge]=o.useState("oldest"),[Ee,$]=o.useState(!1),[rt,Le]=o.useState(!1),[Xe,kt]=o.useState(la),[jt,Nt]=o.useState(null),[O,_e]=o.useState(null),[fe,Te]=o.useState(!1),[Qe,tt]=o.useState(1),[Y,We]=o.useState("structured"),[we,X]=o.useState(null),[$e,He]=o.useState("feed"),[De,st]=o.useState(null),[dt,Ct]=o.useState(null),[Dt,W]=o.useState(!1),[Ne,Ue]=o.useState(null),[Ve,ze]=o.useState(null),[qe,Oe]=o.useState(!1),[ut,Ft]=o.useState(null),[pt,bt]=o.useState(!1),At=o.useRef(Date.now()),nt=o.useRef(null),Pt=o.useRef(null),Je=o.useRef(null),qt=o.useRef(null),Mt=o.useRef(null),[_t,Ut]=o.useState(()=>ri(g.startIso)),[It,on]=o.useState(()=>ri(g.endIso)),[as,os]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Is=o.useMemo(()=>Ll(x),[x]),$n=o.useMemo(()=>ri(g.startIso),[g.startIso]),Ht=o.useMemo(()=>ri(g.endIso),[g.endIso]),Nn=o.useMemo(()=>!_t||!It?!1:It.getTime()>=_t.getTime(),[It,_t]),As=o.useMemo(()=>x!=="custom"?Is.label:$n&&Ht?`${ii($n)} - ${ii(Ht)}`:"Custom range",[Ht,$n,x,Is.label]);o.useEffect(()=>{Ut($n),on(Ht)},[Ht,$n]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>os(window.innerWidth<=640);return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),o.useEffect(()=>{const v=()=>{At.current=Date.now()};window.addEventListener("pointerdown",v),window.addEventListener("keydown",v);const w=setInterval(()=>{Date.now()-At.current>3e5&&bt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",v),window.removeEventListener("keydown",v),clearInterval(w)}},[]);const sn=o.useMemo(()=>{const f=s.filter(S=>S.status==="completed").length,v=s.filter(S=>S.status==="blocked"||S.status==="failed").length,w=t.filter(S=>{var oe;return S.type==="decision_requested"&&((oe=S.metadata)==null?void 0:oe.status)==="pending"}).length;return{completed:f,blocked:v,decisions:w}},[s,t]),ls=o.useMemo(()=>{const f=new Map;for(const v of s)f.set(v.runId,v.title),f.set(v.id,v.title);return f},[s]),Tn=o.useMemo(()=>{const f=new Map;for(const v of s)v.status&&(f.set(v.runId,v.status),f.set(v.id,v.status));return f},[s]),Kn=o.useRef(new Map),Dn=o.useMemo(()=>{var v;const f=new Map;for(const w of s){const S={status:w.status??null,phase:w.phase??null,state:w.state??null,blockerCount:Array.isArray(w.blockers)?w.blockers.length:0,blockerReason:w.blockerReason??((v=w.blockerDiagnostics)==null?void 0:v.reason)??null};f.set(w.runId,S),f.set(w.id,S)}return ol(Kn.current,f)?Kn.current:(Kn.current=f,f)},[s]),Gn=o.useRef(new Map),cs=o.useMemo(()=>{const f=new Map;for(const v of r){const w={status:v.status??null,blockingDecisions:Math.max(0,v.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(v.decisionCount??0)-(v.blockingDecisionCount??0)),updatedEpoch:rs(v.updatedAt??v.lastEventAt??v.startedAt??null)},S=[v.runId,v.sliceRunId].filter(oe=>typeof oe=="string"&&oe.trim().length>0).map(oe=>oe.trim());for(const oe of S){const Pe=f.get(oe);(!Pe||w.updatedEpoch>=Pe.updatedEpoch)&&f.set(oe,w)}}return ol(Gn.current,f)?Gn.current:(Gn.current=f,f)},[r]),Jt=o.useMemo(()=>{const f=new Map;for(const v of r){const w={startedAt:v.startedAt??null,completedAt:v.completedAt??null},S=[v.runId,v.sliceRunId].filter(oe=>typeof oe=="string"&&oe.trim().length>0);for(const oe of S)f.set(oe,w)}return f},[r]),ds=o.useMemo(()=>{const f=new Map;for(const v of s){const w=fc(v.progress);w!==null&&(f.set(v.runId,w),f.set(v.id,w))}return f},[s]),fn=o.useMemo(()=>{const f=new Map;for(const v of s)!v.agentId||!v.agentName||f.set(v.agentId,v.agentName);return f},[s]),Fn=o.useMemo(()=>{const f=new Map;for(const v of s){const w=v.workstreamId??null;f.set(v.runId,w),f.set(v.id,w)}return f},[s]),D=o.useMemo(()=>{const f=new Map;for(const v of r){const w=v.workstreamId??null,S=Ir(v.workstreamTitle,w);if(!S)continue;const oe=[v.runId,v.sliceRunId].filter(Pe=>typeof Pe=="string"&&Pe.trim().length>0).map(Pe=>Pe.trim());for(const Pe of oe)f.set(Pe,S)}return f},[r]),de=o.useMemo(()=>{const f=new Map;for(const v of i){const w=Ir(v.name,v.id);w&&f.set(v.id,w)}return f},[i]),me=o.useMemo(()=>{const f=new Map;for(const v of i)for(const w of v.workstreams??[]){const S=Ir(w.name,w.id);S&&f.set(w.id,S)}for(const v of r){const w=v.workstreamId??null;if(!w||f.has(w))continue;const S=Ir(v.workstreamTitle,w);S&&f.set(w,S)}return f},[i,r]);o.useMemo(()=>{const f=[...s];return f.sort((v,w)=>{const S=rs(v.updatedAt??v.lastEventAt??v.startedAt??null);return rs(w.updatedAt??w.lastEventAt??w.startedAt??null)-S}),f},[s]);const Ce=o.useMemo(()=>t.map(f=>{const v=bi(f),w=eh(f),S=lt(f),oe=v?Dn.get(v)??null:null,Pe=v?cs.get(v)??null:null,Be=th(f,S),Ye=Qp({sessionStatus:Be?null:(oe==null?void 0:oe.status)??(v?Tn.get(v)??null:null),sessionPhase:Be?null:(oe==null?void 0:oe.phase)??null,sessionState:Be?null:(oe==null?void 0:oe.state)??null,sliceStatus:Be?null:(Pe==null?void 0:Pe.status)??null,activityType:f.type,activityStatus:Se(S,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:Se(S,["stop_reason","stopReason"]),decisionRequired:f.decisionRequired??!1,blockingDecisionCount:Ps(S,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Pe==null?void 0:Pe.blockingDecisions)??0,nonBlockingDecisionCount:Ps(S,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Pe==null?void 0:Pe.nonBlockingDecisions)??0,blockerCount:Be?0:(oe==null?void 0:oe.blockerCount)??0,blockerReason:Be?null:(oe==null?void 0:oe.blockerReason)??null}),mt=rh(w,Ye),ct=[f.title,f.description,f.summary,f.agentName,zf(S)].filter(Kt=>typeof Kt=="string"&&Kt.length>0).join(" ").toLowerCase(),je=v?(ls.get(v)??v).toLowerCase():"",ht=S==null?void 0:S.scope,gt=ht==="milestone"||ht==="workstream"?ht:void 0;return{item:f,bucket:w,userState:mt.state,userStateWhy:mt.why,canonicalProjection:Ye,runId:v,timestampEpoch:rs(f.timestamp),searchText:ct,runLabelSearch:je,scopeGroupId:gt?v??null:null,scope:gt}}),[t,ls,Dn,Tn,cs]),xt=o.useMemo(()=>{const f=[...Ce];return f.sort((v,w)=>{const S=w.timestampEpoch-v.timestampEpoch;return S!==0?S:w.item.id.localeCompare(v.item.id)}),f},[Ce]),Bt=o.useMemo(()=>[...xt].reverse(),[xt]),ft=o.useMemo(()=>{let f=0;for(const v of Ce)f=Math.max(f,v.timestampEpoch);return f<=0?!1:Date.now()-f<6e4},[Ce]),zt=o.useMemo(()=>new Set(c.filter(f=>f&&f.trim().length>0)),[c]),rn=zt.size>0,Pn=o.useMemo(()=>Mr.filter(f=>["live","24h","7d","all"].includes(f.id)),[]),St=o.useMemo(()=>{if(!rn)return null;for(const f of zt){const v=s.find(w=>w.runId===f||w.id===f);if(v)return v}return null},[rn,zt,s]),Tt=o.useMemo(()=>rn?St!=null&&St.runtimeProvider?{id:qf(St.runtimeProvider)}:ks(St==null?void 0:St.agentId,St==null?void 0:St.agentName,St==null?void 0:St.title,St==null?void 0:St.lastEventSummary,St==null?void 0:St.runtimeClient,l):ks(),[St,rn,l]),In=o.useMemo(()=>p?ks(p):ks(),[p]),{filtered:Et,filteredTotal:An,hiddenCount:_n,hiddenSyncCount:_s}=o.useMemo(()=>{const f=Re==="newest"?xt:Bt,v=[];let w=0,S=0,oe=0;const Pe=new Set,Be=ye.trim().toLowerCase();for(const je of f){const ht=je.runId;if(rn&&(!ht||!zt.has(ht)))continue;if(d){const mn=tr(je.item),En=ht?Fn.get(ht)??null:null;if((mn??En)!==d)continue}const gt=sr(je.item);if(p&&gt.agentName!==p){oe++;continue}if(!xe){const mn=lt(je.item),En=Se(mn,["event","event_name","eventName"]);if(En&&_h.has(En))continue}const Kt=fa(je.item);if(Kt){if(Pe.has(Kt)){S+=1;continue}if(Pe.add(Kt),!ke){S+=1;continue}}else if(!ke&&Sr(je.item)){S+=1;continue}Q==="completed"&&je.userState!=="completed"||Q==="needs_attention"&&je.userState!=="needs_input"&&je.userState!=="issue"||Q==="in_progress"&&je.userState!=="in_progress"||Be.length>0&&!`${je.searchText} ${je.runLabelSearch}`.includes(Be)||(v.length<rl?v.push(je):w+=1)}const Ye=Math.min(Math.max(1,Math.min(sl,Xe)),v.length),mt=v.slice(0,Ye),ct=v.length+w;return{filtered:mt,filteredTotal:ct,hiddenCount:Math.max(0,ct-mt.length),hiddenSyncCount:S,skippedByAgent:oe}},[Q,p,xt,Bt,rn,ye,Xe,d,zt,Fn,ke,Re]),hn=o.useMemo(()=>{if(!p)return null;let f=0;for(const v of t)if(sr(v).agentName===p){const S=rs(v.timestamp);S>f&&(f=S)}return f===0?null:$t(f)},[p,t]),an=o.useMemo(()=>{const f=new Map;for(const w of Et){const S=nh(w.item.timestamp),oe=f.get(S);oe?oe.push(w):f.set(S,[w])}return Array.from(f.keys()).sort((w,S)=>{const oe=Number(S)-Number(w);return Re==="newest"?oe:-oe}).map(w=>({key:w,label:sh(w),items:f.get(w)??[]}))},[Et,Re]),Xn=o.useMemo(()=>an.map(f=>{const v=new Map;for(const w of f.items){const S=Rr(w.item).title.trim().toLowerCase(),oe=fa(w.item),Pe=lt(w.item),Be=Se(Pe,["event","event_name","eventName"]),Ye=(Be==null?void 0:Be.startsWith("autopilot_"))||(Be==null?void 0:Be.startsWith("auto_continue_")),mt=tr(w.item),ct=oe?`${w.item.type}::sync::${oe}`:Ye&&mt?`autopilot::${mt}::${Math.floor(w.timestampEpoch/3e5)}`:`${w.item.type}::${S}`,je=v.get(ct);je?(je.count+=1,je.firstTimestamp=Math.min(je.firstTimestamp,w.timestampEpoch),je.allItems.push(w),w.timestampEpoch>je.representative.timestampEpoch&&(je.representative=w)):v.set(ct,{key:ct,representative:w,count:1,firstTimestamp:w.timestampEpoch,allItems:[w]})}return{...f,clusters:Array.from(v.values())}}),[an]),Qn=o.useCallback(f=>{q(v=>{const w=new Set(v);return w.has(f)?w.delete(f):w.add(f),w}),re(v=>{if(Object.prototype.hasOwnProperty.call(v,f)){const w={...v};return delete w[f],w}return{...v,[f]:jr}})},[]),Ss=o.useCallback((f,v)=>{re(w=>{const S=w[f]??jr,oe=Math.min(v,S+jr);return oe===S?w:{...w,[f]:oe}})},[]),Jn=o.useCallback(()=>{!j||!b||!_t||!It||It.getTime()<_t.getTime()||(j({startIso:_t.toISOString(),endIso:It.toISOString()}),b("custom"),Le(!1))},[It,_t,j,b]),us=o.useCallback(()=>{Ut(null),on(null),j==null||j({startIso:null,endIso:null}),x==="custom"&&(b==null||b("live"))},[j,b,x]),Yn=o.useMemo(()=>Math.min(sl,Math.min(rl,An)),[An]);o.useEffect(()=>{kt(la),q(new Set),re({})},[Q,p,rn,ye,d,ke,Re,x]),o.useEffect(()=>{if(!Ee)return;const f=w=>{var oe;const S=w.target;S instanceof Node&&((oe=nt.current)!=null&&oe.contains(S)||$(!1))},v=w=>{w.key==="Escape"&&$(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",v),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",v)}},[Ee]),o.useEffect(()=>{if(!rt)return;const f=w=>{var oe;const S=w.target;S instanceof Node&&((oe=Pt.current)!=null&&oe.contains(S)||Le(!1))},v=w=>{w.key==="Escape"&&Le(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",v),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",v)}},[rt]);const Cs=o.useRef(k);Cs.current=k;const Dr=o.useRef(y);Dr.current=y;const Fr=o.useRef(I);Fr.current=I;const[Ws,ln]=o.useState(!1),Zn=o.useRef(null),Pr=o.useRef(x),Or=o.useRef(Date.now()),lr=o.useRef(!1);o.useEffect(()=>{Pr.current!==x&&(Pr.current=x,Zn.current=null,Or.current=Date.now(),lr.current=!1)},[x]),o.useEffect(()=>{const f=Je.current,v=qt.current;if(!f||!v)return;const w=new IntersectionObserver(oe=>{const Pe=oe.some(Be=>Be.isIntersecting);ln(Pe)},{root:f,rootMargin:"0px 0px 600px 0px"});w.observe(v);const S=()=>{lr.current=!0};return f.addEventListener("scroll",S,{passive:!0}),()=>{w.disconnect(),f.removeEventListener("scroll",S)}},[]),o.useEffect(()=>{var f;if(Ws){if(Et.length<Yn){kt(v=>Math.min(Yn,Math.max(v,la)+Bf));return}if(Dr.current&&!Fr.current){(f=Cs.current)==null||f.call(Cs);return}}},[Et.length,Yn,Ws]),o.useEffect(()=>{if(!Ws||y||I||!b)return;const f=Je.current,v=f?f.scrollHeight<=f.clientHeight+4:!1;if(!lr.current&&!v||Date.now()-Or.current<3e3)return;const S=al(x);S&&Zn.current!==S&&(Zn.current=S,b(S))},[Et.length,y,I,b,Ws,x]);const On=o.useMemo(()=>jt?Et.findIndex(f=>f.item.id===jt):-1,[jt,Et]),E=On>=0?Et[On]:null,es=o.useMemo(()=>{var v;const f=new Map;for(const w of a){const S=(v=w==null?void 0:w.sliceRunId)==null?void 0:v.trim();!S||f.has(S)||f.set(S,w)}return f},[a]),Bn=o.useMemo(()=>{if(!E)return null;const f=E.runId??bi(E.item);return f?es.get(f)??null:null},[E,es]),dn=o.useMemo(()=>mc((E==null?void 0:E.item)??null),[E]),Us=o.useMemo(()=>ai((E==null?void 0:E.item)??null),[E]),ms=o.useMemo(()=>uc((E==null?void 0:E.item)??null),[E]),Hs=o.useMemo(()=>ms?null:bh((E==null?void 0:E.item)??null,t),[ms,E,t]),et=o.useMemo(()=>E?ml(E.item):null,[E]),qn=o.useMemo(()=>et?et.executor??et.requester:null,[et]),J=ms??(Hs==null?void 0:Hs.detail)??null,Br=o.useMemo(()=>{var f,v;return pa((J==null?void 0:J.requesterAgentName)??((f=et==null?void 0:et.requester)==null?void 0:f.name)??null,(J==null?void 0:J.requesterAgentId)??((v=et==null?void 0:et.requester)==null?void 0:v.id)??null,fn)},[J,et,fn]),ps=o.useMemo(()=>Vf(Br),[Br]),zn=o.useMemo(()=>{var v,w;const f=pa((J==null?void 0:J.agentName)??((v=et==null?void 0:et.executor)==null?void 0:v.name)??null,(J==null?void 0:J.agentId)??((w=et==null?void 0:et.executor)==null?void 0:w.id)??null,fn);return f==="—"?(et==null?void 0:et.primaryLabel)??"Codex":f},[J,et,fn]),qr=o.useMemo(()=>E!=null&&E.runId?ds.get(E.runId)??null:null,[E,ds]),Vt=o.useMemo(()=>kh(J,qr),[J,qr]),F=o.useMemo(()=>{const f=J;if(!f)return null;const v=f.initiativeId??(E==null?void 0:E.item.initiativeId)??null,w=v?i.find(Kt=>Kt.id===v)??null:null,S=f.initiativeTitle??(w==null?void 0:w.name)??null,oe=f.initiativeStatus??(w==null?void 0:w.status)??null,Pe=(w==null?void 0:w.workstreams)??[],Be=Pe.length>0?Pe.length:null,Ye=Be!==null?Pe.filter(Kt=>$r(Kt.status)).length:null,mt=Be&&Ye!==null?Math.round(Ye/Be*100):null,ct=f.workstreamId??null,je=ct&&Pe.length>0?Pe.find(Kt=>Kt.id===ct)??null:null,ht=f.workstreamTitle??(je==null?void 0:je.name)??(ct?me.get(ct)??null:null),gt=f.workstreamStatus??(je==null?void 0:je.status)??null;return{initiativeId:v,initiativeTitle:S,initiativeStatus:oe,totalInitiativeWorkstreams:Be,doneInitiativeWorkstreams:Ye,initiativeWorkstreamPct:mt,workstreamId:ct,workstreamTitle:ht,workstreamStatus:gt,taskTitle:f.taskTitle,milestoneTitle:f.milestoneTitle,scopedTaskCount:f.taskIds.length,scopedMilestoneCount:f.milestoneIds.length,statusUpdatesApplied:f.statusUpdatesApplied,statusUpdatesBuffered:f.statusUpdatesBuffered,artifacts:f.artifacts,decisions:f.decisions,blockingDecisions:f.blockingDecisions,nonBlockingDecisions:f.nonBlockingDecisions,tokensUsed:f.tokensUsed,tokenBudget:f.tokenBudget,nextStep:f.nextStep,phase:f.phase,stopReason:f.stopReason,parsedStatus:f.parsedStatus}},[J,E,i,me]),Lt=o.useMemo(()=>E?jh(E.item,J,F?{decisions:F.decisions,blockingDecisions:F.blockingDecisions,nonBlockingDecisions:F.nonBlockingDecisions,stopReason:F.stopReason,parsedStatus:F.parsedStatus}:null,E.canonicalProjection??null):null,[J,E,F]),un=o.useMemo(()=>{if(!E)return new Set;if(xe)return new Set(["header","artifact","outcome","structured_outcomes","action_needed","session","scope","summary","evidence"]);const f=Se(lt(E.item),["event","event_name","eventName"])??"";return Ah(f,!!dn||!!ai(E.item),!!Lt)},[E,dn,Lt,xe]),Vs=o.useMemo(()=>{if(!F)return[];const f=[];Lt&&f.push({label:"Status",value:Lt.label}),F.scopedTaskCount>0&&f.push({label:"Tasks",value:F.scopedTaskCount}),F.scopedMilestoneCount>0&&f.push({label:"Milestones",value:F.scopedMilestoneCount});const v=F.artifacts??0;v>0&&f.push({label:"Artifacts",value:v});const w=F.decisions??0;w>0&&f.push({label:"Decisions",value:w}),F.blockingDecisions&&F.blockingDecisions>0&&f.push({label:"Blocking",value:F.blockingDecisions,tone:"critical"}),F.stopReason&&f.push({label:"Stop reason",value:pr(F.stopReason)??at(F.stopReason)});const S=Wc(F.tokensUsed,F.tokenBudget);return S&&f.push({label:"Token usage",value:S}),f},[F,Lt]),fs=o.useMemo(()=>{const f=new Set;for(const v of xh((E==null?void 0:E.item)??null))f.add(v);for(const v of(J==null?void 0:J.decisionIds)??[])f.add(v);for(const v of(J==null?void 0:J.blockingDecisionIds)??[])f.add(v);for(const v of(J==null?void 0:J.nonBlockingDecisionIds)??[])f.add(v);return Array.from(f)},[J,E]),cr=o.useMemo(()=>te?fs.length>0||(E==null?void 0:E.item.decisionRequired)===!0||((F==null?void 0:F.blockingDecisions)??0)>0?!0:(Lt==null?void 0:Lt.label)==="Needs decision":!1,[fs,E,F,Lt,te]),hs=o.useMemo(()=>Vt?Vt.tone==="positive"?T.lime:Vt.tone==="warning"?T.amber:Vt.tone==="critical"?T.red:T.teal:T.teal,[Vt]),dr=(Vt==null?void 0:Vt.terminalStop)===!0,m=o.useMemo(()=>ah(lt((E==null?void 0:E.item)??null)),[E]),A=o.useMemo(()=>lt((E==null?void 0:E.item)??null),[E]),M=o.useMemo(()=>mh((E==null?void 0:E.item)??null,J),[J,E]),_=o.useMemo(()=>{if(!(M!=null&&M.retryAt))return null;const f=new Date(M.retryAt);if(!Number.isFinite(f.getTime()))return null;const v=f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),w=$t(M.retryAt);return w?`${v} (${w})`:v},[M]),Z=o.useMemo(()=>E?sr(E.item):{agentId:null,agentName:null},[E]),Me=o.useMemo(()=>gl(Bs(E==null?void 0:E.item.metadata)??void 0),[E]);o.useMemo(()=>gl(A),[A]);const ot=o.useMemo(()=>{const f=pc((E==null?void 0:E.item)??null);return f.length>0?f:yh((E==null?void 0:E.item)??null,t,new Set)},[E,t]),Fe=o.useMemo(()=>ot.filter((f,v,w)=>w.findIndex(S=>S.path===f.path)===v),[ot]),Ze=o.useMemo(()=>Fe.slice(0,4),[Fe]),yt=o.useMemo(()=>Fe.slice(4),[Fe]),Rt=o.useMemo(()=>{if(Fe.length===0)return null;const f=Fe[0];return f?ma(f.path):null},[Fe]),Ms=o.useMemo(()=>{var S;const f=tn(we);if(f)return f;const v=xl((E==null?void 0:E.item)??null);if(v)return v;const w=tn(E==null?void 0:E.item.summary)??tn(E==null?void 0:E.item.description);if(w)return w;if(E){const oe=E.item,Pe=lt(oe),Be=Se(Pe,["agent_name","agentName"])??oe.agentName??"OrgX",Ye=Se(Pe,["task_title","taskTitle","workstream_title","workstreamTitle"]),mt=((S=oe.type)==null?void 0:S.replace(/_/g," "))??"activity";return Ye?`${Be} worked on ${Ye}`:`${Be} recorded a ${mt}`}return null},[we,E]),Ks=o.useMemo(()=>E?Sr(E.item):!1,[E]),en=o.useMemo(()=>{if(!J||!E)return null;const f=J.initiativeId??E.item.initiativeId??null,v=J.workstreamId??tr(E.item);if(!f||!v)return null;const w=Mn((F==null?void 0:F.parsedStatus)??J.parsedStatus),S=Mn((F==null?void 0:F.stopReason)??J.stopReason),oe=Math.max(0,(F==null?void 0:F.blockingDecisions)??J.blockingDecisions??(E.item.decisionRequired?1:0)),Pe=Math.max(0,(F==null?void 0:F.nonBlockingDecisions)??J.nonBlockingDecisions??0),Be=w==="blocked"||w==="error"||w==="failed"||S==="blocked"||S==="error"||E.item.type==="blocker_created",Ye=!Be&&oe===0&&Pe>0&&(w==="needs_decision"||w==="completed"||S==="completed");return!Be&&!Ye?null:{initiativeId:f,workstreamId:v,runId:E.runId??null,event:J.event,requestedByAgentId:J.requesterAgentId??E.item.requesterAgentId??null,requestedByAgentName:J.requesterAgentName??E.item.requesterAgentName??null,actionLabel:Be?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Be?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Be}},[J,E,F]),Sn=o.useCallback(()=>{Nt(null)},[]),Li=o.useCallback(async(f,v)=>{if(v){ze(null),Ue(f);try{await v()}catch(w){ze(w instanceof Error?w.message:"Action failed")}finally{Ue(w=>w===f?null:w)}}},[]),zr=o.useCallback(async()=>{var f;if(!(!en||qe)){Oe(!0),Ft(null);try{const v=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:en.initiativeId,workstreamId:en.workstreamId,runId:en.runId,event:en.event,requestedByAgentId:en.requestedByAgentId,requestedByAgentName:en.requestedByAgentName,graceMs:1e4})}),w=await v.json().catch(()=>null);if(!v.ok||(w==null?void 0:w.ok)!==!0)throw new Error((w==null?void 0:w.error)||`Request failed (${v.status})`);const S=(f=w==null?void 0:w.scheduled)!=null&&f.dueAt?new Date(w.scheduled.dueAt):null,oe=S&&Number.isFinite(S.getTime())?S.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Ft(oe?`Scheduled. Auto action starts by ${oe} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(v){const w=v instanceof Error?v.message:"Failed to schedule auto-fix";Ft(Wt(w)||w)}finally{Oe(!1)}}},[en,qe]);o.useEffect(()=>{if(!O)return;const f=window.setTimeout(()=>_e(null),2e3);return()=>window.clearTimeout(f)},[O]),o.useEffect(()=>{ze(null)},[Q,ye,x]),o.useEffect(()=>{if(!z){Mt.current=null;return}const f=z.trim();!f||Mt.current===f||!t.some(w=>w.id===f)||(Mt.current=f,ge("all"),he(""),tt(1),Nt(f),Ie==null||Ie(f))},[t,Ie,z]);const gn=o.useCallback(async(f,v)=>{if(v)try{await navigator.clipboard.writeText(v),_e(`${f} copied`)}catch{_e("Copy failed")}},[]);o.useEffect(()=>{We("structured"),Te(!1),Oe(!1),Ft(null)},[jt]),o.useEffect(()=>{X(null),He("feed");const f=Ch((E==null?void 0:E.item)??null);if(!f||Gt())return;const v=new URLSearchParams({turnId:f.turnId});f.sessionKey&&v.set("sessionKey",f.sessionKey),f.runId&&v.set("run",f.runId);const w=new AbortController;return fetch(`/orgx/api/live/activity/detail?${v.toString()}`,{method:"GET",signal:w.signal}).then(async S=>{var Pe;return S.ok?((Pe=(await S.json()).detail)==null?void 0:Pe.summary)??null:(S.status===404&&He("missing"),null)}).then(S=>{typeof S=="string"&&S.trim().length>0?(X(S),He("local")):He("missing")}).catch(S=>{S instanceof DOMException&&S.name==="AbortError"||He("missing")}),()=>w.abort()},[E]),o.useEffect(()=>{st(null),Ct(null);const f=E==null?void 0:E.item;if(!f||Dt)return;const v=(we??f.summary??f.description??f.title??"").trim();if(!v||Gt())return;const w=new AbortController;return fetch("/orgx/api/live/activity/headline",{method:"POST",headers:{"Content-Type":"application/json"},signal:w.signal,body:JSON.stringify({text:v,title:f.title??null,type:f.type})}).then(async S=>S.ok?await S.json():((S.status===404||S.status===405)&&W(!0),null)).then(S=>{const oe=S==null?void 0:S.headline;typeof oe=="string"&&oe.trim().length>0&&(W(!1),st(oe.trim()),Ct((S==null?void 0:S.source)??null))}).catch(S=>{S instanceof DOMException&&S.name}),()=>w.abort()},[E,we,Dt]);const Wn=o.useCallback(f=>{var S;if(Et.length===0)return;const w=((On>=0?On:0)+f+Et.length)%Et.length;tt(f),Nt(((S=Et[w])==null?void 0:S.item.id)??null)},[On,Et]);o.useEffect(()=>{jt&&(On>=0||Nt(null))},[On,jt]),o.useEffect(()=>{if(!jt)return;const f=v=>{v.key==="ArrowRight"||v.key.toLowerCase()==="l"?(v.preventDefault(),Wn(1)):(v.key==="ArrowLeft"||v.key.toLowerCase()==="h")&&(v.preventDefault(),Wn(-1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[jt,Wn]);const gs=zt.size===1,$i=gs?[...zt][0]:null,xc=$i?s.find(f=>f.runId===$i||f.id===$i)??null:null,Di=o.useMemo(()=>{if(!gs)return[];const f=[],v=new Set;for(const w of Ce){if(!w.runId||!zt.has(w.runId))continue;const S=fa(w.item);if(S){if(v.has(S)||(v.add(S),!ke))continue}else if(!ke&&Sr(w.item))continue;f.push(w.item)}return f},[gs,Ce,zt,ke]),Ua=!U&&Et.length<=160,Gs=(f,v,w)=>{const S=f.item,oe=w??S.id,Pe=sr(S),Be=ml(S),Ye=Qf(S,Be),mt=Be.executor??Be.requester,ct=pa(pn((mt==null?void 0:mt.name)??Be.primaryLabel??S.agentName??Pe.agentName??null),pn((mt==null?void 0:mt.id)??S.agentId??Pe.agentId??null),fn)||"OrgX";let je=Yf(Ye)||ct;if(Ye==="agent"&&ct){const Ja=Er(ct);Ja&&(je=`${ct} (${Ja})`)}const ht=ua(f.userState),gt=Ye==="agent"?Da(ct)||ht:Jf[Ye]||ht,Kt=Re==="newest"&&v<2,mn=f.runId,En=xl(S),{title:Fi}=Rr(S),Pi=En??tn(S.summary),Oi=tn(S.description),Va=bl(S,Pi??Oi??null),Ka=lt(S),Ga=ci([{value:Se(Ka,["initiative_title","initiativeTitle"]),idHint:S.initiativeId},{value:S.initiativeId?de.get(S.initiativeId)??null:null,idHint:S.initiativeId}]),xs=tr(S)??(mn?Fn.get(mn)??null:null),Xa=ci([{value:Se(Ka,["workstream_title","workstreamTitle"]),idHint:xs},{value:xs?me.get(xs)??null:null,idHint:xs},{value:mn?D.get(mn)??null:null,idHint:xs}]),yc=[Ga,Xa].filter(Boolean).join(" > "),ur=xs?H.get(xs):void 0,bc=(R==null?void 0:R.state)==="running"&&xs===(R==null?void 0:R.activeWorkstreamId),wc=ur?` — #${ur.rank} in queue`:"",vc=(yc||Ga||Xa||at(S.type))+(bc?wc:""),kc=da(f.userState),jc=new Date(S.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Nc=$t(S.timestamp),Ic=f.bucket==="artifact"?lh(S):null,Qa=ch(S);return n.jsx(ff,{renderKey:oe,displayTitle:Fi,headline:Va,contextLabel:vc,detailText:(Pi??Oi)!==Va?Pi??Oi:null,displayAgentName:je,railColor:gt,statusColor:ht,userStateLabel:kc,userStateWhy:f.userStateWhy,relativeTime:Nc,timeLabel:jc,isRecent:Kt,enableMotion:Ua,onOpen:()=>{tt(1),Nt(S.id)},ariaLabel:`Open activity details for ${Fi||Si(S.type)}`,artifactSnippet:Ic,evidenceChips:Qa.length>0?Qa:void 0,actorCategory:Ye,queuePosition:ur?{rank:ur.rank,state:ur.state}:null},oe)};return n.jsx(Cf,{sessions:s,initiatives:i??[],workspaceId:Ke??null,query:ye,statusFilter:Q,sortOrder:Re,timeFilterId:x,customTimeRange:g,snapshot:pe,onRequestRefresh:ae,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[gs&&Di.length>0?n.jsx(df,{items:Di,session:xc,agentName:((Ha=Di[0])==null?void 0:Ha.agentName)??null,onBack:N,onOpenItem:f=>{tt(1),Nt(f.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:An}),_n>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:["+",_n," hidden"]}),_s>0&&!ke&&n.jsxs("button",{type:"button",onClick:()=>se(!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:[_s," sync hidden"]}),ke&&n.jsx("button",{type:"button",onClick:()=>se(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-[#E1FFB2] transition-colors hover:bg-lime/[0.16] sm:inline-flex",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsx("span",{className:le("h-1.5 w-1.5 flex-shrink-0 rounded-full",ft&&"pulse-soft"),style:{backgroundColor:T.lime},"aria-label":"Live",title:ft?"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:ye,onChange:f=>he(f.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-[#BFFF00]/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:Pt,children:[n.jsxs("button",{type:"button",onClick:()=>{Le(f=>!f),$(!1)},"aria-haspopup":"menu","aria-expanded":rt,className:le("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",rt?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"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:As}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:le("transition-transform duration-200",rt&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(vt,{children:rt&&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:Mr.filter(f=>f.id!=="custom").map(f=>{const v=x===f.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(f.id),Le(!1)},className:le("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.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"}),as?n.jsx("input",{type:"datetime-local",step:300,value:ca(_t),onChange:f=>Ut(cl(f.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(Ya,{selected:_t,onChange:f=>Ut(f instanceof Date?f:null),selectsStart:!0,startDate:_t,endDate:It,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"}),as?n.jsx("input",{type:"datetime-local",step:300,min:ca(_t),value:ca(It),onChange:f=>on(cl(f.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(Ya,{selected:It,onChange:f=>on(f instanceof Date?f:null),selectsEnd:!0,minDate:_t??void 0,startDate:_t,endDate:It,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:Nn?`${ii(_t)} - ${ii(It)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:us,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:Jn,disabled:!Nn,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-[#E1FFB2] 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:[(rn||d||p)&&n.jsxs(n.Fragment,{children:[rn&&n.jsxs("button",{onClick:N,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[ll(Tt.id)?n.jsx(ir,{provider:Tt.id,size:"xs"}):n.jsx(Xt,{name:(St==null?void 0:St.agentName)??"OrgX",hint:l??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",l?`: ${l}`:""]}),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:h,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),p&&n.jsxs("button",{onClick:C,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(In.id)?n.jsx(ir,{provider:In.id,size:"xs"}):n.jsx(Xt,{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(si).map(f=>{const v=Q===f;return n.jsx("button",{type:"button",onClick:()=>ge(f),"aria-pressed":v,className:le("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",v?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:si[f]},f)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:nt,children:[n.jsxs("button",{type:"button",onClick:()=>{$(f=>!f),Le(!1)},"aria-haspopup":"menu","aria-expanded":Ee,"aria-label":"Activity filters",title:"Activity filters",className:le("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Ee?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"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:le("transition-transform duration-200",Ee&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(vt,{children:Ee&&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(f=>n.jsx("button",{type:"button",onClick:()=>{Ge(f.id),$(!1)},className:le("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",Re===f.id?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.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(si).map(f=>{const v=Q===f;return n.jsx("button",{type:"button",onClick:()=>{ge(f),$(!1)},className:le("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:si[f]},f)})})]}),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:()=>{se(f=>!f)},className:le("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",ke?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:ke?"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:Je,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[Et.length===0&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-4 py-5",children:n.jsxs("div",{className:"mx-auto max-w-2xl",children:[n.jsx(Ri,{icon:"activity",headline:ne?"Syncing activity feed...":rn?"No activity yet for this session":d?"No activity yet for this workstream":p?`No recent activity from ${p}`:Q!=="all"?`No matches for this filter. ${An>0?`${An} events in other categories.`:""}`:K&&K.length>0?`Waiting for autopilot to start. Queue has ${K.length} item${K.length===1?"":"s"} ready.`:"No activity yet",description:ne?"Live updates usually appear within a few seconds after dispatch.":Q!=="all"?'Try selecting "All" to see every event.':p?`Try widening the time window or select a different agent.${hn?` Last active: ${hn}.`:""}`:`Try widening the time window (${As}), 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:Pn.map(f=>{const v=x===f.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(f.id),className:le("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:f.label},`empty-time-${f.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[p&&n.jsx("button",{type:"button",onClick:()=>{C==null||C(),b==null||b("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"}),(rn||d||Q!=="all")&&n.jsx("button",{type:"button",onClick:()=>{rn&&N(),d&&(h==null||h()),p&&(C==null||C()),Q!=="all"&&ge("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"}),B&&n.jsx("button",{type:"button",onClick:()=>void Li("play",B),disabled:Ne!==null,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18 disabled:opacity-45",children:Ne==="play"?"Starting...":"Start next session"}),!B&&Ae&&n.jsx("button",{type:"button",onClick:Ae,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),Ve&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Ve})]})}),n.jsx(uf,{completedCount:sn.completed,decisionsCount:sn.decisions,blockerCount:sn.blocked,visible:pt,onDismiss:()=>{bt(!1),At.current=Date.now()}}),Et.length>0&&n.jsxs("div",{className:"space-y-4",children:[Xn.map(f=>{const v=f.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:f.label}),Ua?n.jsx(vt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:v.map((w,S)=>{const oe=L.has(w.key),Pe=w.allItems.slice(1),Be=Pe.length,Ye=Math.min(Be,G[w.key]??jr),mt=Pe.slice(0,Ye);if(w.count===1)return Gs(w.representative,S);if(w.key.startsWith("autopilot::")&&w.count>=3){const je=hl(w);return n.jsx(nl,{workstreamTitle:je.workstreamTitle,items:je.items,firstTimestamp:w.firstTimestamp,lastTimestamp:w.representative.timestampEpoch,onExpandItem:ht=>{const gt=w.allItems[ht];gt&&Nt(gt.item.id)}},w.key)}const ct=`cluster:${w.key}`;return n.jsxs("div",{children:[Gs(w.representative,S,ct),n.jsxs("button",{type:"button",onClick:je=>{je.stopPropagation(),Qn(w.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:["×",w.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:oe?"hide":`and ${w.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:le("transition-transform",oe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),oe&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[mt.map((je,ht)=>Gs(je,S+ht+1)),Ye<Be&&n.jsxs("button",{type:"button",onClick:je=>{je.stopPropagation(),Ss(w.key,Be)},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 (",Be-Ye," remaining)"]})]})]},w.key)})})}):n.jsx("div",{className:"space-y-2",children:v.map((w,S)=>{const oe=L.has(w.key),Pe=w.allItems.slice(1),Be=Pe.length,Ye=Math.min(Be,G[w.key]??jr),mt=Pe.slice(0,Ye);if(w.count===1)return Gs(w.representative,S);if(w.key.startsWith("autopilot::")&&w.count>=3){const je=hl(w);return n.jsx(nl,{workstreamTitle:je.workstreamTitle,items:je.items,firstTimestamp:w.firstTimestamp,lastTimestamp:w.representative.timestampEpoch,onExpandItem:ht=>{const gt=w.allItems[ht];gt&&Nt(gt.item.id)}},w.key)}const ct=`cluster:${w.key}`;return n.jsxs("div",{children:[Gs(w.representative,S,ct),n.jsxs("button",{type:"button",onClick:je=>{je.stopPropagation(),Qn(w.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:["×",w.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:oe?"hide":`and ${w.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:le("transition-transform",oe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),oe&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[mt.map((je,ht)=>Gs(je,S+ht+1)),Ye<Be&&n.jsxs("button",{type:"button",onClick:je=>{je.stopPropagation(),Ss(w.key,Be)},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 (",Be-Ye," remaining)"]})]})]},w.key)})})]},f.key)}),n.jsx("div",{ref:qt,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:le("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",I?"opacity-100":y?"opacity-0":"opacity-0 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-[#BFFF00]/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!y&&!I&&Et.length>0&&!al(x)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:_n>0?`${Et.length} of ${An} events`:"Beginning of activity history"})]})]})]}),xe?n.jsx(Of,{}):null,n.jsx(hf,{open:E!==null,onClose:Sn,children:E&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:ua(E.userState),boxShadow:`0 0 12px ${ua(E.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[da(E.userState)," · ",On+1,"/",Et.length," sessions"]}),O&&n.jsx(Rn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:O})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[E.runId&&V&&n.jsx("button",{type:"button",onClick:()=>{V(E.runId),Sn()},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:()=>Wn(-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:()=>Wn(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:()=>Te(f=>!f),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"})]})}),fe&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Te(!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:[E.runId&&n.jsx("button",{type:"button",onClick:()=>{gn("Run id",E.runId??""),Te(!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"}),Z.agentId&&n.jsx("button",{type:"button",onClick:()=>{gn("Agent id",Z.agentId??""),Te(!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:()=>{gn("Event id",E.item.id),Te(!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:Sn,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(vt,{mode:"wait",custom:Qe,children:n.jsx(ce.section,{custom:Qe,initial:{opacity:0,x:Qe*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:Qe*-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:De||bl(E.item,we)||at(E.item.title||Si(E.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(E.item.timestamp).toLocaleString()," · ",$t(E.item.timestamp),dt==="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 f=lt(E.item),v=(J==null?void 0:J.workstreamId)??tr(E.item)??(E.runId?Fn.get(E.runId)??null:null),w=ci([{value:(J==null?void 0:J.workstreamTitle)??null,idHint:v},{value:Se(f,["workstream_title","workstreamTitle"]),idHint:v},{value:v?me.get(v)??null:null,idHint:v},{value:E.runId?D.get(E.runId)??null:null,idHint:v}]),oe=[ci([{value:(J==null?void 0:J.initiativeTitle)??null,idHint:E.item.initiativeId},{value:Se(f,["initiative_title","initiativeTitle"]),idHint:E.item.initiativeId},{value:E.item.initiativeId?de.get(E.item.initiativeId)??null:null,idHint:E.item.initiativeId}]),w].filter(Boolean).join(" > ");return oe?n.jsx(Rn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:oe})}):null})(),n.jsx(Rn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:da(E.userState)}),n.jsxs(Rn,{tone:"muted",children:[n.jsx(Xt,{name:(qn==null?void 0:qn.label)??(et==null?void 0:et.primaryLabel)??"OrgX",hint:qn?pl(qn):(et==null?void 0:et.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(qn==null?void 0:qn.label)??(et==null?void 0:et.primaryLabel)??"OrgX"})]}),Ks&&n.jsx(Rn,{tone:"lime",children:"Sync replay"})]})]}),un.has("artifact")&&E&&ai(E.item)&&!dn&&n.jsxs("button",{type:"button",onClick:()=>{const f=ai(E.item);f&&P(f)},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:T.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:T.cyan},children:"View registered artifact"})]}),n.jsx(yf,{item:E.item}),un.has("artifact")&&dn&&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:dn.source==="metadata"?"Artifact":at(dn.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[xe&&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:()=>We("structured"),"aria-pressed":Y==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${Y==="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:()=>We("json"),"aria-pressed":Y==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${Y==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Us&&n.jsx("button",{type:"button",onClick:()=>P(Us),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:Y==="structured"?hc(dn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(dn.value,null,2)})})})]}),un.has("outcome")&&Lt&&n.jsxs("div",{className:le("rounded-xl border px-3.5 py-3",Lt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Lt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Lt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Lt.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:Lt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Lt.summary}),Lt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Lt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[E.runId&&V&&n.jsx("button",{type:"button",onClick:()=>{V(E.runId),Sn()},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"}),cr&&n.jsx("button",{type:"button",onClick:()=>{te==null||te(fs[0]??null),Sn()},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:fs.length>0?"Resolve decision":"Resolve decisions"}),Us&&!dn&&n.jsx("button",{type:"button",onClick:()=>P(Us),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"}),Rt&&n.jsx("a",{href:Rt,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"}),en&&n.jsx("button",{type:"button",onClick:()=>void zr(),disabled:qe,className:le("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",en.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-[#D8FFA1] hover:bg-lime/[0.18]"),children:qe?"Scheduling...":en.actionLabel})]}),en&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:ut??en.helperText})]}),(()=>{if(!un.has("structured_outcomes"))return null;const f=lt(E.item),v=f==null?void 0:f.outcomes,w=f==null?void 0:f.task_updates;if(!v&&(!w||w.length===0))return null;const S=v==null?void 0:v.pr_url,oe=v==null?void 0:v.pr_number,Pe=v==null?void 0:v.commit_sha,Be=v==null?void 0:v.commit_url,Ye=v==null?void 0:v.tests;return S||Pe||Ye||w&&w.length>0?n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-muted",children:"Outcomes"}),S&&n.jsxs("a",{href:S,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:oe?`#${oe}`:"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"})})]}),Pe&&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:Pe.slice(0,7)})]}),Be&&n.jsx("a",{href:Be,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?T.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?T.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"]})]})]})]}),w&&w.length>0&&n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/15 bg-[#14B8A6]/[0.04] 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-[#14B8A6]/70",children:"Task Updates"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[w.length," task",w.length!==1?"s":""," updated"]})]})]}),w.length<=5&&n.jsx("ul",{className:"mt-2 space-y-1 pl-5",children:w.map((ct,je)=>n.jsxs("li",{className:"text-caption text-secondary",children:[ct.title?`"${ct.title}"`:"Task",ct.status?` → ${at(ct.status)}`:""]},je))})]})]}):null})(),M&&!xe&&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."}),M.retryInMs!==null&&n.jsxs("p",{className:"mt-1 text-micro text-muted",children:["Retrying in ~",Math.max(1,Math.round(M.retryInMs/1e3)),"s"]})]}),M&&xe&&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(Rn,{tone:M.isRateLimited?"muted":"red",children:M.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:M.domainCurrent!==null&&M.domainMax!==null?`${M.domainCurrent}/${M.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:M.totalCurrent!==null&&M.totalMax!==null?`${M.totalCurrent}/${M.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[M.domain&&n.jsxs(Rn,{tone:"muted",children:["Domain: ",at(M.domain)]}),M.modelTier&&n.jsxs(Rn,{tone:"muted",children:["Tier: ",at(M.modelTier)]}),_&&n.jsxs(Rn,{tone:"muted",children:["Retry: ",_]}),!_&&M.retryInMs!==null&&n.jsxs(Rn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(M.retryInMs/1e3)),"s"]})]}),M.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:tn(M.blockedReason)??M.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ue&&n.jsx("button",{type:"button",onClick:ue,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"}),en&&n.jsx("button",{type:"button",onClick:()=>void zr(),disabled:qe,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-[#D8FFA1] transition hover:bg-lime/[0.18] disabled:opacity-50",children:qe?"Scheduling...":"Retry now"})]})]}),Vs.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:Vs.map(f=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:f.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${f.tone==="critical"?"text-red-300":"text-primary"}`,children:f.value})]},f.label))})]}),et&&!J&&et.mode!=="system"&&n.jsxs("div",{className:"flex items-center gap-2 text-body text-secondary",children:[et.executor&&n.jsxs(n.Fragment,{children:[n.jsx(Xt,{name:et.executor.label,hint:pl(et.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:et.executor.label}),(()=>{const f=Er(et.executor.label);return f?n.jsxs("span",{className:"text-caption text-muted",children:["(",f,")"]}):null})()]}),et.mode==="handoff"&&et.requester&&n.jsxs("span",{className:"text-caption text-muted",children:["requested by ",et.requester.label]})]}),J&&n.jsxs("div",{className:"space-y-5",children:[un.has("action_needed")&&(F==null?void 0:F.nextStep)&&((Vt==null?void 0:Vt.tone)==="critical"||(Vt==null?void 0:Vt.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})]}),n.jsx("div",{children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Session"}),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:pr(J.event)??at(J.event)})]})}),(()=>{if(!un.has("session"))return null;const f=lt(E.item),v=Se(f,["parsed_status","status"]),w=["Queued","Dispatched","Running","Completed"],S={queued:"Queued",dispatched:"Dispatched",running:"Running",completed:"Completed",success:"Completed",blocked:"Running",needs_decision:"Running",needs_attention:"Running",failed:"Running"},oe=S[v??""]??S[J.event??""]??null;if(!oe)return null;const Pe=w.indexOf(oe),Be=v==="completed"||v==="success",Ye=bi(E.item),mt=Ye?Jt.get(Ye):null,ct=mt!=null&&mt.startedAt?new Date(mt.startedAt).getTime():null,je=mt!=null&&mt.completedAt?new Date(mt.completedAt).getTime():Be?null:Date.now();let ht=null;if(ct&&je){const gt=je-ct;ht=gt<6e4?`${Math.round(gt/1e3)}s`:`${Math.floor(gt/6e4)}m ${Math.round(gt%6e4/1e3)}s`}else if(ct&&!Be){const gt=Date.now()-ct;ht=gt<6e4?`${Math.round(gt/1e3)}s`:`${Math.floor(gt/6e4)}m ${Math.round(gt%6e4/1e3)}s`}return n.jsxs("div",{className:"flex items-center gap-1 px-1",children:[w.map((gt,Kt)=>{const mn=Kt<Pe||Kt===Pe&&Be,En=Kt===Pe&&!Be;return n.jsxs("div",{className:"flex items-center gap-1",children:[Kt>0&&n.jsx("div",{className:"h-[1.5px] w-4",style:{backgroundColor:mn||En?T.lime:"rgba(255,255,255,0.12)"}}),n.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[n.jsx("span",{className:le("h-2 w-2 rounded-full",En&&"animate-pulse"),style:{backgroundColor:mn||En?T.lime:"rgba(255,255,255,0.15)"}}),n.jsxs("span",{className:le("text-[9px] tracking-wider",mn||En?"text-primary":"text-muted/50"),children:[gt,mn&&Kt===w.length-1&&" ✓"]})]})]},gt)}),ht&&n.jsx("span",{className:"ml-2 text-micro text-muted",children:ht})]})})(),Vt&&n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:dr?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:hs},children:dr?(Lt==null?void 0:Lt.label)??"Stopped":`${Vt.pct}%`})]}),n.jsx("div",{className:"mt-1.5 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,Vt.pct)}%`,backgroundColor:hs}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:Vt.label})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),ps.primary!==zn?n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Xt,{name:ps.primary,hint:ps.secondary??ps.primary,size:"xs"}),n.jsx("span",{children:ps.primary}),n.jsx("span",{className:"text-white/[0.2]",children:"→"}),n.jsx(Xt,{name:zn,hint:zn,size:"xs"}),n.jsx("span",{children:zn}),J.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",at(J.domain),")"]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Xt,{name:zn,hint:zn,size:"xs"}),n.jsx("span",{children:zn}),J.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",at(J.domain),")"]})]}),xe&&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:ps.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:zn})]}),J.dispatcherClient&&J.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:at(J.dispatcherClient)})]}),(J.domain||J.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:[J.domain??"",J.requiredSkills.length>0?`${J.domain?" · ":""}${J.requiredSkills.join(", ")}`:""]})]})]})]}),un.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?ws(F.initiativeId):"—")})]}),F.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:at(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??ws(F.workstreamId)})]}),F.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:at(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-[#BFFF00]/80",style:{width:`${Math.max(4,F.initiativeWorkstreamPct)}%`}})})]})]}),((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:pr(F.phase)??at(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:pr(F.parsedStatus)??at(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:pr(F.stopReason)??at(F.stopReason)})]})]})]}),J.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:J.error})]}),un.has("summary")&&Ms&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),$e==="missing"&&!Ks&&xe&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(_r,{mode:"block",text:Ms,className:"text-body leading-relaxed text-primary"})]}),tn(E.item.description)&&tn(E.item.description)!==Ms&&(()=>{const f=tn(E.item.description)??"";return f.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(_r,{mode:"block",text:f,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(_r,{mode:"block",text:f,className:"text-body leading-relaxed text-secondary"})]})})(),Bn&&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:Bn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:Bn.dispatch})]}),Bn.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:Bn.highlights.slice(0,3).map((f,v)=>n.jsx("li",{children:f},`${Bn.sliceRunId}:highlight:${v}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:Bn.outcome.summary})]})]})]}),(()=>{if(!un.has("evidence"))return null;const f=lt(E.item),v=f==null?void 0:f.blocker,w=f==null?void 0:f.decisions_needed,S=f==null?void 0:f.outcomes,oe=f==null?void 0:f.task_updates,Pe=!!(S!=null&&S.pr_url||S!=null&&S.commit_sha||S!=null&&S.tests||oe&&oe.length>0),Be=!!(v||w&&w.length>0),Ye=Pe||Be,mt=Be,ct=Fe.length>0;return!mt&&!ct?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:[v&&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:v.description??"Blocked"}),v.waiting_on&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Waiting on: ",v.waiting_on]})]})]}),cr&&n.jsx("div",{className:"mt-2 flex gap-2",children:n.jsx("button",{type:"button",onClick:()=>{te==null||te(fs[0]??null),Sn()},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:"Resolve decision"})})]}),w&&w.length>0&&n.jsx("div",{className:"space-y-1.5",children:w.map((je,ht)=>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??"Pending decision"})]}),je.id&&te&&n.jsx("button",{type:"button",onClick:()=>{te(je.id),Sn()},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??ht))}),ct&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",open:!Ye,children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary select-none",children:[Fe.length," evidence file",Fe.length===1?"":"s"]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[Ze.map((je,ht)=>{const gt=ma(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:at(je.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Ds(je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[gt&&n.jsx("a",{href:gt,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 gn(`${at(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}:${ht}`)}),yt.length>0&&yt.map((je,ht)=>{const gt=ma(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:at(je.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Ds(je.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[gt&&n.jsx("a",{href:gt,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 gn(`${at(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:${ht}`)})]})]})]})]})})(),xe&&(m||(J==null?void 0:J.logPath)||Me)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),xe&&(m||(J==null?void 0:J.logPath)||(J==null?void 0:J.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:[m&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[m.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:at(m.domain)})]}),(m.provider||m.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:[m.provider?`${at(m.provider)} · `:"",m.model?Cr(m.model):"—"]})]}),m.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:at(m.modelTier)})]}),m.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",m.pluginVersion]})]})]}),(m==null?void 0:m.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:[m.skillPack.name??"—",m.skillPack.version?`@${m.skillPack.version}`:"",m.skillPack.source?` · ${m.skillPack.source}`:""]}),m.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var f;return void gn("Skill pack checksum",((f=m.skillPack)==null?void 0:f.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 ",m.skillPack.checksum.slice(0,12)]})]}),m&&m.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"}),m.requiredSkills.map(f=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:f},f))]}),(m==null?void 0:m.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:[m.kickoffContextSource?`${m.kickoffContextSource} · `:"",m.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void gn("Kickoff context hash",m.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"})]}),((J==null?void 0:J.logPath)||(J==null?void 0:J.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(J==null?void 0:J.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: ",Ds(J.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void gn("Log path",(J==null?void 0:J.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"})]}),(J==null?void 0:J.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: ",Ds(J.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void gn("Output path",(J==null?void 0:J.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: ",ws(F.initiativeId)]}),(F==null?void 0:F.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",ws(F.workstreamId)]})]})]})]}),xe&&Me&&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:Me})]})]})},E.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"})]})})]})})}),Eh=o.lazy(async()=>({default:(await nn(()=>import("./CSDhTbKy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),Rh=o.lazy(async()=>({default:(await nn(()=>import("./C-XuWXGi.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),Lh=o.lazy(async()=>({default:(await nn(()=>import("./CReugbyT.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),$h=o.lazy(()=>nn(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),Dh=o.lazy(()=>nn(()=>import("./C-MOJWHs.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),Fh=o.lazy(async()=>({default:(await nn(()=>import("./BEnI6kNR.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),Ph=o.lazy(async()=>({default:(await nn(()=>import("./CfMS9yIf.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),Oh=o.lazy(async()=>({default:(await nn(()=>import("./DS79hzMu.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),Bh=o.lazy(async()=>({default:(await nn(()=>import("./C9-UYhBb.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),qh=o.lazy(async()=>({default:(await nn(()=>import("./C3_j_W9V.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),zh=o.lazy(async()=>({default:(await nn(()=>import("./sdoPH_Z1.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Wh=o.lazy(async()=>({default:(await nn(()=>import("./qDJ6rqcs.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),Uh=o.lazy(async()=>({default:(await nn(()=>import("./C9yV06GS.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),Hh=o.lazy(async()=>({default:(await nn(()=>import("./B71dt9yu.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),wl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},Vh={connected:T.lime,reconnecting:T.amber,disconnected:T.red},ha="orgx.demo_mode",ga="orgx.dev_mode",xa="orgx.show_synthetic_entities",Ca="orgx.selected_workspace_id",vl={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},kl=new Set(["running","active","queued","pending","in_progress","working","planning"]),Kh=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function kn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Gh(e){const t=kn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Xh(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),i=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return i.length<=t?i:`${i.slice(0,t-1).trimEnd()}…`}function Qh(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=Wt(e);return{title:"Live stream degraded",message:Xh(s),action:"settings"}}function ya(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 r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function Jh(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,r=["sliceRunId","slice_run_id","sliceId","slice_id","sliceRun","slice_run"];for(const i of r){const a=s[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function jl(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Nl(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function ba(e,t){const s=vl[e.status]??99,r=vl[t.status]??99;return s!==r?s-r:kn(e.updatedAt??e.lastEventAt??e.startedAt)-kn(t.updatedAt??t.lastEventAt??t.startedAt)}function Il(e){return!Array.isArray(e)||e.length===0?null:e.find(t=>t.queueState!=="blocked"&&t.queueState!=="running")??e.find(t=>t.queueState!=="blocked")??null}function Yh(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 Zh(e){if(zs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function eg(e){if(zs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function tg(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function ng(e){return Kh.test(e)}function di(e,t){for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function sg(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function rg(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function ig(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 ag(e,t){Ns(e,t)}function og(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 lg(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=ig(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Ca);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function cg(){const e=Zd();return e.showGate?n.jsx(Xu,{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(Ym,{children:n.jsx(fg,{onboarding:e})})}function dg(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 ug(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 Al(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 _l(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function mg(){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:Ti,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function pg(){const{state:e}=Jl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Wh,{})}):null}function fg({onboarding:e}){const[t,s]=o.useState(()=>{if(typeof window>"u")return!1;if(new URLSearchParams(window.location.search).get("demo")==="1")return!0;try{return window.localStorage.getItem(ha)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(xa)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ga)==="1"}catch{return!1}}),[l,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,p]=o.useState(()=>lg()),x=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:b=[]}=qs({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const m=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!m.ok)return[];const A=await m.json().catch(()=>null),M=Array.isArray(A==null?void 0:A.data)?A.data:[],_=[];for(const Z of M){if(!Z||typeof Z!="object"||Array.isArray(Z))continue;const Me=di(Z,["id"]);if(!Me)continue;const ot=di(Z,["status","priority"]);if(!sg(ot))continue;const Fe=di(Z,["title","name"])??(Me.length>10?`${Me.slice(0,8)}…`:Me),Ze=Z.is_default===!0,yt=rg({title:Fe,isDefault:Ze}),Rt=di(Z,["created_at"]);_.push({id:Me,title:yt,status:ot,isDefault:Ze,createdAt:Rt})}return _.sort((Z,Me)=>{if(Z.isDefault!==Me.isDefault)return Z.isDefault?-1:1;const ot=kn(Z.createdAt)-kn(Me.createdAt);return ot!==0?ot:Z.title.localeCompare(Me.title)}),_},staleTime:6e4}),g=o.useMemo(()=>{var m;return u?((m=b.find(A=>A.id===u))==null?void 0:m.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),j=o.useMemo(()=>!u||b.some(m=>m.id===u)?b:[{id:u,title:g,status:null,isDefault:!1,createdAt:null},...b],[u,g,b]);o.useEffect(()=>{u&&b.length!==0&&(b.some(m=>m.id===u)||p(null))},[u,b]),t||e.state.hasApiKey&&e.state.connectionVerified;const y=o.useMemo(()=>l==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[l]),{data:I,isLoading:k,error:N,refetch:h,approveDecision:C,rejectDecision:V,approveAllDecisions:te,bulkDecisionAction:z,decisionMutation:Ie}=_d({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),B=t||r,ee=o.useMemo(()=>B?I.sessions.nodes:I.sessions.nodes.filter(m=>!Zh(m)),[I.sessions.nodes,B]),be=o.useMemo(()=>I.activity.filter(m=>!(!B&&eg(m)||!a&&tg(m))),[I.activity,B,a]),ve=I.connection==="connected"||I.decisions.length>0,[Ae,ue]=o.useState(null),[Ke,pe]=o.useState(!1),[ae,ne]=o.useState(null),[ie,xe]=o.useState(null),[K,R]=o.useState(null),[U,P]=o.useState(null),[H,Q]=o.useState("24h"),[ge,ke]=o.useState({startIso:null,endIso:null}),se=o.useRef(new Set),[ye,he]=o.useState(null),[L,q]=o.useState(null),[G,re]=o.useState(null),[Re,Ge]=o.useState(null),Ee=o.useRef(null),$=o.useCallback(m=>{Ee.current&&clearTimeout(Ee.current),Ge(m),Ee.current=setTimeout(()=>Ge(null),4e3)},[]),[rt,Le]=o.useState(!1),[Xe,kt]=o.useState(!1),[jt,Nt]=o.useState([]),O=o.useRef(null),_e=o.useRef(null),[fe,Te]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[Qe,tt]=o.useState(!1),[Y,We]=o.useState(null),[we,X]=o.useState("activity"),[$e,He]=o.useState("initiatives"),[De,st]=o.useState("next_up"),dt=o.useCallback(m=>{if(X(m),m==="initiatives"){He("initiatives"),st("next_up");return}m==="decisions"&&(He("initiatives"),st("in_progress"),Dt("needs_attention"))},[]),[Ct,Dt]=o.useState("all"),W=o.useMemo(()=>Array.isArray(I.sliceRuns)?I.sliceRuns:[],[I.sliceRuns]),Ue=o.useMemo(()=>Kl({sessions:ee,sliceRuns:W}),[W,ee]).length,Ve=o.useMemo(()=>Gl(W),[W]),ze=Ve.length+(ve?I.decisions.length:0),[qe,Oe]=o.useState(null),ut=o.useCallback(m=>{const A=W.find(M=>M.initiativeId===m.initiativeId&&M.workstreamId===m.workstreamId)??null;Oe({source:"queue",item:m,linkedSliceRun:A})},[W]),Ft=o.useCallback((m,A)=>{Oe({source:"in_progress",row:m,sliceRun:A})},[]),pt=o.useCallback(m=>{Oe({source:"needs_input",sliceRun:m})},[]),bt=o.useCallback(async(m,A)=>{$("Slice accepted and marked complete."),h()},[h,$]),At=o.useCallback(async(m,A)=>{$("Changes requested — feedback posted.")},[$]),nt=bu({projectId:u,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:I.snapshotVersion}),Pt=vu({authToken:null,embedMode:!1}),{model:Je,actions:qt}=Nu({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Mt=o.useMemo(()=>Je.items.filter(m=>m.kind==="failure_diagnostic"),[Je.items]),_t=o.useMemo(()=>({...Je,items:Mt,total:Mt.length}),[Mt,Je]),[Ut,It]=o.useState(null),[on,as]=o.useState(0),os=o.useCallback(m=>{It(m);const A=Mt.findIndex(M=>M.id===m.id);as(A>=0?A:0)},[Mt]),Is=o.useCallback(m=>{if(Mt.length===0)return;const A=(on+m+Mt.length)%Mt.length;as(A),It(Mt[A]??null)},[on,Mt]),$n=nt,Ht=o.useMemo(()=>nt.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[nt.items]),Nn=!!Ht,As=o.useMemo(()=>{var M;if(!Ht)return null;const m=Ht.autoRuntimeState;return{state:m==="running"?"running":m==="stopping"?"stopping":"idle",reason:Ht.blockReason??null,activeRunId:((M=Ht.autoContinue)==null?void 0:M.activeRunId)??null,activeWorkstreamTitle:Ht.workstreamTitle??null}},[Ht]);o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(ha,"1"):window.localStorage.removeItem(ha)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(xa,"1"):window.localStorage.removeItem(xa)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(ga,"1"):window.localStorage.removeItem(ga)}catch{}},[a]),o.useEffect(()=>{a||tt(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(Ca,u):window.localStorage.removeItem(Ca)}catch{}try{const m=new URL(window.location.href);u?ag(m.searchParams,u):og(m.searchParams),m.searchParams.delete("initiative"),m.searchParams.delete("initiative_id"),m.searchParams.delete("project"),window.history.replaceState(null,"",`${m.pathname}${m.search}${m.hash}`)}catch{}}},[u]);const sn=o.useCallback((m,A)=>{Te(M=>({open:!0,tab:m??M.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),ls=o.useCallback(m=>{if(s(m),!(typeof window>"u"))try{const A=new URL(window.location.href);m?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),Tn=o.useCallback(()=>{sn("orgx")},[sn]),Kn=o.useCallback(()=>{nn(()=>import("./CSDhTbKy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),{data:Dn}=Xl(l==="mission-control",u),{data:Gn}=Jm(l==="mission-control",u),{data:cs=[]}=qs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Jt,ds]=o.useState(null),[fn,Fn]=o.useState(""),[D,de]=o.useState(!1),me=o.useCallback((m,A)=>{ds({type:m,initiativeId:A}),Fn(""),de(!1)},[]),Ce=o.useCallback(()=>{ds(null),Fn(""),de(!1)},[]),xt=o.useCallback(()=>{xe(null)},[]),Bt=o.useCallback(()=>{R(null),P(null)},[]),ft=o.useCallback(()=>{re(null)},[]);o.useEffect(()=>{var M;const m=((M=ee[0])==null?void 0:M.id)??null;if(!m){Ae!==null&&ue(null);return}if(Ae===null){ue(m);return}ee.some(_=>_.id===Ae)||ue(m)},[ee,Ae]),o.useEffect(()=>{if(!ie)return;ee.some(A=>A.id===ie)||xe(null)},[ie,ee]);const zt=o.useCallback(m=>{nn(()=>import("./C-XuWXGi.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ue(m),pe(!0),ne(null),xe(m),R(null),P(null)},[]),rn=o.useCallback(m=>{nn(()=>import("./C-XuWXGi.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ue(m.id),pe(!0),xe(m.id),R(m.workstreamId??null),P(m.title),ne({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),$(`Opened intervention composer for ${m.title}.`)},[]),Pn=o.useCallback(m=>{const A=m.trim();if(!A)return;const M=ee.find(_=>_.runId===A||_.id===A)??null;M&&(zt(M.id),$(`Focused session: ${M.title}`))},[ee,zt]),St=o.useCallback(m=>{var _;const A=(_=m.id)==null?void 0:_.trim();if(!A)return;const M=ya(m);if(M){const Z=ee.find(Me=>Me.runId===M||Me.id===M)??null;Z&&(ue(Z.id),xe(Z.id))}x("activity"),X("activity"),pe(!1),he(A),$("Opened activity detail from session timeline.")},[ee,x]),Tt=o.useMemo(()=>ee.find(m=>m.id===ie)??null,[ie,ee]),In=o.useMemo(()=>{var M,_;const m=((M=Tt==null?void 0:Tt.runId)==null?void 0:M.trim())??"",A=((_=Tt==null?void 0:Tt.id)==null?void 0:_.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[Tt==null?void 0:Tt.id,Tt==null?void 0:Tt.runId]),Et=o.useMemo(()=>{const m=new Set;for(const A of In){const M=A.trim();M.length>0&&m.add(M)}return m},[In]),An=o.useMemo(()=>{const m=new Map;for(const A of ee){const M=A.workstreamId??null;A.runId&&m.set(A.runId,M),A.id&&m.set(A.id,M)}return m},[ee]),_n=o.useMemo(()=>{const m=In.length>0?In.join("|"):"*",A=(K==null?void 0:K.trim())||"*",M=(G==null?void 0:G.trim())||"*";return`${m}::${A}::${M}`},[K,G,In]),_s=o.useCallback(m=>{se.current.add(_n),Q(m)},[_n]);o.useEffect(()=>{if(se.current.has(_n)||k)return;const m=Date.now(),A=be.filter(Z=>{const Me=ya(Z);if(Et.size>0&&(!Me||!Et.has(Me)))return!1;if(K){const ot=jl(Z);if((Nl(ot,["workstreamId","workstream_id"])??(Me?An.get(Me)??null:null))!==K)return!1}if(G){const ot=jl(Z);if((Nl(ot,["agentName","agent_name"])??Z.agentName)!==G)return!1}return!0});if(A.length===0)return;const _=["live","24h","7d","all"].find(Z=>{const Me=Lr(Z,m);return A.some(ot=>{const Fe=kn(ot.timestamp);return Fe?Me===null||Fe>=Me:!1})})??"all";se.current.add(_n),_!==H&&Q(_)},[K,be,_n,H,An,G,k,Et]);const hn=Pd({seed:be,timeFilterId:H,customSinceIso:H==="custom"?ge.startIso:null,customUntilIso:H==="custom"?ge.endIso:null,runId:(Tt==null?void 0:Tt.runId)??null,projectId:u,pageSize:50,demoMode:t}),an=o.useMemo(()=>ee.find(m=>m.id===Ae)??null,[ee,Ae]),Xn=o.useMemo(()=>ee.filter(m=>kl.has(m.status)).length,[ee]),Qn=o.useMemo(()=>W.length>0?Ve.length:ee.filter(m=>{const A=Zt(m.status),M=Zt(m.phase??""),_=Zt(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||M==="blocked"||_==="error"?!0:kl.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[W.length,Ve.length,ee]);o.useMemo(()=>ee.filter(m=>m.status==="failed").length,[ee]);const Ss=o.useMemo(()=>ee.filter(m=>m.status==="completed").length,[ee]);o.useMemo(()=>{const m=(ve?I.decisions.length:0)+Qn;return[{id:"active",label:"Running",value:Xn,color:Xn>0?T.lime:T.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?T.amber:T.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:Ss,color:T.teal,icon:"session"}]},[Xn,Qn,Ss,I.decisions.length,ee,ve]),o.useMemo(()=>I.decisions.length>0?Math.max(0,...I.decisions.map(m=>m.waitingMinutes)):0,[I.decisions]);const Jn=o.useMemo(()=>N?Qh(N):null,[N]),us=o.useMemo(()=>{const m=[];if(Jn){const A=Jn.action==="refresh"&&typeof h=="function";m.push({id:`stream-error:${N}`,kind:"error",icon:"notification",title:Jn.title,message:Jn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void h():()=>sn("orgx")})}return I.connection!=="connected"&&m.push({id:`connection:${I.connection}`,kind:I.connection==="disconnected"?"error":"info",icon:"notification",title:I.connection==="disconnected"?"Connection lost":"Reconnecting",message:I.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:Tn}),Re&&m.push({id:`ops:${Re}`,kind:"info",icon:/decision/i.test(Re)?"decision":"workstream",title:"Update",message:Re}),m},[I.connection,I.outbox.lastReplayError,I.outbox.pendingTotal,I.outbox.replayStatus,N,Jn,Tn,h,sn,Re]);o.useEffect(()=>{const m=new Set(us.map(A=>A.id));Nt(A=>A.filter(M=>m.has(M)))},[us]);const Yn=o.useMemo(()=>us.filter(m=>!jt.includes(m.id)),[jt,us]),Cs=ve?I.decisions.length:0,Dr=Xn+Qn+Cs,Fr=o.useCallback(m=>{Nt(A=>A.includes(m)?A:A.concat(m))},[]),Ws=o.useCallback(()=>{Nt(us.map(m=>m.id))},[us]);o.useEffect(()=>{if(!Xe)return;const m=M=>{var Z,Me;const _=M.target;_&&((Z=_e.current)!=null&&Z.contains(_)||(Me=O.current)!=null&&Me.contains(_)||kt(!1))},A=M=>{M.key==="Escape"&&kt(!1)};return document.addEventListener("mousedown",m),document.addEventListener("touchstart",m),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("touchstart",m),document.removeEventListener("keydown",A)}},[Xe]);const ln=o.useMemo(()=>{var M;const m=new Map;for(const _ of ee){const Z=_.initiativeId??_.groupId??"unscoped",Me=_.groupLabel&&_.groupLabel.trim().length>0?_.groupLabel:_.initiativeId??"Unscoped Initiative",ot=dg(Me),Fe=m.get(Z)??{id:Z,name:Me,category:ot,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(_.progress!==null&&(Fe.progressTotal+=_.progress,Fe.progressCount+=1),Fe.statusCounts[_.status]=(Fe.statusCounts[_.status]??0)+1,_.agentName&&(Fe.allAgents.add(_.agentName),["running","queued","pending","blocked"].includes(_.status)&&Fe.activeAgents.add(_.agentName)),_.workstreamId){const Ze=I.sessions.groups.find(Rt=>Rt.id===_.workstreamId),yt=((M=Ze==null?void 0:Ze.label)==null?void 0:M.trim())||_.workstreamId;Fe.workstreams.set(_.workstreamId,yt)}Fe.latestEpoch=Math.max(Fe.latestEpoch,kn(_.updatedAt??_.lastEventAt??_.startedAt)),m.set(Z,Fe)}const A=[];for(const _ of m.values()){const Z=_.progressCount>0?Math.round(_.progressTotal/_.progressCount):_.statusCounts.completed?100:_.statusCounts.running?55:0,Me=_.category,ot=ug(Me),Fe=Math.round(Math.max(0,Math.min(100,Z))/100*(ot.length-1)),Ze=(_.statusCounts.blocked??0)>0,yt=(_.statusCounts.completed??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0&&(_.statusCounts.blocked??0)===0&&(_.statusCounts.paused??0)===0,Rt=!yt&&!Ze&&(_.statusCounts.paused??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0,Ms=(_.statusCounts.running??0)+(_.statusCounts.active??0)+(_.statusCounts.in_progress??0),Ks=(_.statusCounts.queued??0)+(_.statusCounts.pending??0),en=_.workstreams.size,Sn=`${en} workstream${en===1?"":"s"}`,Li=en===0?"No workstreams linked yet.":yt?`${Sn} completed.`:Ze?`${Sn} linked · resolve blockers to continue.`:Rt?`${Sn} linked · initiative is paused.`:Ms>0?`${Ms} workstream${Ms===1?"":"s"} active right now.`:Ks>0?`${Ks} workstream${Ks===1?"":"s"} queued to start.`:`${Sn} linked · ready to run.`,zr=ot.map((gn,Wn)=>{let gs="upcoming";return(yt||Wn<Fe)&&(gs="completed"),Wn===Fe&&!yt&&(gs=Ze?"warning":"current"),{name:gn,status:gs}});A.push({id:_.id,name:_.name,status:yt?"completed":Ze?"blocked":Rt?"paused":"active",rawStatus:yt?"completed":Ze?"blocked":Rt?"paused":"active",category:Me,health:Math.max(0,Math.min(100,Z)),phases:zr,currentPhase:yt?ot.length-1:Fe,daysRemaining:0,targetDate:null,createdAt:_.latestEpoch>0?new Date(_.latestEpoch).toISOString():null,updatedAt:_.latestEpoch>0?new Date(_.latestEpoch).toISOString():null,activeAgents:_.activeAgents.size,totalAgents:_.allAgents.size,avatars:Array.from(_.activeAgents).slice(0,3),description:Li,workstreams:Array.from(_.workstreams.entries()).map(([gn,Wn])=>({id:gn,name:Wn,status:"active"}))})}return A.sort((_,Z)=>{const Me=_.status==="blocked"?0:_.status==="active"?1:2,ot=Z.status==="blocked"?0:Z.status==="active"?1:2;return Me!==ot?Me-ot:Z.health-_.health})},[ee,I.sessions.groups]),Zn=o.useMemo(()=>{const m=(_,Z)=>{var Fe,Ze;const Me=typeof Z.description=="string"&&Z.description.trim().length>0?Z.description:null,ot=typeof _.description=="string"&&_.description.trim().length>0?_.description:null;return{..._,...Z,health:Z.health>0?Z.health:_.health,activeAgents:Math.max(_.activeAgents,Z.activeAgents),totalAgents:Math.max(_.totalAgents,Z.totalAgents),avatars:(Fe=_.avatars)!=null&&Fe.length?_.avatars:Z.avatars,workstreams:(Ze=_.workstreams)!=null&&Ze.length?_.workstreams:Z.workstreams,description:Me??ot??void 0,rawStatus:Z.rawStatus??_.rawStatus??null,targetDate:Z.targetDate??_.targetDate??null,createdAt:Z.createdAt??_.createdAt??null,updatedAt:Z.updatedAt??_.updatedAt??null}},A=new Map;for(const _ of ln)A.set(_.id,_);for(const _ of[...Gn??[],...Dn??[]]){if(!B&&zs(_.id)){A.delete(_.id);continue}const Z=_.rawStatus??_.status;if(!_l(Z)){A.delete(_.id);continue}const Me=A.get(_.id);A.set(_.id,Me?m(Me,_):_)}const M=new Set(cs);return Array.from(A.values()).filter(_=>!M.has(_.id)).filter(_=>_l(_.rawStatus??_.status)).sort((_,Z)=>{const Me=Rt=>Rt==="blocked"?0:Rt==="active"?1:Rt==="paused"?2:3,ot=Me(_.status)-Me(Z.status);if(ot!==0)return ot;const Fe=Al(_.priority)-Al(Z.priority);if(Fe!==0)return Fe;const Ze=kn(Z.updatedAt)-kn(_.updatedAt);if(Ze!==0)return Ze;const yt=Z.health-_.health;return yt!==0?yt:_.name.localeCompare(Z.name)})},[ln,Dn,B,Gn,cs]),Pr=o.useMemo(()=>{const m={};for(const A of Zn)A.id&&A.name&&(m[A.id]=A.name);return m},[Zn]),Or=o.useMemo(()=>{if(!Tt)return null;const m=Tt.agentName,A=Tt.title;if(m){const M=be.find(_=>{var Z;return _.runId===Tt.runId&&((Z=_.summary)==null?void 0:Z.trim())});if(M!=null&&M.summary){const _=M.summary.trim().length>40?M.summary.trim().slice(0,40)+"…":M.summary.trim();return`${m}: ${_}`}return m}if(A){const M=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(M.length>0)return M}return A??null},[be,Tt]),lr=o.useMemo(()=>{const m=new Map;for(const A of ee){const M=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,_=(A.agentName??"").trim()||(A.agentId??"").trim();if(!_)continue;const Z=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),Me=kn(Z),ot=Me?Math.max(0,Math.floor((Date.now()-Me)/6e4)):0,Fe=m.get(M),Ze={id:M,name:_,role:"Agent",status:Yh(A.status),task:A.title??null,progress:A.progress??null,lastActive:Z,lastActiveMinutes:ot};(!Fe||kn(Ze.lastActive)>kn(Fe.lastActive))&&m.set(M,Ze)}return Array.from(m.values())},[ee]),On=o.useCallback(async()=>{if(ee.length===0){$("No sessions available to continue.");return}const m=[...ee].sort(ba)[0];if(ue(m.id),xe(m.id),R(null),P(null),["blocked","pending","queued"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}$(`Focused highest priority session: ${m.title}`),await h()},[ee,h]),E=o.useCallback(async(m,A)=>{const M=await m.json().catch(()=>null),_=typeof(M==null?void 0:M.error)=="string"&&M.error.trim()||typeof(M==null?void 0:M.message)=="string"&&M.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(_)?`${A}. This route is unavailable in the running plugin build.`:Wt(_)},[]),es=o.useCallback((m,A)=>!m||m.trim().length===0?A:Wt(m.trim())||A,[]),Bn=o.useCallback(async()=>{const m=Il(nt.items);if(!m){$("No startable Next Up workstream is available."),x("mission-control");return}await nt.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),xe(null),R(m.workstreamId),P(m.workstreamTitle),re(null),$(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([nt.refetch(),h()])},[h,nt,x]),dn=o.useCallback(async()=>{const m=Il(nt.items);if(!m){$("No startable initiative is ready for Autopilot yet."),x("mission-control");return}await Pt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await nt.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),xe(null),R(null),P(null),re(null),$(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([nt.refetch(),h()])},[h,Pt,nt,x]),Us=o.useCallback(async()=>{Le(!0);try{if(!Ht){await dn();return}await nt.stopInitiativeAutoContinue({initiativeId:Ht.initiativeId}),$(`Autopilot stopped for ${Ht.initiativeTitle}.`),await Promise.all([nt.refetch(),h()])}finally{Le(!1)}},[Ht,h,nt,dn]),ms=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),M=(m.workstreamId??"").trim();if(!A||!M)throw new Error("Missing initiative/workstream metadata for this session.");const _=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:M,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok)throw new Error(await E(_,"Failed to dispatch workstream from In Progress"));xe(null),R(M),P(m.title),$(`Dispatched ${m.title}.`),await Promise.all([nt.refetch(),h()])},[E,h,nt]),Hs=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),M=(m.workstreamId??"").trim();if(!A||!M)throw new Error("Missing initiative/workstream metadata for this session.");const _=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:M,placement:"bottom",resetToTodo:!1})});if(!_.ok){const Z=await E(_,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(Z))throw new Error(Z);const Me=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!Me.ok)throw new Error(await E(Me,"Failed to pause workstream using legacy fallback"))}$(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([nt.refetch(),h()])},[E,h,nt]),et=o.useCallback(async m=>{const A=(m.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const M=m.text.trim();if(ng(M)){sn("agents",{focusAgentDomain:"engineering"}),$("Opened agent settings for engineering runtime configuration.");return}const _=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(A)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:M,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!_.ok)throw new Error(await E(_,"Failed to submit intervention"));$(`Intervention sent for ${m.session.title}.`),await h()},[sn,E,h]),qn=o.useCallback(async m=>{if(ue(m.id),xe(m.id),R(null),P(null),!["running","completed","archived"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}$(`Dispatch requested: ${m.title}`),await h()},[h]),J=o.useCallback(async(m,A,M={})=>{const _=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!_.ok){const Z=await _.json().catch(()=>null);throw new Error((Z==null?void 0:Z.error)??`${A} failed (${_.status})`)}},[]),Br=o.useCallback(async m=>{var Z;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const Me=await A.json().catch(()=>null);throw new Error((Me==null?void 0:Me.error)??`Checkpoint creation failed (${A.status})`)}const M=await A.json().catch(()=>null),_=M&&"data"in M&&((Z=M.data)==null?void 0:Z.id)||M&&"id"in M&&M.id||null;$(_?`Checkpoint created: ${_.slice(0,8)}`:"Checkpoint created."),await h()},[h]),ps=o.useCallback(async m=>{await J(m,"pause",{reason:"pause_from_dashboard"}),$(`Pause requested: ${m.title}`),await h()},[h,J]),zn=o.useCallback(async m=>{await J(m,"resume",{reason:"resume_from_dashboard"}),$(`Resume requested: ${m.title}`),await h()},[h,J]),qr=o.useCallback(async m=>{await J(m,"cancel",{reason:"restart_from_in_progress"}),await ms(m),$(`Restarted ${m.title}.`),await h()},[ms,h,J]),Vt=o.useCallback(async m=>{await J(m,"cancel",{reason:"cancel_from_dashboard"}),$(`Cancel requested: ${m.title}`),await h()},[h,J]),F=o.useCallback(async m=>{var ot;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Fe=await A.json().catch(()=>null);throw new Error((Fe==null?void 0:Fe.error)??`Checkpoint list failed (${A.status})`)}const M=await A.json().catch(()=>null),Me=(ot=(Array.isArray(M)?M:Array.isArray(M==null?void 0:M.data)?M.data:[]).map(Fe=>({id:typeof Fe.id=="string"?Fe.id:"",createdAt:typeof Fe.createdAt=="string"?Fe.createdAt:typeof Fe.created_at=="string"?Fe.created_at:""})).filter(Fe=>Fe.id.length>0).sort((Fe,Ze)=>Date.parse(Ze.createdAt)-Date.parse(Fe.createdAt))[0])==null?void 0:ot.id;if(!Me)throw new Error("No checkpoint available for rollback.");await J(m,"rollback",{checkpointId:Me,reason:"rollback_from_dashboard"}),$(`Rollback requested for ${m.title}.`),await h()},[h,J]),Lt=o.useCallback(async()=>{var M;if(!Jt||fn.trim().length===0||D)return;de(!0);const m=Jt.type,A=fn.trim();try{const _={type:m,title:A,status:"active"};if(m==="workstream"){const Me=Jt.initiativeId??(an==null?void 0:an.initiativeId)??((M=ln[0])==null?void 0:M.id)??null;if(!Me){$("Select an initiative first to start a workstream."),de(!1);return}_.initiative_id=Me,_.parentId=Me}const Z=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(!Z.ok){const Me=await Z.json().catch(()=>null);throw new Error((Me==null?void 0:Me.error)??`Failed to create ${m}.`)}$(`Created ${m}: ${A}`),Ce(),await h()}catch(_){$(es(_ instanceof Error?_.message:"",`Failed to create ${m}.`)),de(!1)}},[Ce,D,Jt,fn,ln,h,an==null?void 0:an.initiativeId]),un=o.useCallback(()=>{me("initiative")},[me]),Vs=o.useCallback(m=>{me("workstream",m)},[me]);o.useCallback(()=>{var m;return Vs((an==null?void 0:an.initiativeId)??((m=ln[0])==null?void 0:m.id)??null)},[ln,an==null?void 0:an.initiativeId,Vs]);const fs=o.useCallback(m=>{const A=[...ee].filter(M=>(M.initiativeId??M.groupId)===m.id).sort(ba)[0];A&&(ue(A.id),xe(A.id),R(null),P(null),$(`Focused initiative: ${m.name}`))},[ee]),cr=o.useCallback(m=>{const A=ln.find(M=>M.id===m)??Zn.find(M=>M.id===m)??null;A&&fs(A)},[fs,ln,Zn]),hs=o.useCallback(m=>{const A=(m??"").trim();x("activity"),He("initiatives"),X("initiatives"),st("in_progress"),Dt("needs_attention"),q(A.length>0?A:null),$(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[x]),dr=o.useCallback(m=>{const A=new Set,M=(m.runId??"").trim();M.length>0&&A.add(M),A.add(m.sliceRunId);const _=new Map;for(const Ze of be){const yt=ya(Ze),Rt=Jh(Ze);(yt&&A.has(yt)||Rt&&Rt===m.sliceRunId)&&_.set(Ze.id,Ze)}const Z=Array.from(_.values()),Me=Ze=>{const yt=Ze.type.trim().toLowerCase();let Rt=0;return(yt==="decision_requested"||yt==="blocker_created")&&(Rt+=80),(yt==="run_failed"||yt==="autopilot_stopped")&&(Rt+=70),(yt.includes("slice_completed")||yt.includes("completed"))&&(Rt+=60),yt.includes("artifact")&&(Rt+=55),(yt.includes("progress")||yt.includes("update"))&&(Rt+=35),Rt+=Math.floor(kn(Ze.timestamp)/1e3),Rt};Z.sort((Ze,yt)=>Me(yt)-Me(Ze));const ot=Z[0]??null;x("activity"),X("activity"),He("initiatives");const Fe=(M?ee.find(Ze=>Ze.runId===M||Ze.id===M)??null:null)??(m.initiativeId&&m.workstreamId?ee.find(Ze=>Ze.initiativeId===m.initiativeId&&Ze.workstreamId===m.workstreamId)??null:null);if(Fe?(ue(Fe.id),xe(Fe.id),R(null),P(null)):m.workstreamId&&(xe(null),R(m.workstreamId),P(m.workstreamTitle??"Work slice")),ot!=null&&ot.id){he(ot.id),$(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){hs();return}if(M.length>0){Pn(M),$("Opened the related work session. Timeline details were unavailable.");return}$("No activity details were found for this slice yet.")},[be,Pn,hs,ee,x]);return o.useCallback(m=>{const A=new Set(m),M=[...ee].filter(_=>A.has(_.status)).sort(ba)[0];if(!M){$("No matching sessions for that metric right now.");return}zt(M.id),X("activity")},[ee,zt]),o.useCallback(m=>{l==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&We(m)},[l]),k?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:T.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((m,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),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}})]})]})]}):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:T.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(mg,{}),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(Qu,{color:Vh[I.connection],pulse:I.connection==="connected",title:[`Status: ${wl[I.connection]??I.connection}`,I.connection==="connected"?"Meaning: receiving live updates.":I.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${Gh(I.lastSnapshotAt)}`,Jn?`Details: ${Jn.message}`:null].filter(Boolean).join(`
212
- `),children:wl[I.connection]??"Unknown"}),(Xn>0||Qn>0)&&n.jsx(qo,{className:"hidden md:flex",running:Xn,blocked:Qn,decisionsCount:ve?I.decisions.length:0,completedToday:Ss,onDecisionsClick:()=>{x("activity"),He("initiatives"),X("initiatives"),st("in_progress"),Dt("needs_attention")},onBlockedClick:()=>{W.length>0?(x("mission-control"),st("in_progress"),Dt("needs_attention")):We("blocked")},onNewInitiative:un})]}),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:()=>x("activity"),"aria-pressed":l==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),onMouseEnter:Kn,onFocus:Kn,"aria-pressed":l==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:m=>{const A=m.target.value;p(A==="__all__"?null:A)},className:"control-pill h-8 min-w-[170px] appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${g}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),j.map(m=>n.jsx("option",{value:m.id,children:m.title},m.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"})})]}),I.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",I.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{ls(!1),Tn()},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 demo mode",children:"Exit demo"}),n.jsxs("button",{type:"button",ref:O,onClick:()=>kt(m=>!m),title:"Notifications","aria-haspopup":"dialog","aria-expanded":Xe,"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"})]}),Yn.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:Yn.length})]}),a?n.jsx("button",{type:"button",onClick:()=>tt(!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:()=>sn("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:h,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"})]}),Xe&&n.jsxs("div",{id:"header-notifications-panel",ref:_e,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:[Yn.length>0&&n.jsx("button",{type:"button",onClick:Ws,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>kt(!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(qo,{className:"max-w-full overflow-hidden",running:Xn,blocked:Qn,decisionsCount:Cs,completedToday:Ss,onDecisionsClick:()=>{x("activity"),X("initiatives"),He("initiatives"),st("in_progress"),Dt("needs_attention"),kt(!1)},onBlockedClick:()=>{W.length>0?(x("mission-control"),st("in_progress"),Dt("needs_attention")):We("blocked"),kt(!1)}})}),Yn.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:Dr>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:Yn.map(m=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:m.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:m.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:m.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(jn,{type:m.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:m.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:m.message}),m.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=m.onAction)==null||A.call(m),kt(!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:m.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>Fr(m.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"})]})},m.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:m=>{const A=m.target.value;p(A==="__all__"?null:A)},className:"control-pill h-8 w-full appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${g}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),j.map(m=>n.jsx("option",{value:m.id,children:m.title},m.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:()=>x("activity"),"aria-pressed":l==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),"aria-pressed":l==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),l==="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(Eh,{initiatives:Zn,activities:be,agents:lr,runtimeInstances:I.runtimeInstances??[],workspaceInitiativeId:u,isLoading:k,authToken:null,embedMode:!1,connection:I.connection,lastSnapshotAt:I.lastSnapshotAt,error:N,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>sn("orgx"),onRefresh:h,onCreateInitiative:un,onPlayNextUp:Bn,onStartAutopilot:dn,nextUpQueueModel:nt,nextUpActionsModel:Pt,snapshotVersion:I.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 ${we!=="agents"?"hidden lg:flex":""}`,children:n.jsx(Op,{sessions:I.sessions,activity:be,runtimeInstances:I.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:Ae,onSelectSession:zt,onAgentFilter:re,agentFilter:G,timeFilterId:H,onReconnect:Tn,onLaunched:h,connectionStatus:I.connection,autopilotState:As})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${we!=="activity"?"hidden lg:flex":""}`,children:n.jsx(Th,{activity:hn.items,sessions:ee,sliceRuns:W,initiatives:ln,timelineNarrative:I.timelineNarrative??[],workspaceId:u,chatSnapshot:I.chat,devMode:a,selectedRunIds:In,selectedSessionLabel:Or,selectedWorkstreamId:K,selectedWorkstreamLabel:U,agentFilter:G,timeFilterId:H,onTimeFilterChange:_s,customTimeRange:ge,onCustomTimeRangeChange:ke,hasMore:hn.hasMore,isLoadingMore:hn.isLoadingMore,onLoadMore:hn.loadMore,onClearSelection:xt,onClearWorkstreamFilter:Bt,onClearAgentFilter:ft,onFocusRunId:Pn,onOpenDecision:hs,requestedActivityItemId:ye,onActivityItemRequestHandled:()=>he(null),onPlayNextUp:Bn,onStartAutopilot:dn,onPauseWorkstream:Hs,onCreateInitiative:un,onOpenMissionControl:()=>x("mission-control"),onOpenNextUp:()=>x("mission-control"),onOpenSettings:()=>sn("orgx"),onRefreshData:h,isLoading:k})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${we!=="decisions"&&we!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${$e==="initiatives"?"flex-1":"flex-shrink-0"} `,children:$e==="initiatives"?n.jsxs(rr,{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":De==="in_progress",onClick:m=>{m.stopPropagation(),st("in_progress")},className:le("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",De==="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:Ue}),n.jsx("span",{className:le("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",De==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":De==="next_up",onClick:m=>{m.stopPropagation(),st("next_up")},className:le("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",De==="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:$n.total}),n.jsx("span",{className:le("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",De==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{Us().catch(m=>{$(es(m instanceof Error?m.message:"","Autopilot action failed."))})},disabled:rt,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":"teal","data-state":Nn?"active":"idle",title:Nn?"Stop autopilot":"Start autopilot","aria-label":Nn?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:le("h-3.5 w-3.5",Nn?"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:le("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",Nn?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:Nn?"On":"Off"})]})]}),De==="in_progress"?n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-subtle px-4 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>Dt("all"),className:le("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Ct==="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:Ue})]}),n.jsxs("button",{type:"button",onClick:()=>Dt("needs_attention"),className:le("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Ct==="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:ze})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:De==="in_progress"?Ct==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[_t.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($h,{model:_t,actions:qt,onOpenDetail:os})})}),ve?n.jsxs("section",{className:le("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",Ve.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:"Decision queue"}),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:I.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(Lh,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:I.decisions,focusDecisionId:L,onFocusDecisionHandled:()=>q(null),onApproveDecision:C,onRejectDecision:V,onApproveAll:te,onBulkDecisionAction:z,mutationState:Ie,initiativeNames:Pr})})})]}):n.jsx(rr,{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:le("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:ve?"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:Ve.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(Bm,{className:le("h-full min-h-0"),title:ve?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:W,initiatives:ln,onOpenDecisions:()=>hs(),onFocusRunId:Pn,onReviewActivity:dr,onOpenSliceDetail:pt})})]})]}):n.jsx(Cm,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:ee,sliceRuns:W,initiatives:ln,needsAttentionCount:ze,onSwitchToNeedsAttention:()=>Dt("needs_attention"),onOpenSession:zt,onFocusRunId:Pn,onPlayWorkstream:ms,onPauseWorkstream:Hs,onResumeWorkstream:ms,onRestartSession:qr,onIntervene:rn,onOpenSliceDetail:Ft}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Fh,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:nt,queueActions:Pt,snapshotVersion:I.snapshotVersion,excludeRunning:!0,onOpenInitiative:cr,onOpenSliceDetail:ut})})},`${De}:${Ct}`)]}):n.jsx(rr,{className:"card-enter",children:n.jsxs("button",{onClick:()=>He("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(vt,{children:Ke&&an&&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:()=>pe(!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:T.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(Rh,{session:an,activity:be,initiatives:ln,sliceRuns:W,initialInterventionDraft:ae,onSubmitIntervention:et,onOpenActivityItem:St,onContinueHighestPriority:On,onDispatchSession:qn,onPauseSession:ps,onResumeSession:zn,onCancelSession:Vt,onCreateCheckpoint:Br,onRollbackSession:F,onStartInitiative:un,onStartWorkstream:Vs,onClose:()=>pe(!1)})})})},"session-drawer-panel")]})}),l==="activity"?n.jsx(Yu,{activeTab:we,onTabChange:dt,pendingDecisionCount:ve?I.decisions.length:0}):null,n.jsx(Ei,{open:Jt!==null,onClose:Ce,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:(Jt==null?void 0:Jt.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Jt==null?void 0:Jt.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:fn,onChange:m=>Fn(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Lt()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Jt==null?void 0:Jt.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-[#BFFF00]/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:Ce,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:Lt,disabled:fn.trim().length===0||D,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:D?"Creating…":"Create"})]})]})}),fe.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ph,{open:fe.open,onClose:()=>Te(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:fe.tab,onChangeTab:m=>Te(A=>({...A,tab:m})),agentBehaviorInitialDomain:fe.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{ls(m),m||Tn()},devMode:a,onToggleDevMode:c,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:j,selectedWorkspaceId:u,onSelectWorkspace:p,onboarding:e,authToken:null,embedMode:!1})}),a&&Qe&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Hh,{open:Qe,selectedWorkspaceId:u,onClose:()=>tt(!1)})}),(Y==="sessions"||Y==="active"||Y==="blocked"||Y==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Oh,{open:Y==="sessions"||Y==="active"||Y==="blocked"||Y==="failed",onClose:()=>We(null),mode:Y==="active"||Y==="blocked"||Y==="failed"?Y:"sessions",sessions:ee,onOpenSession:m=>{zt(m.id),We(null)},onRunAction:async(m,A)=>{await J(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>h(),onSetNotice:m=>$(m)})}),Y==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Bh,{open:Y==="decisions",onClose:()=>We(null),decisions:ve?I.decisions:[],onApproveDecision:C,onRejectDecision:V,onApproveAll:te,onBulkDecisionAction:z})}),Y==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(qh,{open:Y==="outbox",onClose:()=>We(null),outbox:I.outbox,onOpenSettings:()=>{We(null),sn("orgx")},onRefresh:()=>{h()}})}),Y==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(zh,{open:Y==="handoffs",onClose:()=>We(null),handoffs:I.handoffs})}),n.jsx(pg,{}),Ut&&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(Dh,{item:Ut,actions:qt,onClose:()=>It(null),onNavigate:Is,currentIndex:on,totalCount:Mt.length,decisions:ve?I.decisions:void 0,onApproveDecision:C,onRejectDecision:V})})})}),qe&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Uh,{target:qe,initiatives:ln,onClose:()=>Oe(null),onPlayWorkstream:async(m,A,M)=>{const _=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,agentId:M??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok){const Z=await _.json().catch(()=>null);$(es((Z==null?void 0:Z.error)??(Z==null?void 0:Z.message)??null,`Failed to dispatch workstream (${_.status})`));return}$("Dispatched workstream."),h()},onStartAutoContinue:async(m,A,M)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:"top"})});const _=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,agentId:M??void 0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok){const Z=await _.json().catch(()=>null);$(es((Z==null?void 0:Z.error)??(Z==null?void 0:Z.message)??null,`Failed to start auto-continue (${_.status})`));return}$("Auto-continue started."),h()},onMoveWorkstream:async(m,A,M)=>{const _=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:M})});if(!_.ok){const Z=await _.json().catch(()=>null);$(es((Z==null?void 0:Z.error)??(Z==null?void 0:Z.message)??null,`Move failed (${_.status})`));return}$(`Moved workstream to ${M}.`),h()},onRemoveFromQueue:async(m,A)=>{const M=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!M.ok){const _=await M.json().catch(()=>null);$(es((_==null?void 0:_.error)??(_==null?void 0:_.message)??null,`Remove failed (${M.status})`));return}$("Removed workstream from queue."),h()},onOpenSession:zt,onFocusRunId:Pn,onOpenInitiative:cr,onReviewActivity:dr,onOpenDecisions:()=>hs(),onAcceptSlice:bt,onRejectSlice:At})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Kd();const hg=new Tc({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Cc.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(Ec,{client:hg,children:n.jsx(cg,{})})}));export{Kc as $,Xt as A,le as B,Yt as C,Vn as D,jn as E,ws as F,bu as G,Ag as H,Eg as I,_g as J,Cg as K,ys as L,_r as M,ks as N,Qp as O,rr as P,Ng as Q,Ds as R,Rn as S,Ri as T,eu as U,Du as V,Bl as W,Fu as X,zu as Y,Hu as Z,Mg as _,tu as a,Ig as a0,gm as a1,Tg as a2,Xr as a3,im as a4,hp as a5,jg as a6,pr as a7,wi as a8,Ot as b,Wm as c,Rd as d,T as e,Fg as f,dp as g,Wt as h,Gt as i,Ls as j,Rg as k,Jl as l,Qt as m,Zt as n,$g as o,Ji as p,vs as q,Dg as r,Pg as s,Um as t,vu as u,$t as v,Lg as w,Sg as x,Ei as y,Ns as z};