@useorgx/openclaw-plugin 0.7.15 → 0.7.17

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 (126) hide show
  1. package/dashboard/dist/assets/{CFZ4Swr5.js → 05zHA1Am.js} +1 -1
  2. package/dashboard/dist/assets/05zHA1Am.js.br +0 -0
  3. package/dashboard/dist/assets/05zHA1Am.js.gz +0 -0
  4. package/dashboard/dist/assets/0uYJrBLl.js +1 -0
  5. package/dashboard/dist/assets/0uYJrBLl.js.br +0 -0
  6. package/dashboard/dist/assets/0uYJrBLl.js.gz +0 -0
  7. package/dashboard/dist/assets/8nr6IqT4.js +1 -0
  8. package/dashboard/dist/assets/8nr6IqT4.js.br +0 -0
  9. package/dashboard/dist/assets/8nr6IqT4.js.gz +0 -0
  10. package/dashboard/dist/assets/{3VwNyxUf.js → B7kFLPiD.js} +1 -1
  11. package/dashboard/dist/assets/B7kFLPiD.js.br +0 -0
  12. package/dashboard/dist/assets/B7kFLPiD.js.gz +0 -0
  13. package/dashboard/dist/assets/{3TtV4moZ.js → B8NuBCcY.js} +1 -1
  14. package/dashboard/dist/assets/B8NuBCcY.js.br +0 -0
  15. package/dashboard/dist/assets/B8NuBCcY.js.gz +0 -0
  16. package/dashboard/dist/assets/{CnPC783_.js → BDlKSbsp.js} +1 -1
  17. package/dashboard/dist/assets/BDlKSbsp.js.br +0 -0
  18. package/dashboard/dist/assets/BDlKSbsp.js.gz +0 -0
  19. package/dashboard/dist/assets/C8AYbjlq.js +212 -0
  20. package/dashboard/dist/assets/C8AYbjlq.js.br +0 -0
  21. package/dashboard/dist/assets/C8AYbjlq.js.gz +0 -0
  22. package/dashboard/dist/assets/CMir7ekf.js +1 -0
  23. package/dashboard/dist/assets/CMir7ekf.js.br +0 -0
  24. package/dashboard/dist/assets/CMir7ekf.js.gz +0 -0
  25. package/dashboard/dist/assets/{CKrH5fYO.js → CWXk6UZl.js} +1 -1
  26. package/dashboard/dist/assets/CWXk6UZl.js.br +0 -0
  27. package/dashboard/dist/assets/CWXk6UZl.js.gz +0 -0
  28. package/dashboard/dist/assets/{Ctw95IkC.js → CoDun8X6.js} +1 -1
  29. package/dashboard/dist/assets/CoDun8X6.js.br +0 -0
  30. package/dashboard/dist/assets/CoDun8X6.js.gz +0 -0
  31. package/dashboard/dist/assets/{7DhYqBrM.js → Crj3jKHE.js} +1 -1
  32. package/dashboard/dist/assets/Crj3jKHE.js.br +0 -0
  33. package/dashboard/dist/assets/Crj3jKHE.js.gz +0 -0
  34. package/dashboard/dist/assets/{T2NFtzAv.js → CyUpNSKv.js} +1 -1
  35. package/dashboard/dist/assets/CyUpNSKv.js.br +0 -0
  36. package/dashboard/dist/assets/CyUpNSKv.js.gz +0 -0
  37. package/dashboard/dist/assets/{C9fvfXmS.js → D8mvKY2h.js} +1 -1
  38. package/dashboard/dist/assets/D8mvKY2h.js.br +0 -0
  39. package/dashboard/dist/assets/D8mvKY2h.js.gz +0 -0
  40. package/dashboard/dist/assets/{C91KLKit.js → DBRLnKWw.js} +1 -1
  41. package/dashboard/dist/assets/DBRLnKWw.js.br +0 -0
  42. package/dashboard/dist/assets/DBRLnKWw.js.gz +0 -0
  43. package/dashboard/dist/assets/DBct8HLW.js +1 -0
  44. package/dashboard/dist/assets/DBct8HLW.js.br +0 -0
  45. package/dashboard/dist/assets/DBct8HLW.js.gz +0 -0
  46. package/dashboard/dist/assets/{gZr_xKlA.js → DLNTxNX-.js} +1 -1
  47. package/dashboard/dist/assets/DLNTxNX-.js.br +0 -0
  48. package/dashboard/dist/assets/DLNTxNX-.js.gz +0 -0
  49. package/dashboard/dist/assets/DMKyYAtD.js +1 -0
  50. package/dashboard/dist/assets/DMKyYAtD.js.br +0 -0
  51. package/dashboard/dist/assets/DMKyYAtD.js.gz +0 -0
  52. package/dashboard/dist/assets/{CJjEAGFN.js → DdYkuATV.js} +1 -1
  53. package/dashboard/dist/assets/DdYkuATV.js.br +0 -0
  54. package/dashboard/dist/assets/DdYkuATV.js.gz +0 -0
  55. package/dashboard/dist/assets/{CGj8kRhg.js → DvFumX8R.js} +1 -1
  56. package/dashboard/dist/assets/DvFumX8R.js.br +0 -0
  57. package/dashboard/dist/assets/DvFumX8R.js.gz +0 -0
  58. package/dashboard/dist/assets/RZkbqlJk.css +1 -0
  59. package/dashboard/dist/assets/RZkbqlJk.css.br +0 -0
  60. package/dashboard/dist/assets/RZkbqlJk.css.gz +0 -0
  61. package/dashboard/dist/index.html +3 -3
  62. package/dashboard/dist/index.html.br +0 -0
  63. package/dashboard/dist/index.html.gz +0 -0
  64. package/dist/http/helpers/auto-continue-engine.d.ts +15 -0
  65. package/dist/http/helpers/auto-continue-engine.js +165 -0
  66. package/dist/http/helpers/mission-control.d.ts +3 -0
  67. package/dist/http/helpers/mission-control.js +38 -7
  68. package/dist/http/helpers/value-utils.d.ts +1 -1
  69. package/dist/http/helpers/value-utils.js +5 -2
  70. package/dist/http/index.js +3 -1
  71. package/dist/http/routes/chat.d.ts +1 -1
  72. package/dist/http/routes/chat.js +2 -2
  73. package/dist/http/routes/entities.js +60 -2
  74. package/dist/http/routes/entity-dynamic.js +49 -9
  75. package/dist/http/routes/live-snapshot.d.ts +10 -1
  76. package/dist/http/routes/live-snapshot.js +11 -3
  77. package/dist/http/routes/mission-control-actions.d.ts +6 -0
  78. package/dist/http/routes/mission-control-actions.js +33 -0
  79. package/package.json +1 -1
  80. package/dashboard/dist/assets/0RUEVzJa.js +0 -1
  81. package/dashboard/dist/assets/0RUEVzJa.js.br +0 -0
  82. package/dashboard/dist/assets/0RUEVzJa.js.gz +0 -0
  83. package/dashboard/dist/assets/3TtV4moZ.js.br +0 -0
  84. package/dashboard/dist/assets/3TtV4moZ.js.gz +0 -0
  85. package/dashboard/dist/assets/3VwNyxUf.js.br +0 -0
  86. package/dashboard/dist/assets/3VwNyxUf.js.gz +0 -0
  87. package/dashboard/dist/assets/7DhYqBrM.js.br +0 -0
  88. package/dashboard/dist/assets/7DhYqBrM.js.gz +0 -0
  89. package/dashboard/dist/assets/BVvffj0x.js +0 -1
  90. package/dashboard/dist/assets/BVvffj0x.js.br +0 -0
  91. package/dashboard/dist/assets/BVvffj0x.js.gz +0 -0
  92. package/dashboard/dist/assets/BiOgVMED.js +0 -1
  93. package/dashboard/dist/assets/BiOgVMED.js.br +0 -0
  94. package/dashboard/dist/assets/BiOgVMED.js.gz +0 -0
  95. package/dashboard/dist/assets/C91KLKit.js.br +0 -0
  96. package/dashboard/dist/assets/C91KLKit.js.gz +0 -0
  97. package/dashboard/dist/assets/C9fvfXmS.js.br +0 -0
  98. package/dashboard/dist/assets/C9fvfXmS.js.gz +0 -0
  99. package/dashboard/dist/assets/CFZ4Swr5.js.br +0 -0
  100. package/dashboard/dist/assets/CFZ4Swr5.js.gz +0 -0
  101. package/dashboard/dist/assets/CGj8kRhg.js.br +0 -0
  102. package/dashboard/dist/assets/CGj8kRhg.js.gz +0 -0
  103. package/dashboard/dist/assets/CJjEAGFN.js.br +0 -0
  104. package/dashboard/dist/assets/CJjEAGFN.js.gz +0 -0
  105. package/dashboard/dist/assets/CKrH5fYO.js.br +0 -0
  106. package/dashboard/dist/assets/CKrH5fYO.js.gz +0 -0
  107. package/dashboard/dist/assets/CMTTPXch.js +0 -1
  108. package/dashboard/dist/assets/CMTTPXch.js.br +0 -0
  109. package/dashboard/dist/assets/CMTTPXch.js.gz +0 -0
  110. package/dashboard/dist/assets/CnPC783_.js.br +0 -0
  111. package/dashboard/dist/assets/CnPC783_.js.gz +0 -0
  112. package/dashboard/dist/assets/Ctw95IkC.js.br +0 -0
  113. package/dashboard/dist/assets/Ctw95IkC.js.gz +0 -0
  114. package/dashboard/dist/assets/DHz-aQPw.js +0 -1
  115. package/dashboard/dist/assets/DHz-aQPw.js.br +0 -0
  116. package/dashboard/dist/assets/DHz-aQPw.js.gz +0 -0
  117. package/dashboard/dist/assets/DNX2foSJ.css +0 -1
  118. package/dashboard/dist/assets/DNX2foSJ.css.br +0 -0
  119. package/dashboard/dist/assets/DNX2foSJ.css.gz +0 -0
  120. package/dashboard/dist/assets/DxUw4FMR.js +0 -212
  121. package/dashboard/dist/assets/DxUw4FMR.js.br +0 -0
  122. package/dashboard/dist/assets/DxUw4FMR.js.gz +0 -0
  123. package/dashboard/dist/assets/T2NFtzAv.js.br +0 -0
  124. package/dashboard/dist/assets/T2NFtzAv.js.gz +0 -0
  125. package/dashboard/dist/assets/gZr_xKlA.js.br +0 -0
  126. package/dashboard/dist/assets/gZr_xKlA.js.gz +0 -0
@@ -0,0 +1,212 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/0uYJrBLl.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/DBct8HLW.js","assets/DvFumX8R.js","assets/eeHXe_OQ.js","assets/B7kFLPiD.js","assets/BCudUvwg.js","assets/DBRLnKWw.js","assets/CWXk6UZl.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/B8NuBCcY.js","assets/D8mvKY2h.js","assets/CMir7ekf.js","assets/CSlBSRyv.js","assets/C-MOJWHs.js","assets/CyUpNSKv.js","assets/DLNTxNX-.js","assets/05zHA1Am.js","assets/BDlKSbsp.js","assets/Crj3jKHE.js","assets/DdYkuATV.js","assets/8nr6IqT4.js","assets/CoDun8X6.js"])))=>i.map(i=>d[i]);
2
+ var kc=Object.defineProperty;var jc=(e,t,s)=>t in e?kc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Un=(e,t,s)=>jc(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as Nc,d as Ic}from"./Dj2k1r16.js";import{u as _a,a as Ac,b as Nn,c as Os,Q as Sc,d as _c}from"./DMKyYAtD.js";import{m as ue,A as yt,u as ss}from"./eeHXe_OQ.js";import{a7 as Cc}from"./cX2e-TLi.js";import{D as Ga}from"./BjK42gtU.js";import{T as Mc,u as Tc}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 Ec="modulepreload",Rc=function(e){return"/orgx/live/"+e},Xa={},sn=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=Rc(u),u in Xa)return;Xa[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":Ec,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)})},Qa=()=>{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)},{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)},{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)}],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"}],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()}}},$i="all";function ts(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Lc(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return ts(e.get("workspace_id"))??ts(e.get("workspaceId"))??ts(e.get("command_center_id"))??ts(e.get("commandCenterId"))??ts(e.get("center"))??ts(e.get("project_id"))??ts(e.get("projectId"))}catch{return null}}function vs(e,t,s){const r=ts(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",$i),e.set("command_center_id",$i),e.set("center",$i));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function $c(e){const t=ts(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??Lc();return Object.assign(t,$c(s)),t}const Dc=[[/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 Rr(e){if(!e)return"";for(const[s,r]of Dc)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const Nl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Il=/^[0-9a-f]{20,}$/i;function xs(e){return Nl.test(e)?`#${e.slice(0,4)}`:Il.test(e)?`#${e.slice(0,4)}`:e}function Vn(e){return Nl.test(e)||Il.test(e)}function Ls(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 lt(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=>Rr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Ls(s)),t}function Zt(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=>Ls(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 Di(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 Ja(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function gr(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 Fc(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 Ya(e){const t=Ja(e);if(!t)return null;const s=Ja(t.error),r=s??t,i=gr(r,["message","detail","error_description"])??(s?null:gr(t,["error"])),a=gr(r,["code","error_code","type"]),c=Fc(r,["status","httpStatusCode"]),l=gr(r,["requestId","request_id"]),d=gr(r,["docsUrl","docs_url"]);return!i&&!a&&c==null&&!l&&!d?null:{code:a,message:i,status:c,requestId:l,docsUrl:d}}function Pc(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),r=Ya(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=Ya(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 Za(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 Ut(e){var l;const t=Pc(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=Za(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.":Zt(lt(a))}function Oc(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 Bc(e){const t=e.metadata??{},s=Ks(t,"task_title")??Ks(t,"workstream_title"),r=s?Zt(String(s)):e.title?Zt(e.title):null,i=Ks(t,"user_summary")??Ks(t,"summary"),a=i?Zt(String(i)):e.summary?Zt(e.summary):e.description?Zt(e.description):null,c=Ks(t,"next_step")??Ks(t,"nextStep"),l=c?Zt(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 Ks(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const qc={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 xr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return qc[t]??e.replace(/_/g," ")}const zc={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function yg(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return zc[t]??e.replace(/_/g," ")}function bg(e,t){return e.toLowerCase().includes("path")?Ls(t):Vn(t)?xs(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return Vn(i)?xs(i):i}).join(", "):Zt(t)}function Wc(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 wg(e){const t=Wc(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function yi(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 Uc=8e3,Hc=320,Vc=300,Kc=80,Gc=80,Xc=120,eo=6e4,Qc=1200,Jc=90,Yc=3,Zc=24,to=24,yr=new WeakMap,Ca={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},Fs={threads:[],total:0,updatedAt:null},no={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},Al=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Ur=10*6e4;function ed(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 td(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=>Ut(a)).filter(a=>a.length>0).join(" ")}function nd(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 Ut(s.length>0?s:e.trim())}function sd(e){const t=e.map(s=>nd(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function xt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function bi(e,t){const s=no[e.status]??99,r=no[t.status]??99;if(s!==r)return s-r;const i=xt(e.updatedAt??e.lastEventAt??e.startedAt),a=xt(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function rd(e){return(e??"").trim().toLowerCase()}function so(e){return Al.has(rd(e.status))}function Fi(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function ro(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const g=Date.now(),j=e.nodes.filter(v=>{const N=xt(v.updatedAt??v.lastEventAt??v.startedAt);if(so(v))return!0;const C=["completed","archived","failed"].includes((v.status??"").toLowerCase())?Ur/3:Ur;return g-N<=C});if(!j.length)return t;const y=new Set(j.map(v=>v.id)),I=new Set(j.map(v=>v.groupId));return{nodes:j.sort(bi),edges:e.edges.filter(v=>y.has(v.parentId)&&y.has(v.childId)),groups:e.groups.filter(v=>I.has(v.id))}}const s=new Set,r=[...t.nodes];for(const g of t.nodes)for(const j of Fi(g))s.add(j);const i=Date.now(),a=[];for(const g of e.nodes){if(Fi(g).some(f=>s.has(f)))continue;const y=xt(g.updatedAt??g.lastEventAt??g.startedAt),v=["completed","archived","failed"].includes((g.status??"").toLowerCase())?Ur/3:Ur,N=i-y<=v;if(so(g)||N){a.push(g),r.push(g);for(const f of Fi(g))s.add(f)}}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(bi),edges:b,groups:u}}function br(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(bi).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 io(e,t){return e.length<=t?e:[...e].sort((s,r)=>xt(r.updatedAt)-xt(s.updatedAt)).slice(0,t)}function id(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()-xt(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 Sl(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 ao(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 oo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function lo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function _l(e){if(!e||typeof e!="object")return Ca;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 ad(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 wi(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=yr.get(r);if(i)return i;if(t>=Yc){const x=Array.isArray(e)?"[…]":"{…}";return yr.set(r,x),x}if(yr.set(r,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const x=e.slice(0,to).map(j=>wi(j,t+1)).join(","),b=e.length>to?",…":"",g=`[${x}${b}]`;return yr.set(r,g),g}const a=e,c=Object.keys(a).sort(),l=c.slice(0,Zc),d=l.map(x=>`${x}:${wi(a[x],t+1)}`).join("|"),u=c.length>l.length?"|…":"",p=`{${d}${u}}`;return yr.set(r,p),p}function od(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Cs(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 ld(e){const t=od(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)??Cs(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=Cs(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??Cs(t,["initiative_id","initiativeId"]),l=Cs(t,["workstream_id","workstreamId"]),d=Cs(t,["task_id","taskId"]),u=Cs(t,["stop_reason","stopReason"]),p=Cs(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 Cl(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=ld(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 cd(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,wi(d.metadata));let a=!1;for(const d of t){const u=r.get(d.id),p=wi(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=xt(u.timestamp)-xt(d.timestamp);return p!==0?p:u.id.localeCompare(d.id)}),l=Cl(c,s);return Sl(e,l)?e:l}function Pi(e,t){const s=[...e].sort((r,i)=>{const a=xt(i.timestamp)-xt(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Cl(s,t)}function co(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(id).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:xt(c.requestedAt??c.updatedAt)-xt(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 uo(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 dd(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 ud(e,t){return!!(Al.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 Oi(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 md(e,t,s){const r=new Map,i=[...e].sort((l,d)=>xt(d.timestamp)-xt(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:uo(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||xt(p)<xt(u.startedAt))&&(u.startedAt=p),xt(p)>=xt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=p,u.lastEventAt=p,u.lastEventSummary=l.title,u.status=uo(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=dd(l.status),x=new Date().toISOString(),b=ud(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:Oi(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),Oi(l.blockers).length>0&&(u.blockers=Oi(l.blockers)),j&&!u.initiativeId&&(u.initiativeId=j,u.groupId=j,u.groupLabel=Vr(j))}const a=Array.from(r.values()).sort(bi).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 pd(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"||ed(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 fd(e,t,s,r,i=[],a=Ca,c=null,l=1,d=[],u=Fs,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=xt(x)>=xt(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:_l(a),chat:di(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 mo(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)=>xt(r.lastEventAt??r.lastHeartbeatAt)-xt(s.lastEventAt??s.lastHeartbeatAt))}function po(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 hd(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)=>xt(r.lastActivityAt??r.updatedAt)-xt(s.lastActivityAt??s.updatedAt))}function di(e){if(!e||typeof e!="object")return Fs;const t=hd(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 gd(e,t){const s=e??Fs,r=t??Fs;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 ui(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)=>xt(i.updatedAt??i.lastEventAt)-xt(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)=>xt(r.updatedAt??r.completedAt??r.failedAt)-xt(s.updatedAt??s.completedAt??s.failedAt))}function Bi(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)=>xt(r.occurredAt)-xt(s.occurredAt))}function qi(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 fo(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 ui(t)}function xd(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 yd(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 bd(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 wd(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 vd(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 kd(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 jd(e={}){const{enabled:t=!0,pollInterval:s=Uc,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=Hc,maxActivityItems:d=Vc,maxHandoffs:u=Kc,maxDecisions:p=Gc,batchWindowMs:x=Xc}=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(Qa()),[I,v]=o.useState(Wr),[N,f]=o.useState(!r),[C,H]=o.useState(null),Z=o.useRef(),U=o.useRef(null),fe=o.useRef(null),[K,re]=o.useState(!1),be=o.useRef(0),ve=o.useRef(!1),Se=o.useRef(`${b??"__all__"}::${g??"__all__"}`),me=o.useRef(!1),Ke=o.useRef(null),pe=o.useCallback((P,W)=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null),v(P),W!=null&&W.autoResetMs&&W.autoResetMs>0&&(Ke.current=setTimeout(()=>{Ke.current=null,v(Wr)},W.autoResetMs))},[]);o.useEffect(()=>()=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null)},[]),o.useEffect(()=>{const P=`${b??"__all__"}::${g??"__all__"}`;Se.current!==P&&(Se.current=P,me.current=!0,pe(Wr),y(W=>({...W,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Fs,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(W.snapshotVersion??0)+1})),f(!0),H(null))},[b,g,pe]);const ae=o.useCallback((P,W,Q,xe=null,je=null,ne=null,ye=null,ge=null,E=null,B=null)=>{be.current=Date.now(),ve.current=!1,y(G=>{const se=me.current;se&&(me.current=!1);const Re=W===null?se?[]:G.activity:Pi(W,d),Ge=Q===null?se?[]:G.handoffs:io(Q,u),Te=br(P===null?se?{nodes:[],edges:[],groups:[]}:G.sessions:se?br(P,l):ro(G.sessions,br(P,l)),l),L=xe===null?se?[]:G.decisions:co(xe,p),at=je===null?se?[]:G.sliceRuns:ui(je),Le=ne===null?se?Ca:G.outbox:_l(ne),Xe=ge===null?se?[]:G.runtimeInstances??[]:mo(ge),bt=E===null?se?Fs:G.chat??Fs:di(E),vt=(B==null?void 0:B.workSliceProjections)==null?se?[]:G.workSliceProjections??[]:Kr(B.workSliceProjections),kt=(B==null?void 0:B.timelineNarrative)==null?se?[]:G.timelineNarrative??[]:Bi(B.timelineNarrative),O=(B==null?void 0:B.nextUpByInitiative)==null?se?[]:G.nextUpByInitiative??[]:qi(B.nextUpByInitiative),_e=typeof(B==null?void 0:B.runningWorkSlices)=="number"&&Number.isFinite(B.runningWorkSlices)?Math.max(0,Math.floor(B.runningWorkSlices)):G.runningWorkSlices??0,he=typeof(B==null?void 0:B.needsInputTotal)=="number"&&Number.isFinite(B.needsInputTotal)?Math.max(0,Math.floor(B.needsInputTotal)):G.needsInputTotal??0,Me=typeof(B==null?void 0:B.failedActionableTotal)=="number"&&Number.isFinite(B.failedActionableTotal)?Math.max(0,Math.floor(B.failedActionableTotal)):G.failedActionableTotal??0,Qe=typeof(B==null?void 0:B.completedTodayTotal)=="number"&&Number.isFinite(B.completedTodayTotal)?Math.max(0,Math.floor(B.completedTodayTotal)):G.completedTodayTotal??0,nt=(B==null?void 0:B.consistencyFlags)==null?G.consistencyFlags??[]:B.consistencyFlags.filter(we=>typeof we=="string"),J=(B==null?void 0:B.dataHealth)===void 0||(B==null?void 0:B.dataHealth)===null?G.dataHealth:B.dataHealth,ze=(G.snapshotVersion??0)+1;return ao(G.sessions,Te)&&Sl(G.activity,Re)&&oo(G.handoffs,Ge)&&lo(G.decisions,L)&&xd(G.sliceRuns,at)&&ad(G.outbox,Le)&&gd(G.chat,bt)&&po(G.runtimeInstances,Xe)&&yd(G.workSliceProjections??[],vt)&&bd(G.timelineNarrative??[],kt)&&wd(G.nextUpByInitiative??[],O)&&(G.runningWorkSlices??0)===_e&&(G.needsInputTotal??0)===he&&(G.failedActionableTotal??0)===Me&&(G.completedTodayTotal??0)===Qe&&vd(G.consistencyFlags??[],nt)&&kd(G.dataHealth,J)&&G.lastSnapshotAt===ye&&G.connection==="connected"?G:fd(Te,Re,Ge,L,at,Le,ye,ze,Xe,bt,{workSliceProjections:vt,timelineNarrative:kt,nextUpByInitiative:O,runningWorkSlices:_e,needsInputTotal:he,failedActionableTotal:Me,completedTodayTotal:Qe,consistencyFlags:nt,dataHealth:J})}),f(!1)},[d,p,u,l]),te=o.useCallback(async()=>{if(!t){y(Q=>Q.connection==="disconnected"?Q:{...Q,connection:"disconnected"}),f(!1),H(null);return}const P=`${b??"__all__"}::${g??"__all__"}`;if(U.current&&fe.current===P)return U.current;if(r){y(Qa()),f(!1);return}const W=(async()=>{try{const Q=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});g&&vs(Q,g),b&&Q.set("initiative",b);const xe=[{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()}`}],je=[];let ne=null,ye=!1;for(let De=0;De<xe.length;De+=1){const rt=xe[De];De>0&&await new Promise(_t=>{setTimeout(_t,Jc)});const ut=await pd(rt.url,{headers:Ot({workspaceId:g})},{timeoutMs:Qc});if(ut.ok&&ut.data){ne=ut.data;break}(ut.status===401||ut.status===403)&&(ye=!0),je.push(`${rt.label}: ${ut.error??"unavailable"}`)}if(!ne){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(td(je))}if(Se.current!==P)return;const ge=Array.isArray(ne.degraded)?ne.degraded.filter(De=>typeof De=="string"):[],E=ge.map(De=>De.toLowerCase()),B=(...De)=>E.some(rt=>De.some(ut=>rt.includes(ut))),G=Array.isArray(ne.activity)?ne.activity:[],se=Array.isArray(ne.handoffs)?ne.handoffs:[],Re=Array.isArray(ne.decisions)?ne.decisions:[],Ge=G.length===0&&B("activity unavailable","activity local fallback failed"),Te=B("sessions unavailable","sessions local fallback failed"),L=se.length===0&&B("handoffs unavailable"),at=Re.length===0&&B("decisions unavailable"),Le=Kr(Array.isArray(ne.projections)?ne.projections:[]),Xe=di(ne.chat??null),bt=Bi(Array.isArray(ne.timelineNarrative)?ne.timelineNarrative:[]),vt=qi(Array.isArray(ne.nextUpByInitiative)?ne.nextUpByInitiative:[]),kt=Le.length>0?fo(Le):ui(Array.isArray(ne.sliceRuns)?ne.sliceRuns:[]),O=ne.sessions&&Array.isArray(ne.sessions.nodes)&&Array.isArray(ne.sessions.edges)&&Array.isArray(ne.sessions.groups)?ne.sessions:md(G,ne.agents,l),_e=kt.length===0&&Le.length===0&&B("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),he=vt.length===0&&B("next-up unavailable","next-up queue"),Me=Ge?null:G,Qe=L?null:se,nt=at?null:Re,J=Te&&O.nodes.length===0?null:O,ze=_e?null:Le,we=_e?null:bt,X=_e?null:kt,$e=he?null:vt;ae(J,Me,Qe,nt,X,ne.outbox??null,ne.generatedAt??null,ne.runtimeInstances??null,Xe,{workSliceProjections:ze,timelineNarrative:we,nextUpByInitiative:$e,runningWorkSlices:_e?null:ne.runningWorkSlices??null,needsInputTotal:_e?null:ne.needsInput??null,failedActionableTotal:_e?null:ne.failedActionable??null,completedTodayTotal:_e?null:ne.completedToday??null,consistencyFlags:Array.isArray(ne.consistencyFlags)?ne.consistencyFlags:null,dataHealth:ne.dataHealth??null});const He=ge.length>0?sd(ge):[];He.length>0?(H(`Partial live data: ${He.join("; ")}`),y(De=>De.connection==="connected"?De:{...De,connection:"connected"}),re(!1)):(H(null),y(De=>De.connection==="connected"?De:{...De,connection:"connected"}))}catch(Q){if(Se.current!==P)return;const xe=Q instanceof Error?Q.message:"Unknown error",je=!!(Q&&typeof Q=="object"&&"code"in Q&&Q.code==="ORGX_AUTH");je&&(ve.current=!0);const ne=be.current>0&&Date.now()-be.current>eo;H(xe),y(ye=>{const ge=je||ne?"disconnected":"reconnecting";return ye.connection===ge?ye:{...ye,connection:ge}}),re(!je),f(!1)}finally{fe.current===P&&(U.current=null,fe.current=null)}})();return U.current=W,fe.current=P,W},[ae,t,i,d,p,u,l,g,b,r]),ie=o.useCallback(async(P,W,Q)=>{var E,B,G;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const xe=Array.from(new Set(P.filter(Boolean)));if(xe.length===0)return{updated:0,failed:0};const je=((E=Q==null?void 0:Q.note)==null?void 0:E.trim())||void 0,ne=((B=Q==null?void 0:Q.optionId)==null?void 0:B.trim())||void 0;if(r){const se=new Set(xe);return y(Re=>{const Ge=Re.decisions.filter(Le=>se.has(Le.id));if(Ge.length===0)return Re;const Te=new Date().toISOString(),L=Ge.map(Le=>({id:`decision:${W}:${Le.id}:${Date.now()}`,type:"decision_resolved",title:W==="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:Te,metadata:{decisionId:Le.id,action:W}})),at=Pi(L.concat(Re.activity),d);return{...Re,decisions:Re.decisions.filter(Le=>!se.has(Le.id)),activity:at,lastActivity:$t(Te)}}),{updated:se.size,failed:0,firstError:void 0}}const ye=new Date().toISOString(),ge=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ot({contentTypeJson:!0,workspaceId:g}),body:JSON.stringify({ids:xe,action:W,...je?{note:je}:{},...ne?{option_id:ne}:{}})});try{const se=await ge.json().catch(()=>null),Re=Array.isArray(se==null?void 0:se.results)?se.results:[],Ge=new Set(Re.filter(Xe=>Xe.ok).map(Xe=>Xe.id)),L=((G=Re.filter(Xe=>!Xe.ok).find(Xe=>typeof Xe.error=="string"&&Xe.error.trim().length>0))==null?void 0:G.error)??(typeof(se==null?void 0:se.error)=="string"&&se.error.trim().length>0?se.error:void 0);if(!ge.ok&&ge.status!==207){const Xe=L??`Decision action failed (${ge.status})`;throw new Error(Xe)}if(Ge.size===0&&ge.ok&&((se==null?void 0:se.failed)??0)===0)for(const Xe of xe)Ge.add(Xe);Ge.size>0?y(Xe=>{const bt=Xe.decisions.filter(he=>Ge.has(he.id));if(bt.length===0)return Xe;const vt=new Date().toISOString(),kt=bt.map(he=>({id:`decision:${W}:${he.id}:${Date.now()}`,type:"decision_resolved",title:W==="approve"?`Approved: ${he.title}`:`Rejected: ${he.title}`,description:he.context,agentId:null,agentName:he.agentName,requesterAgentId:null,requesterAgentName:he.agentName??null,executorAgentId:null,executorAgentName:he.agentName??null,runId:null,initiativeId:null,timestamp:vt,metadata:{decisionId:he.id,action:W}})),O=Pi(kt.concat(Xe.activity),d);return{...Xe,decisions:Xe.decisions.filter(he=>!Ge.has(he.id)),activity:O,lastActivity:$t(vt)}}):ge.ok&&xe.length>0&&y(Xe=>({...Xe,decisions:Xe.decisions.filter(bt=>!xe.includes(bt.id))})),te();const at=(se==null?void 0:se.updated)??Ge.size,Le=(se==null?void 0:se.failed)??Math.max(0,xe.length-Ge.size);return pe({phase:Le>0?"error":"success",action:W,targetCount:xe.length,message:Le>0?`${W==="approve"?"Approve":"Reject"} completed with ${Le} failure${Le===1?"":"s"}.`:W==="approve"?`Approved ${at} decision${at===1?"":"s"}.`:`Rejected ${at} decision${at===1?"":"s"}.`,startedAt:ye,completedAt:new Date().toISOString()},{autoResetMs:Le>0?8e3:4e3}),{updated:at,failed:Le,firstError:L}}catch(se){throw pe({phase:"error",action:W,targetCount:xe.length,message:se instanceof Error?se.message:"Decision update failed.",startedAt:ye,completedAt:new Date().toISOString()}),se}},[i,te,d,g,pe,r]),ke=o.useCallback(async(P,W)=>ie([P],"approve",W),[ie]),V=o.useCallback(async(P,W)=>ie([P],"reject",W),[ie]),T=o.useCallback(async()=>{let P=[];return y(W=>(P=W.decisions.map(Q=>Q.id),W)),P.length===0?{updated:0,failed:0}:ie(P,"approve")},[ie]),z=o.useCallback(async(P,W,Q)=>ie(P,W,Q?{note:Q}:void 0),[ie]);return o.useEffect(()=>{i||pe(Wr)},[i,pe]),o.useEffect(()=>{if(!t){re(!1),f(!1),H(null);return}if(r){te();return}if(te(),g){re(!0);return}const P=new URLSearchParams;g&&vs(P,g),b&&P.set("initiative",b);const W=P.toString()?`/orgx/api/live/stream?${P.toString()}`:"/orgx/api/live/stream",Q=new EventSource(W),xe=new EventSource("/orgx/api/hooks/runtime/stream");let je=null,ne=null,ye=null,ge=null,E=[],B=null,G;const se=()=>{if(G=void 0,je){be.current=Date.now(),ve.current=!1;const Te=je;je=null,ye=null,ge=null,E=[],B=null,ne=null,ae(Te.sessions,Te.activity,Te.handoffs,Te.decisions,Te.sliceRuns,Te.outbox,Te.generatedAt,Te.runtimeInstances,Te.chat,Te.v2);return}!ye&&!ge&&!B&&!ne&&E.length===0||(be.current=Date.now(),ve.current=!1,y(Te=>{var at;let L=Te;if(ye){const Le=br(ye,l),Xe=br(ro(L.sessions,Le),l);ye=null,ao(L.sessions,Xe)||(L={...L,sessions:Xe})}if(ge){const Le=io(ge,u);ge=null,oo(L.handoffs,Le)||(L={...L,handoffs:Le})}if(B){const Le=co(B,p);B=null,lo(L.decisions,Le)||(L={...L,decisions:Le})}if(ne){const Le=mo(ne);ne=null,po(L.runtimeInstances,Le)||(L={...L,runtimeInstances:Le})}if(E.length>0){const Le=cd(L.activity,E,d);E=[],Le!==L.activity&&(L={...L,activity:Le,lastActivity:(at=Le[0])!=null&&at.timestamp?$t(Le[0].timestamp):L.lastActivity})}return L===Te?Te:L.connection==="connected"?L:{...L,connection:"connected"}}),H(null),f(!1))},Re=()=>{G||(G=setTimeout(se,x))};Q.onopen=()=>{be.current=Date.now(),ve.current=!1,re(!1),y(Te=>Te.connection==="connected"?Te:{...Te,connection:"connected"}),H(null)},Q.onerror=()=>{if(ve.current){y(L=>L.connection==="disconnected"?L:{...L,connection:"disconnected"}),re(!1);return}const Te=be.current>0&&Date.now()-be.current>eo;y(L=>L.connection===(Te?"disconnected":"reconnecting")?L:{...L,connection:Te?"disconnected":"reconnecting"}),re(!0)},Q.addEventListener("snapshot",Te=>{try{const L=JSON.parse(Te.data),at=typeof L.generatedAt=="string"&&L.generatedAt.length>0?L.generatedAt:new Date().toISOString();je={sessions:L.sessions,activity:L.activity??[],handoffs:L.handoffs??[],decisions:L.decisions??null,sliceRuns:Array.isArray(L.sliceRuns)?ui(L.sliceRuns):Array.isArray(L.projections)?fo(Kr(L.projections)):null,outbox:L.outbox??null,generatedAt:at,runtimeInstances:Array.isArray(L.runtimeInstances)?L.runtimeInstances:null,chat:di(L.chat??null),v2:{workSliceProjections:Array.isArray(L.projections)?Kr(L.projections):null,timelineNarrative:Array.isArray(L.timelineNarrative)?Bi(L.timelineNarrative):null,nextUpByInitiative:Array.isArray(L.nextUpByInitiative)?qi(L.nextUpByInitiative):null,runningWorkSlices:typeof L.runningWorkSlices=="number"?L.runningWorkSlices:null,needsInputTotal:typeof L.needsInput=="number"?L.needsInput:null,failedActionableTotal:typeof L.failedActionable=="number"?L.failedActionable:null,completedTodayTotal:typeof L.completedToday=="number"?L.completedToday:null,consistencyFlags:Array.isArray(L.consistencyFlags)?L.consistencyFlags:null,dataHealth:L.dataHealth??null}},Re()}catch(L){H(L instanceof Error?L.message:"Invalid snapshot")}}),Q.addEventListener("activity.appended",Te=>{try{const L=JSON.parse(Te.data);if(L.length===0)return;E=E.concat(L),Re()}catch{}}),Q.addEventListener("session.updated",Te=>{try{ye=JSON.parse(Te.data),Re()}catch{}});const Ge=Te=>{try{const L=JSON.parse(Te.data);ne=Array.isArray(L)?L:[L],Re()}catch{}};return Q.addEventListener("runtime.updated",Ge),xe.addEventListener("runtime.updated",Ge),Q.addEventListener("handoff.updated",Te=>{try{ge=JSON.parse(Te.data),Re()}catch{}}),Q.addEventListener("decision.updated",Te=>{try{B=JSON.parse(Te.data),Re()}catch{}}),()=>{G&&clearTimeout(G),Q.close(),xe.close()}},[ae,x,t,i,te,d,p,u,l,b,g,r]),o.useEffect(()=>{if(!(!t||r||(Z.current&&clearInterval(Z.current),!K&&!!!g)))return Z.current=setInterval(te,s),()=>{Z.current&&clearInterval(Z.current)}},[t,te,g,s,K,r]),{data:j,isLoading:N,error:C,refetch:te,approveDecision:ke,rejectDecision:V,approveAllDecisions:T,bulkDecisionAction:z,decisionMutation:I}}const Lr=[{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 Ml(e){return Lr.find(t=>t.id===e)??Lr[0]}function Fr(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=Lr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Nd(e,t=Date.now()){const s=Fr(e,t);return s?new Date(s).toISOString():null}const Id=new Set(["ungrouped","unscoped","unknown"]),Ad="orgx.demo_mode",Sd="orgx.show_synthetic_entities";function Bs(e){const t=(e??"").trim().toLowerCase();return!!(!t||Id.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Xt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Ad)==="1"}catch{return!1}}function _d(){if(typeof window>"u")return!1;if(Xt())return!0;try{return window.localStorage.getItem(Sd)==="1"}catch{return!1}}function Cd(e){return Xt()?!0:!Bs(e)}function ga(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Tl(e,t){const s=ga(t.timestamp)-ga(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function Md(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Td(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 El(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=Md(e.metadata);return Td(s,["initiative_id","initiativeId"])}function zi(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function xa(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(!xa(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]||!xa(s[l],r[l]))return!1}return!0}const Ed=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function er(e,...t){}function Rd(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&&El(p)!==r){d++;continue}const x=ga(p.timestamp);if(x){if(a!==null&&x<a){u++;continue}if(c!==null&&x>c){u++;continue}i.set(p.id,p)}}return er("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(Tl)}function ho(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||!xa(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return er("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Tl):e}function Ld(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=Xt()}=e,p=o.useMemo(()=>zi(a),[a]),x=o.useMemo(()=>zi(c),[c]),b=o.useMemo(()=>zi(l),[l]),g=o.useMemo(()=>Fr(s),[s]),j=o.useMemo(()=>Nd(s),[s]),y=o.useMemo(()=>{if(s==="custom"){const T=(r==null?void 0:r.trim())??"";return T.length>0?T:null}return j},[r,j,s]),I=o.useMemo(()=>{if(s!=="custom")return null;const T=(i==null?void 0:i.trim())??"";return T.length>0?T:null},[i,s]),v=o.useMemo(()=>{if(y){const T=Date.parse(y);if(Number.isFinite(T))return T}return g},[g,y]),N=o.useMemo(()=>{if(!I)return null;const T=Date.parse(I);return Number.isFinite(T)?T:null},[I]),f=o.useMemo(()=>Rd(t,{sinceEpoch:v,untilEpoch:N},p,x),[t,v,N,p,x]),C=u?null:"",[H,Z]=o.useState(f),[U,fe]=o.useState(()=>C),[K,re]=o.useState(!1),[be,ve]=o.useState(null),[Se,me]=o.useState(null),Ke=o.useRef(null),pe=o.useRef(!1),ae=o.useRef(f);ae.current=f;const te=o.useMemo(()=>`${p??""}|${x??""}|${s}|${y??""}|${I??""}|${b??""}|${u?"demo":"live"}`,[p,x,s,y,I,b,u]),ie=o.useRef(te);o.useEffect(()=>{ie.current!==te&&(ie.current=te,er("RESET",{reason:"filter/run change",runId:p,initiativeId:x,projectId:b,timeFilterId:s,sinceIso:y,untilIso:I,seedCount:ae.current.length}),Z(ae.current),fe(C),ve(null),me(null),pe.current=!1)},[te,C,p,x,b,s,y,I]),o.useEffect(()=>{Z(T=>{const z=ho(T,f);return z!==T&&er("SSE_MERGE",{prevCount:T.length,seedCount:f.length,nextCount:z.length,delta:z.length-T.length}),z})},[f]);const ke=o.useCallback(async()=>{if(u){fe(null),ve(null);return}if(U===null)return;if(Ke.current)return Ke.current;re(!0);const T=(async()=>{try{const z=new URLSearchParams;z.set("limit",String(Math.max(1,Math.min(500,d)))),U.trim().length>0&&z.set("cursor",U),y&&z.set("since",y),I&&z.set("until",I),p&&z.set("run",p),x&&z.set("initiative",x),b&&vs(z,b);const P=await fetch(`/orgx/api/live/activity/page?${z.toString()}`,{headers:Ot({workspaceId:b})}),W=await P.json().catch(()=>null);if(!P.ok||!W){const je=typeof(W==null?void 0:W.error)=="string"&&W.error.trim()||typeof(W==null?void 0:W.message)=="string"&&W.message.trim()||`Activity paging failed (${P.status})`;throw new Error(je)}const Q=Array.isArray(W.activities)?W.activities:[],xe=Q.filter(je=>!x||El(je)===x);er("PAGE_FETCH",{cursor:U,rawCount:Q.length,afterFilter:xe.length,filteredOut:Q.length-xe.length,initiativeId:x,runId:p,nextCursor:W.nextCursor??null}),Z(je=>{const ne=ho(je,xe);return er("PAGE_MERGE",{prevCount:je.length,pageCount:xe.length,nextCount:ne.length,added:ne.length-je.length}),ne}),fe(W.nextCursor??null),me(W.storeUpdatedAt??null),ve(null)}catch(z){const P=z instanceof Error?z.message:"";ve(P?Ut(P):"Activity paging failed"),fe(W=>W===""?null:W)}finally{re(!1),Ke.current=null}})();return Ke.current=T,T},[U,u,x,d,b,p,y,I]);return o.useEffect(()=>{U===""&&(pe.current||(pe.current=!0,ke()))},[U,ke]),{items:H,hasMore:U!==null,isLoadingMore:K,error:be,storeUpdatedAt:Se,loadMore:ke,cutoffEpoch:v,sinceIso:y,untilIso:I}}const $d="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Dd="".trim().toLowerCase()==="true"||"".trim()==="1",Fd="".trim().toLowerCase()==="true"||"".trim()==="1",Pd={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Wi=null,go=!1,xo=!1,Ma=!1;function Od(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function _i(){return Ma||!Dd?!1:Fd?!0:!Od()}function Bd(){return _i()?(Wi||(Wi=sn(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(Ma=!0,null))),Wi):Promise.resolve(null)}function qd(e){if(go)return!0;try{return e.init($d,Pd),go=!0,!0}catch{return Ma=!0,!1}}async function Ta(){const e=await Bd();return!e||!qd(e)?null:e}function zd(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 Wd(){!_i()||typeof window>"u"||xo||(xo=!0,zd(()=>{Ta()}))}function Ud(e){if(!_i())return;const t=e.trim();t&&Ta().then(s=>{if(s)try{s.identify(t)}catch{}})}function hs(e,t){_i()&&e.trim()&&Ta().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const Hd="https://orgx.mintlify.site/guides/openclaw-plugin-setup",Vd=1500,Ui="orgx.onboarding.skip",Kd=680,Gd=`<!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>`,mi={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Hd,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Gs(){return{...mi,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function Hi(e){if(typeof e=="string")return Ut(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Ut(t.error);if(typeof t.message=="string")return Ut(t.message)}}async function wr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:Hi(s==null?void 0:s.error)??Hi(s==null?void 0:s.message)??Hi(s)??Ut(`Request failed (${t.status})`)}}function Gr(e){if(e)try{Ud(e)}catch{}}function Xd(){const[e,t]=o.useState(()=>Xt()?Gs():mi),[s,r]=o.useState(()=>!Xt()),[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(Ui)==="1"),x=o.useCallback(async()=>{if(Xt()){const f=Gs();return t(f),f}const N=await wr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!N.ok||!N.data){const f=N.error??"Failed to load onboarding state",C={...mi,status:"error",lastError:f,nextAction:"retry"};return t(C),C}return Gr(N.data.installationId??null),t(N.data),N.data},[]);o.useEffect(()=>{if(Xt()){t(Gs()),r(!1);return}let N=!1;return(async()=>{r(!0);const f=await x();N||(t(f),r(!1))})(),()=>{N=!0}},[x]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const f=Math.max(900,e.pollIntervalMs??Vd),C=window.setInterval(async()=>{const H=await wr(fetch("/orgx/api/onboarding/status",{method:"GET"}));H.ok&&H.data&&(Gr(H.data.installationId??null),t(H.data))},f);return()=>{window.clearInterval(C)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(Ui,"1");return}window.localStorage.removeItem(Ui)}},[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(Gd),N.document.close(),N):null}catch{return null}},[]),g=o.useCallback(async()=>{if(Xt()){const f=Gs();t(f);return}const N=b();d.current=N,a(!0);try{const f=await wr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),C=f.data;if(!f.ok||!(C!=null&&C.state)){N&&!N.closed&&N.close();const Z=f.error??"Could not start pairing";t(U=>({...U,status:"error",lastError:Z,nextAction:"enter_manual_key"}));return}t(C.state);const H=C.connectUrl;if(H){const Z=d.current;let U=!1;if(Z&&!Z.closed)try{window.setTimeout(()=>{if(!Z.closed)try{Z.location.href=H}catch{}},Kd),U=!0}catch{U=!1}U||(U=!!window.open(H,"_blank","noopener,noreferrer")),U||t(fe=>({...fe,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(Xt()){const f=Gs();return t(f),f}l(!0);try{const f=N.trim(),C=f.replace(/^[a-z]+_/i,""),H=Array.from(new Set([f,C?`oxk_${C}`:"",C?`orgx_${C}`:""].map(U=>U.trim()).filter(U=>U.length>0)));let Z="Manual key validation failed";for(const U of H){const fe={"Content-Type":"application/json","X-OrgX-Api-Key":U,Authorization:`Bearer ${U}`},K=await wr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:fe,body:JSON.stringify({apiKey:U})}));if(K.ok&&K.data)return Gr(K.data.installationId??null),t(K.data),K.data;Z=K.error??Z}throw t(U=>({...U,status:"manual_key",lastError:Z,nextAction:"enter_manual_key"})),new Error(Z)}finally{l(!1)}},[]),y=o.useCallback(async()=>{if(Xt()){const C=Gs();return t(C),C}const N=await wr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(N.ok&&N.data)return Gr(N.data.installationId??null),t(N.data),N.data;const f={...mi,status:"idle"};return t(f),f},[]),I=o.useCallback(()=>{t(N=>({...N,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),v=o.useMemo(()=>Xt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:v,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 ys={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 Qd 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 Jd(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 Qd(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 vg(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 Rl 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 Yd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $r(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 Zd(e,t){if(e.status!==404)return!1;const s=$r(t,["error"])??"",r=$r(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${r}`)}function eu(e,t,s){if(Zd(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=$r(t,["error","message"])??`${s} (${e.status})`;return Ut(r)}function Vi(e,t,s){const r=Yd(t),i=eu(e,r,s),a=$r(r,["code"]),c=$r(r,["error_location","errorLocation"]),l=r==null?void 0:r.retryable,d=typeof l=="boolean"?l:!1;return new Rl({message:i,status:e.status,code:a,errorLocation:c,retryable:d,details:r})}function kg(e){return e instanceof Rl}const tu=750;async function vr(e){return await e.json().catch(()=>null)}function nu(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 su(e,t,s){if(nu(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 Ut(r)}function ru(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?Ut(s):t}function iu(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 pi({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 au(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 ou(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function Ea(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 Ra(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 Ll(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=Ea(typeof c.id=="string"?c.id:null),d=Ra(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 lu(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function cu(e){const t=Ea(e.runnerAgentId),s=Ra(e.runnerAgentName,t),r=Ll(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=lu(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:ou(e),autoRuntimeState:au(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 pi(e){const t=e.items.map(u=>cu(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 du(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 uu(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 mu(e){var x,b,g,j,y,I,v,N,f,C,H,Z,U,fe,K,re;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=(v=e.sourceWorkstreamIds)==null?void 0:v.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=(f=e.lineage)==null?void 0:f.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=Ea(e.runnerAgentId??null),d=Ra(e.runnerAgentName??null,l),u=Ll(e.runnerAgents??null,l,d),p=u[0]??null;return{initiativeId:r,initiativeTitle:((H=e.initiativeTitle)==null?void 0:H.trim())||t[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:i,workstreamTitle:((Z=e.workstreamTitle)==null?void 0:Z.trim())||((U=e.title)==null?void 0:U.trim())||((fe=e.milestoneTitle)==null?void 0:fe.trim())||((K=e.taskTitle)==null?void 0:K.trim())||uu(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((re=e.taskTitle)==null?void 0:re.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:du(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 pu(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 fu(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 hu({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 me,Ke,pe,ae,te,ie,ke;const u=_a(),p=Xt(),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(()=>ys.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:ys.liveData({authToken:i,embedMode:a,projectId:t})})},tu)},v=async({includeGraph:V=!0,includeLiveData:T=!0}={})=>{const z=[u.invalidateQueries({queryKey:j}),u.invalidateQueries({queryKey:ys.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})})];V&&z.push(u.invalidateQueries({queryKey:ys.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})),await Promise.all(z),T&&I()},N=async(V,T)=>{if(p)return iu(e);const z=new URLSearchParams;e&&z.set("initiative_id",e),vs(z,t,{allTokenWhenMissing:!0}),z.set("offset",String(V)),z.set("limit",String(T));let P;try{P=await fetch(`/orgx/api/mission-control/next-up?${z.toString()}`,{headers:Ot({authToken:i,embedMode:a})})}catch(ye){throw new Error(ru(ye,"Failed to load next up queue"))}const W=await vr(P);if(!P.ok){const ye=su(P,W,"Failed to load next up queue");throw new Error(ye)}const Q=W??null;if(!Q||Q.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:V,limit:T,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(_d())return pi(Q);const xe=Q.items.filter(ye=>!Bs(ye.initiativeId));let je=pi({...Q,items:xe});if(je.items.length>0)return je;const ne=new URLSearchParams;e&&ne.set("initiative_id",e),vs(ne,t,{allTokenWhenMissing:!0}),ne.set("level","workstream"),ne.set("include_completed","0"),ne.set("offset",String(V)),ne.set("limit",String(Math.max(T,24)));try{const ye=await fetch(`/orgx/api/mission-control/slices?${ne.toString()}`,{headers:Ot({authToken:i,embedMode:a})}),ge=await vr(ye);if(ye.ok&&(ge!=null&&ge.ok)&&Array.isArray(ge.items)){const E=ge.items.map(B=>mu(B)).filter(B=>!!B).filter(B=>!Bs(B.initiativeId));E.length>0&&(je=pi({ok:!0,generatedAt:new Date().toISOString(),total:typeof ge.total=="number"&&Number.isFinite(ge.total)?Math.max(ge.total,E.length):E.length,items:E,pagination:ge.pagination&&typeof ge.pagination=="object"?{offset:typeof ge.pagination.offset=="number"?Math.max(0,Math.floor(ge.pagination.offset)):V,limit:typeof ge.pagination.limit=="number"?Math.max(1,Math.floor(ge.pagination.limit)):Math.max(T,24),total:typeof ge.pagination.total=="number"?Math.max(0,Math.floor(ge.pagination.total)):E.length,nextCursor:typeof ge.pagination.nextCursor=="string"?ge.pagination.nextCursor:null,hasMore:typeof ge.pagination.hasMore=="boolean"?ge.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...Q.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return je},f=Ac({queryKey:j,enabled:c,initialPageParam:x,queryFn:async({pageParam:V})=>{const T=typeof V=="number"&&Number.isFinite(V)?Math.max(0,Math.floor(V)):x;return await N(T,b)},getNextPageParam:V=>{const T=V.pagination;if(!(T!=null&&T.hasMore)||!T.nextCursor)return;const z=Number.parseInt(T.nextCursor,10);if(Number.isFinite(z))return Math.max(0,Math.floor(z))},refetchInterval:V=>{var P;const T=(P=V.state.data)==null?void 0:P.pages;return!T||T.length===0?1e4:T.some(W=>Array.isArray(W.items)&&W.items.some(Q=>Q.queueState==="running"))?2500:8e3}}),C=Nn({mutationFn:async V=>{if(p)return{ok:!0,initiativeId:V.initiativeId,workstreamId:V.workstreamId,dispatchMode:"slice",sessionId:null};const T=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:V.initiativeId,workstreamId:V.workstreamId,agentId:V.agentId??void 0,scope:V.scope??void 0,maxParallelSlices:typeof V.maxParallelSlices=="number"&&Number.isFinite(V.maxParallelSlices)?Math.max(1,Math.floor(V.maxParallelSlices)):void 0,parallelMode:V.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),z=await vr(T);if(!T.ok)throw Vi(T,z,"Failed to dispatch queued workstream");return z},onMutate:async V=>{await u.cancelQueries({queryKey:j});const T=u.getQueryData(j);return T?(u.setQueryData(j,{...T,pages:T.pages.map(z=>({...z,items:z.items.map(P=>P.initiativeId===V.initiativeId&&P.workstreamId===V.workstreamId?{...P,queueState:"running",playbackState:"running"}:P.queueState==="running"?{...P,queueState:"idle",playbackState:"idle"}:P)}))}),{previous:T}):{previous:T}},onError:(V,T,z)=>{z!=null&&z.previous&&u.setQueryData(j,z.previous)},onSuccess:()=>{v({includeGraph:!1})}}),H=Nn({mutationFn:async V=>{if(p)return;const T={initiativeId:V.initiativeId,agentId:V.agentId??void 0,tokenBudgetTokens:V.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};V.scope==="workstream"&&V.workstreamId&&(T.workstreamIds=[V.workstreamId]),typeof V.maxParallelSlices=="number"&&Number.isFinite(V.maxParallelSlices)&&(T.maxParallelSlices=V.maxParallelSlices),V.parallelMode==="iwmt"&&(T.parallelMode=V.parallelMode);const z=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(T)}),P=await vr(z);if(!z.ok){const W=Jd(P);throw W||Vi(z,P,"Failed to start auto-continue")}},onSuccess:()=>{v({includeGraph:!1})}}),Z=Nn({mutationFn:async V=>{if(p)return;const T=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ot({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:V.initiativeId})}),z=await vr(T);if(!T.ok)throw Vi(T,z,"Failed to stop auto-continue")},onSuccess:()=>{v({includeGraph:!1})}}),U=o.useMemo(()=>{var P;const V=((P=f.data)==null?void 0:P.pages)??[];if(V.length===0)return[];const T=new Set,z=[];for(const W of V)for(const Q of W.items){const xe=`${Q.initiativeId}:${Q.workstreamId}`;T.has(xe)||(T.add(xe),z.push(Q))}return z},[(me=f.data)==null?void 0:me.pages]),fe=o.useMemo(()=>{var z;const V=((z=f.data)==null?void 0:z.pages)??[];let T=0;for(const P of V)typeof P.total=="number"&&Number.isFinite(P.total)&&(T=Math.max(T,P.total));return Math.max(T,U.length)},[U.length,(Ke=f.data)==null?void 0:Ke.pages]),K=o.useMemo(()=>{var xe;const V=((xe=f.data)==null?void 0:xe.pages)??[];if(V.length===0)return null;const T=V[0],z=V[V.length-1],P=T.pagination,W=z.pagination,Q=!!f.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:fe,nextCursor:Q?(W==null?void 0:W.nextCursor)??String(((W==null?void 0:W.offset)??x)+((W==null?void 0:W.limit)??b)):null,hasMore:Q}},[fe,b,x,(pe=f.data)==null?void 0:pe.pages,f.hasNextPage]),re=((te=(ae=f.data)==null?void 0:ae.pages[0])==null?void 0:te.generatedAt)??null,be=o.useMemo(()=>{var z;const V=((z=f.data)==null?void 0:z.pages)??[],T=new Set;for(const P of V)for(const W of P.degraded??[])typeof W=="string"&&W.trim().length>0&&T.add(W);return Array.from(T)},[(ie=f.data)==null?void 0:ie.pages]),ve=o.useMemo(()=>d==="initiative"?pu(U):[],[U,d]),Se=o.useMemo(()=>d==="milestone"?fu(U):[],[U,d]);return{items:U,total:fe,pagination:K,generatedAt:re,degraded:be,isLoading:f.isLoading,isFetching:f.isFetching,isFetchingNextPage:f.isFetchingNextPage,hasNextPage:!!f.hasNextPage,error:((ke=f.error)==null?void 0:ke.message)??null,refetch:f.refetch,fetchNextPage:f.fetchNextPage,playWorkstream:C.mutateAsync,startWorkstreamAutoContinue:H.mutateAsync,stopInitiativeAutoContinue:Z.mutateAsync,isPlaying:C.isPending,isStartingAutoContinue:H.isPending,isStoppingAutoContinue:Z.isPending,zoomLevel:d,initiativeGroups:ve,milestoneGroups:Se}}const gu=750;async function hn(e){return await e.json().catch(()=>null)}function Ys(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 gn(e,t,s){if(Ys(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 Ut(r)}function xu(e){const t=e.authToken??null,s=e.embedMode??!1,r=Xt(),i=_a(),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"]})},gu)},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 f=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 hn(f);if(f.ok)return C;if(!Ys(f,C))throw new Error(gn(f,C,"Failed to move Next Up item"));const H=await fetch("/orgx/api/mission-control/next-up",{headers:Ot({authToken:t,embedMode:s})}),Z=await hn(H);if(!H.ok)throw new Error(gn(H,Z,"Failed to read queue for move fallback"));const fe=(Array.isArray(Z==null?void 0:Z.items)?Z.items:[]).map(Se=>{const me=typeof(Se==null?void 0:Se.initiativeId)=="string"?Se.initiativeId:null,Ke=typeof(Se==null?void 0:Se.workstreamId)=="string"?Se.workstreamId:null;return!me||!Ke?null:{initiativeId:me,workstreamId:Ke}}).filter(Se=>!!Se);if(fe.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const K=fe.findIndex(Se=>Se.initiativeId===N.initiativeId&&Se.workstreamId===N.workstreamId);if(K===-1)return{ok:!0,fallback:"reorder-move-skip"};const[re]=fe.splice(K,1);(N.placement??"top")==="bottom"?fe.push(re):fe.unshift(re);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:fe})}),ve=await hn(be);if(!be.ok)throw new Error(gn(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 f=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 hn(f);if(f.ok)return C;if(Ys(f,C)){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)}),Z=await hn(H);if(!H.ok)throw new Error(gn(H,Z,"Failed to remove item from queue with legacy fallback"));return Z??{ok:!0,fallback:"next-up-unpin"}}throw new Error(gn(f,C,"Failed to remove item from queue"))},p=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0};const f=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 hn(f);if(!f.ok)throw new Error(gn(f,C,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),x=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0};const f=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 hn(f);if(!f.ok)throw new Error(gn(f,C,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),b=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,updated:N.order.length};const f=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 hn(f);if(!f.ok)throw new Error(gn(f,C,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),g=Nn({mutationFn:d,onSuccess:()=>{l()}}),j=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId};const f=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 hn(f);if(!f.ok){if(Ys(f,C)){const H=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})}),Z=await hn(H);if(!H.ok)throw new Error(gn(H,Z,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(gn(f,C,"Failed to stop triage"))}return C},onSuccess:()=>{l()}}),y=Nn({mutationFn:u,onSuccess:()=>{l()}}),I=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,cleared:!0};const f=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 hn(f);if(!f.ok){if(Ys(f,C)&&N.initiativeId){const H=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})}),Z=await hn(H);if(!H.ok)throw new Error(gn(H,Z,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(gn(f,C,"Failed to clear Next Up lifecycle state"))}return C},onSuccess:()=>{l()}}),v=Nn({mutationFn:async N=>{if(r)return{ok:!0,demo:!0,updated:N.items.length,failed:0,errors:[],fallback:"demo"};const f=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 hn(f);if(!f.ok){if(!Ys(f,C))throw new Error(gn(f,C,"Failed to apply bulk queue action"));const H=await Promise.all(N.items.map(async K=>{try{return N.action==="remove"?await u(K):await d({initiativeId:K.initiativeId,workstreamId:K.workstreamId,placement:N.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(re){return{ok:!1,error:re instanceof Error?re.message:"Queue action failed"}}})),Z=H.filter(K=>K.ok).length,U=H.length-Z,fe=H.filter(K=>!K.ok&&K.error).map(K=>K.error);return{ok:U===0,updated:Z,failed:U,errors:fe,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:v.mutateAsync,isPinning:p.isPending,isUnpinning:x.isPending,isReordering:b.isPending,isMoving:g.isPending,isRemoving:y.isPending,isStoppingTriage:j.isPending,isClearing:I.isPending,isBulking:v.isPending}}function $l(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function yu(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:$l(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(Ut(String(d)))}return c.json()}async function bu(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:$l(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(Ut(String(d)))}return c.json()}function wu(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,c=_a(),l=ys.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=Os({queryKey:l,queryFn:()=>yu(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=Nn({mutationFn:async({itemId:g,payload:j})=>bu(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 oe(...e){return e.filter(Boolean).join(" ")}const M={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"},jg={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)"}},vu={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},ku={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function Dl(e){return vu[e]??"rgba(255, 255, 255, 0.4)"}function ya(e){return ku[e]??null}function ju(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function en(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Jt={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}},Ng={surfaceSwitch:{duration:Jt.durationStandard/1e3,ease:Jt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Jt.durationFast/1e3,ease:Jt.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:Jt.durationStandard/1e3,ease:Jt.easingStandard}})},Ig={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},Ci="/orgx/live/assets/Fm0FhtnV.png";function Fl({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 vn({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??M.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??M.lime;return n.jsx(Fl,{size:s,className:t,stroke:c,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${c}1A`})}if(e==="milestone"){const c=r??M.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??M.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??M.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??M.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??M.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??M.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??M.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??M.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??M.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 Nu=[{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"}],fi=[{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."}],Iu=[{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."}],yo="openclaw plugins install @useorgx/openclaw-plugin",bo="orgx.demo_mode",Au=6500;function Su(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 _u={hidden:{},visible:{transition:{staggerChildren:.07}}},gs={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},Cu={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 Ki(e){const t=fi.length;return(e+t)%t}function Mu({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,c=e.lastError?Ut(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=fi[x];o.useEffect(()=>{if(l==="idle")return;const f=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(f)},[l]),o.useEffect(()=>{if(u==="idle")return;const f=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(f)},[u]),o.useEffect(()=>{if(g)return;const f=window.setInterval(()=>{b(C=>Ki(C+1))},Au);return()=>window.clearInterval(f)},[g]);const v=async()=>{try{await navigator.clipboard.writeText(yo),d("ok")}catch{d("error")}},N=async()=>{try{const f={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(f,null,2)),p("ok")}catch{p("error")}};return n.jsxs(ue.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-4 sm:px-8 sm:pt-5",children:[n.jsxs(ue.div,{variants:gs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Ci,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsxs(ue.h2,{variants:gs,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(vn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ue.p,{variants:gs,className:"mt-2 max-w-2xl text-heading leading-relaxed text-secondary",children:"Orchestrate agents, approve decisions, and track progress from a single live dashboard."})]}),n.jsxs("div",{className:"mt-3 grid gap-3 px-6 sm:px-8 lg:grid-cols-[1.24fr_0.86fr]",children:[n.jsxs(ue.div,{variants:gs,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(vn,{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,"/",fi.length]})]}),n.jsx(yt,{initial:!1,mode:"wait",children:n.jsxs(ue.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.24,ease:[.22,1,.36,1]},className:"mt-2.5 min-h-[214px] space-y-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.09em] text-muted",children: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(f=>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(vn,{type:f.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:f.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:f.detail})]},`${I.id}-${f.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:fi.map((f,C)=>{const H=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 ${H?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},f.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>b(f=>Ki(f-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(f=>Ki(f+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:Nu.map(f=>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 ${Cu[f.iconType]}`,children:n.jsx(vn,{type:f.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:f.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:f.desc})]},f.label))}),n.jsxs(ue.div,{variants:gs,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(ue.div,{variants:gs,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(vn,{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(vn,{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:yo}),n.jsx("button",{type:"button",onClick:()=>{v()},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: ",Su(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:Iu.map(f=>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(vn,{type:f.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:f.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:f.detail})]},f.label))})]})]})]}),n.jsx(ue.div,{variants:gs,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(ue.div,{variants:gs,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(bo,"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(bo)}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 Tu={hidden:{},visible:{transition:{staggerChildren:.06}}},Ms={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Eu({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(Ut(g))}},u=a!==null;return n.jsxs(ue.section,{variants:Tu,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-6 sm:px-8 sm:pt-8",children:[n.jsxs(ue.div,{variants:Ms,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Ci,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsx(ue.h3,{variants:Ms,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ue.p,{variants:Ms,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(ue.p,{variants:Ms,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(ue.div,{variants:Ms,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(ue.div,{variants:Ms,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(ue.p,{initial:{opacity:0,y:-3},animate:{opacity:1,y:0},className:"mt-1.5 text-body text-red-400/70",children:a})]}),n.jsxs("p",{className:"text-body text-muted",children:["User-scoped keys (",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_..."}),") do not require a separate user ID header."]})]}),n.jsxs(ue.div,{variants:Ms,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 wo="orgx.user.display-name",vo="orgx.user.avatar-seed-suffix";function ko(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function jo(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function Ru(){const[e,t]=o.useState(()=>ko(wo)),[s,r]=o.useState(()=>ko(vo)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();jo(wo,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());jo(vo,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function Lu(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function $u(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 No=[M.lime,M.teal,M.iris,M.cyan];function Du(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),v=t+s*d(p),N=e+s*l(u),f=t+s*d(u);return[`M ${b} ${g}`,`A ${r} ${r} 0 ${x} 1 ${j} ${y}`,`L ${I} ${v}`,`A ${s} ${s} 0 ${x} 0 ${N} ${f}`,"Z"].join(" ")}function Fu(e){const t=$u(Lu(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=No[Math.floor(t()*No.length)],I=.25+t()*.55;r.push({d:Du(i,a,l,d,g,j),fill:y,opacity:I})}}return r}function Pu({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>Fu(e),[e]);return n.jsxs(ue.svg,{viewBox:"0 0 100 100",width:t,height:t,className:oe("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Jt.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:M.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:M.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:M.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(ue.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:Jt.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 Ou({onComplete:e}){const{displayName:t,updateName:s}=Ru(),[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(ue.div,{initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:Jt.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(Pu,{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 Bu=[{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 qu({className:e,compact:t=!1}){return n.jsxs("div",{className:oe("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"]}),Bu.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 Io="orgx.user.name-asked";function zu(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 Wu(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 Uu(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Ao={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Gi="orgx.onboarding.mc_hint.dismissed",Xi={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 Hu({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(Gi)==="1"),[b,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Io)!=="1"),j=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Io,"1"),g(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(Gi,"1"):window.localStorage.removeItem(Gi))},[p]);const y=e.status==="manual_key",I=e.status==="awaiting_browser_auth"||e.status==="pairing",v=Uu(e.status),N=v==="active"&&e.status!=="connected",f=e.status==="connected"&&!p;return n.jsx("div",{className:"relative flex min-h-screen items-start justify-center px-4 pb-6 pt-0 sm:pt-2",style:{backgroundColor:"#02040A"},children:n.jsxs(ue.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${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(yt,{mode:"wait",children:e.status==="connected"&&b?n.jsx(ue.div,{...Xi,children:n.jsx(Ou,{onComplete:j})},"welcome-name"):y?n.jsx(ue.div,{...Xi,children:n.jsx(Eu,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(ue.div,{...Xi,children:n.jsx(Mu,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(I||e.status==="connected")&&n.jsxs(ue.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{delay:.15,duration:.35,ease:[.16,1,.3,1]},className:"mt-4 flex items-center justify-between rounded-xl border border-subtle bg-white/[0.025] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsxs("span",{className:"relative flex h-2 w-2",children:[N&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Ao[v]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Ao[v]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:zu(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Wu(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"})]})]}),f&&n.jsxs(ue.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.2,duration:.3},className:"mt-3 rounded-xl border border-[#7C7CFF]/25 bg-[#7C7CFF]/10 px-4 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#CFCBFF]",children:"Mission Control Tip"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-[#E6E4FF]",children:"Open Mission Control to see initiative → workstream → milestone → task flow with dependencies and recent todos in one expandable view."}),n.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[n.jsx("a",{href:"/orgx/live?view=mission-control",className:"rounded-full border border-[#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(qu,{compact:!0})})]})})}function Vu({children:e,color:t,pulse:s,title:r}){const i=t??M.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 Mi({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 v=I[0],N=I[I.length-1],f=document.activeElement;!j.shiftKey&&f===N?(j.preventDefault(),v.focus()):j.shiftKey&&f===v&&(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(yt,{children:e&&n.jsxs(ue.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(ue.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.24,ease:[.16,1,.3,1]},className:`glass-panel soft-shadow relative flex flex-col w-full ${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:M.cardBgElevated,borderColor:M.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:Nc.createPortal(p,document.body)}const Ku=[{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 Gu({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:Ku.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:oe("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(ue.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(ue.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:M.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:oe("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:M.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:oe("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function nr({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:oe("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Xu={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"},Qu="/orgx/live/",xn=e=>`${Qu.replace(/\/+$/,"/")}${e}`,Ju={pace:xn("brand/product-orchestrator.png"),eli:xn("brand/engineering-autopilot.png"),mark:xn("brand/launch-captain.png"),sage:xn("brand/pipeline-intelligence.png"),orion:xn("brand/control-tower.png"),dana:xn("brand/design-codex.png"),xandy:xn("brand/xandy-orchestrator.png"),nova:xn("brand/xandy-orchestrator.png"),openclaw:xn("brand/openclaw-mark.svg"),codex:xn("brand/openai-mark.svg"),openai:xn("brand/openai-mark.svg"),anthropic:xn("brand/anthropic-mark.svg"),orgx:xn("brand/orgx-logo.png")},Yu=[{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 Zu(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of Yu)if(s.test.test(t))return Ju[s.key];return null}function Qt({name:e,size:t="xs",hint:s,src:r}){const i=Dl(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:Zu(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Xu[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"}):ju(e)})}Qt.displayName="AgentAvatar";const em={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 Tn({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:oe("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",em[t],s),...r,children:e})}function tm(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||$s(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=Pl(e.status),c={id:e.workstreamId,label:e.workstreamTitle||$s(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||$s(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:$s(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function Ag(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||$s(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||$s(e.workstreamId,"Workstream"),type:"workstream",status:Pl(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||$s(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 $s(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function Pl(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 Ol(e){switch(e){case"done":return M.lime;case"active":return M.teal;case"blocked":return M.amber;case"failed":return M.red;default:return"rgba(255,255,255,0.15)"}}function nm(e){const t=Ol(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const sm=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(ue.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),rm=16,im=14,So=8,am=8,om=28,lm=24,cm=24,dm=20,Qi="rgba(255,255,255,0.07)";function um(e){const t=e?im:rm,s=t+am+4;return{iconSz:t,colW:s,rowH:e?cm:om,rowHTask:e?dm:lm}}function Bl({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}=um(i),I=x?y:j,v=e.children??[],N=v.filter(K=>K.type==="task"),f=v.filter(K=>K.type!=="task"),C=N.length>c&&!l,H=C?N.slice(0,c):N,Z=N.length-H.length,U=[...f,...H],fe=U.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:Qi,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:Qi,left:(t-1)*g+g/2,top:I/2,width:g}})]}),n.jsxs(ue.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${u?"rounded-md bg-white/[0.03]":""}`,style:{height: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:{...nm(e.status),width:So,height:So}}):n.jsx(vn,{type:e.type,size:b,accent:u?M.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(sm,{done:e.progress.done,total:e.progress.total,color:Ol(e.status)})})]})]}),fe&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Qi,left:t*g+g/2,top:I/2,height:I/2}}),fe&&n.jsxs("div",{children:[U.map((K,re)=>n.jsx(Bl,{node:K,depth:t+1,isLast:re===U.length-1&&!C,activeId:r,compact:i,index:a+re+1,taskLimit:c,expanded:l,onToggleExpand:d},K.id)),C&&n.jsxs(ue.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+U.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:["+",Z," more · see all"]}),n.jsx(yt,{children:l&&N.length>c&&n.jsx(ue.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 mm=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(Bl,{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))})}),ba={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"}},pm=Object.keys(ba);function _o(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of pm)if(t.includes(s))return s;return"engineering"}function Co(e){return ba[e]??ba.engineering}const Xs={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},kr={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Mo={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},To={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 ql(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=To[r];if(i){const a=kr[i]??"";return{name:i,domain:a,color:Xs[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,c]of Object.entries(Mo))if(r.includes(a)){const l=kr[c]??"";return{name:c,domain:l,color:Xs[c]??s.color,displayLabel:l?`${c} (${l})`:c}}}if(t){const r=t.trim();if(Xs[r]){const c=kr[r]??"";return{name:r,domain:c,color:Xs[r],displayLabel:c?`${r} (${c})`:r}}const i=r.toLowerCase(),a=To[i];if(a){const c=kr[a]??"";return{name:a,domain:c,color:Xs[a]??s.color,displayLabel:c?`${a} (${c})`:a}}for(const[c,l]of Object.entries(Mo))if(i.includes(c)){const d=kr[l]??"";return{name:l,domain:d,color:Xs[l]??s.color,displayLabel:d?`${l} (${d})`:l}}}return s}function Sg({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(Qt,{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 fm=new Set(["running","active","in_progress","working","planning","dispatching"]),hm=new Set(["running","dispatching"]),gm=3*6e4;function xm(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=gm:!1}function ym(e){const t=en(e.status??""),s=en(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:fm.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?xm(e.lastHeartbeatAt):!1}function zl(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function bm(e){const t=en(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 wm(e){const t=en(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 Wl(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 Ts(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 vi(e,t){if(!e)return t;const s=e.trim();return s?Vn(s)?`${t} ${xs(s)}`:s:t}const vm=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),km=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function jm(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?vm.has(t)||t.startsWith("telegram:"):!1}function Nm(e){if(!e)return!1;const t=e.trim();return t?km.some(s=>s.test(t)):!1}function Ul({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var x,b,g,j,y,I;const r=new Map;for(const v of s)v.id&&r.set(v.id,v.name??v.id);const i=new Map;for(const v of e){const N=(x=v.runId)==null?void 0:x.trim();!N||i.has(N)||i.set(N,v)}const a=new Map;for(const v of e){const N=((b=v.initiativeId)==null?void 0:b.trim())??"",f=((g=v.workstreamId)==null?void 0:g.trim())??"";if(!N||!f)continue;const C=`${N}:${f}`;a.has(C)||a.set(C,v)}const c=new Set;for(const v of e){const N=(j=v.runId)==null?void 0:j.trim();N&&c.add(N)}const l=[];for(const v of t){if(!hm.has(v.status))continue;const N=(v.runId??v.sliceRunId??"").trim();if(!N)continue;const f=Ts(v.initiativeIds,v.initiativeId),C=Ts(v.workstreamIds,v.workstreamId),H=f[0]??null,Z=C[0]??null,U=[];for(const ve of f)for(const Se of C)!ve||!Se||U.push(`${ve}:${Se}`);if(!(c.has(N)||U.some(ve=>a.has(ve))))continue;const K=i.get(N)??(U.length>0?U.map(ve=>a.get(ve)??null).find(ve=>!!ve)??null:null),re=H?r.get(H)??H:null,be=v.scopeProgress&&typeof v.scopeProgress.totalTasks=="number"&&v.scopeProgress.totalTasks>0?Math.round(v.scopeProgress.completedTasks/v.scopeProgress.totalTasks*100):null;l.push({key:`slice:${v.sliceRunId}`,source:"slice",session:K??null,runId:N,status:en(v.status),title:v.workstreamTitle??(K==null?void 0:K.title)??`Work slice ${v.sliceRunId.slice(0,8)}`,subtitle:v.statusExplainer??v.lastEventSummary??(K==null?void 0:K.lastEventSummary)??null,progress:be??(K==null?void 0:K.progress)??null,initiativeId:H,initiativeIds:f,initiativeTitle:re,workstreamId:Z,workstreamIds:C,iwmtId:v.iwmtId??null,iwmtIds:Ts(v.iwmtIds,v.iwmtId),workstreamTitle:v.workstreamTitle??(K==null?void 0:K.title)??null,taskIds:Array.isArray(v.taskIds)?v.taskIds:[],milestoneIds:Array.isArray(v.milestoneIds)?v.milestoneIds:[],artifactCount:v.artifactCount??0,decisionCount:v.blockingDecisionCount??v.decisionCount??0,updatedAt:v.updatedAt??v.lastEventAt??(K==null?void 0:K.updatedAt)??null,scope:v.scope,milestoneProgress:(y=v.scopeProgress)==null?void 0:y.milestones})}if(l.sort((v,N)=>Qr(N.updatedAt)-Qr(v.updatedAt)),l.length>0){const v=[],N=new Set;for(const f of l){const C=f.initiativeId??((I=f.initiativeIds)==null?void 0:I[0])??"none",Z=(f.workstreamId?`scope:${C}:${f.workstreamId}`:null)??(f.runId?`run:${f.runId}`:f.key);N.has(Z)||(N.add(Z),v.push(f))}return v}const d=e.filter(v=>{if(!ym(v))return!1;const N=(v.initiativeId??"").trim(),f=(v.workstreamId??"").trim();return N.length>0&&f.length>0});d.sort((v,N)=>{const f=Qr(v.updatedAt??v.lastEventAt??v.startedAt);return Qr(N.updatedAt??N.lastEventAt??N.startedAt)-f});const u=[],p=new Set;for(const v of d){const N=v.workstreamId&&v.workstreamId.trim().length>0?`${v.initiativeId??"none"}:${v.workstreamId}`:v.runId;p.has(N)||(p.add(N),u.push(v))}return u.map(v=>{var N;return{key:`session:${v.id}`,source:"session",session:v,runId:v.runId,status:en(v.status??""),title:v.title,subtitle:(N=v.lastEventSummary)!=null&&N.trim()?v.lastEventSummary.trim():null,progress:v.progress,initiativeId:v.initiativeId,initiativeIds:Ts(void 0,v.initiativeId),initiativeTitle:v.initiativeId?r.get(v.initiativeId)??v.groupLabel??null:v.groupLabel??null,workstreamId:v.workstreamId,workstreamIds:Ts(void 0,v.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:v.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:v.updatedAt??v.lastEventAt??v.startedAt??null}})}const Im=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:v}){const[N,f]=o.useState(null),[C,H]=o.useState(null),[Z,U]=o.useState(null),[fe,K]=o.useState(null),re=o.useMemo(()=>{const te=new Map;if(!Array.isArray(s))return te;for(const ie of s){const ke=Ts(ie.initiativeIds,ie.initiativeId),V=Ts(ie.workstreamIds,ie.workstreamId);for(const z of ke)for(const P of V){if(!z||!P)continue;const W=`${z}:${P}`;te.has(W)||te.set(W,ie)}const T=(ie.runId??ie.sliceRunId??"").trim();T&&!te.has(`run:${T}`)&&te.set(`run:${T}`,ie)}return te},[s]),be=o.useMemo(()=>Ul({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),ve=o.useMemo(()=>{const te=new Map;for(const ie of be){const ke=en(ie.status);te.set(ke,(te.get(ke)??0)+1)}return Array.from(te.entries()).sort((ie,ke)=>ke[1]-ie[1]).map(([ie,ke])=>({status:ie,count:ke}))},[be]),Se=o.useMemo(()=>N?be.filter(te=>en(te.status)===N):be,[N,be]),me=o.useMemo(()=>{var V,T;const te=new Map,ie=[];for(const z of Se){const P=(((V=z.initiativeIds)==null?void 0:V[0])??z.initiativeId??"").trim(),W=(((T=z.workstreamIds)==null?void 0:T[0])??z.workstreamId??"").trim();if(!P){ie.push(z);continue}let Q=te.get(P);Q||(Q={title:z.initiativeTitle??P,wsMap:new Map},te.set(P,Q));const xe=W||"__none__";let je=Q.wsMap.get(xe);je||(je={title:z.workstreamTitle??(W||"Unassigned"),rows:[],completedCount:0,lastActivity:null},Q.wsMap.set(xe,je));const ne=en(z.status);if(ne==="completed"||ne==="done"?je.completedCount+=1:je.rows.push(z),z.updatedAt){const ye=Date.parse(z.updatedAt),ge=je.lastActivity?Date.parse(je.lastActivity):0;Number.isFinite(ye)&&ye>ge&&(je.lastActivity=z.updatedAt)}}const ke=[];for(const[z,P]of te){const W=[];for(const[Q,xe]of P.wsMap)W.push({workstreamId:Q,workstreamTitle:xe.title,rows:xe.rows,completedCount:xe.completedCount,lastActivityAt:xe.lastActivity});W.sort((Q,xe)=>{const je=Q.lastActivityAt?Date.parse(Q.lastActivityAt):0;return(xe.lastActivityAt?Date.parse(xe.lastActivityAt):0)-je}),ke.push({initiativeId:z,initiativeTitle:P.title,workstreams:W})}return ke.sort((z,P)=>{const W=Math.max(0,...z.workstreams.map(xe=>xe.lastActivityAt?Date.parse(xe.lastActivityAt):0));return Math.max(0,...P.workstreams.map(xe=>xe.lastActivityAt?Date.parse(xe.lastActivityAt):0))-W}),{groups:ke,ungrouped:ie}},[Se]),[Ke,pe]=o.useState(new Set),ae=async(te,ie,ke)=>{if(te.session){K(null),H(te.session.id);try{await ie(te.session),K(ke)}catch(V){const T=V instanceof Error?V.message:"";K(T?Ut(T):"Workstream action failed")}finally{H(null)}}};return n.jsxs(nr,{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:()=>f(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:te,count:ie})=>n.jsxs("button",{type:"button",onClick:()=>f(ke=>ke===te?null:te),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${N===te?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[zl(te),n.jsx("span",{className:"tabular-nums opacity-70",children:ie})]},te))]}),fe&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:fe}),Se.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(ue.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[me.groups.map(te=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Zt(te.initiativeTitle&&!Vn(te.initiativeTitle)?te.initiativeTitle:vi(te.initiativeId,"Initiative"))}),te.workstreams.map(ie=>{var ne,ye;const ke=`${te.initiativeId}:${ie.workstreamId}`,V=Ke.has(ke),T=ie.rows[0]??null,z=T?ql((ne=T.session)==null?void 0:ne.agentId,(ye=T.session)==null?void 0:ye.agentName):null,P=T!=null&&T.milestoneProgress?T.milestoneProgress.reduce((ge,E)=>ge+E.total,0):null,W=T!=null&&T.milestoneProgress?T.milestoneProgress.reduce((ge,E)=>ge+E.done,0):null,Q=P&&P>0?`Task ${(W??0)+1} of ${P}`:null,xe=P&&P>0?Math.round((W??0)/P*100):(T==null?void 0:T.progress)!=null?Wl(T.progress):null,je=Zt(T!=null&&T.workstreamTitle&&!Vn(T.workstreamTitle)?T.workstreamTitle:vi(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:[z&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${z.color}20`,color:z.color},children:z.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:je,children:je}),z?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:z.color},title:z.displayLabel,children:z.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,xe??0)}%`,backgroundColor:(z==null?void 0:z.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:ie.rows.map((ge,E)=>n.jsx(Eo,{row:ge,index:E,sliceRunByScope:re,busySessionId:C,expandedRowKey:Z,setExpandedRowKey:U,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:g,onResumeWorkstream:j,onRestartSession:y,onPlayWorkstream:b,onIntervene:I,onOpenSliceDetail:v,runWorkstreamAction:ae,showInitiativeLabel:!1},ge.key))}),ie.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>pe(ge=>{const E=new Set(ge);return E.has(ke)?E.delete(ke):E.add(ke),E}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:V?`Hide ${ie.completedCount} completed`:`${ie.completedCount} completed`})})]},ie.workstreamId)})]},te.initiativeId)),me.ungrouped.length>0&&n.jsxs("div",{children:[me.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:me.ungrouped.map((te,ie)=>n.jsx(Eo,{row:te,index:ie,sliceRunByScope:re,busySessionId:C,expandedRowKey:Z,setExpandedRowKey:U,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:g,onResumeWorkstream:j,onRestartSession:y,onPlayWorkstream:b,onIntervene:I,onOpenSliceDetail:v,runWorkstreamAction:ae,showInitiativeLabel:!0},te.key))})]})]})})]})});function Eo({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,ke,V,T,z,P,W,Q,xe,je;const I=en(e.status??""),v=e.updatedAt,N=e.subtitle?e.subtitle:v?`Updated ${$t(v)}`:null,f=y&&(e.initiativeTitle||e.initiativeId)?Zt(e.initiativeTitle&&!Vn(e.initiativeTitle)?e.initiativeTitle:vi(e.initiativeId,"Initiative")):null,C=(ie=e.title)!=null&&ie.trim()?e.title:"",H=jm(C)&&((ke=e.workstreamTitle)!=null&&ke.trim())?e.workstreamTitle:C||e.workstreamTitle||"",Z=vi(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),U=Zt(H&&!Vn(H)?H:Z),fe=N&&!Nm(N)?Zt(N):null,K=Wl(e.progress),re=["running","active","in_progress","working","planning","dispatching"].includes(I),be=["paused","blocked","queued","pending"].includes(I),ve=p??x,Se=K===null&&["running","active","in_progress","working","planning","dispatching"].includes(I),me=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),te=ql((V=e.session)==null?void 0:V.agentId,(T=e.session)==null?void 0:T.agentName);return n.jsxs(ue.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:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.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 ${wm(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":te.color}:void 0,children:n.jsx(Qt,{name:((z=e.session)==null?void 0:z.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:[f?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:f}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(vn,{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:U,children:U})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Tn,{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] ${bm(I)}`,children:zl(I)}),v&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:Cc(new Date(v),{addSuffix:!0})})]}),fe?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:fe,children:fe}):null,null,(K!==null||Se)&&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:K===null?"Live":`${K}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${K===100?" shimmer-on-complete":""}`,children:K===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,K)}%`,background:`linear-gradient(90deg, ${Co(_o((W=e.session)==null?void 0:W.agentId)).gradient[0]}, ${Co(_o((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(mm,{nodes:tm({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((ne,ye)=>ne+ye.total,0),completedTasks:e.milestoneProgress.reduce((ne,ye)=>ne+ye.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((xe=e.session)==null?void 0:xe.agentName)??null,agentId:((je=e.session)==null?void 0:je.agentId)??null}),activeId:e.workstreamId,compact:!0})}),pe?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:ne=>{ne.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:ne=>ne.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&&re&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:me,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:me,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:me,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:me,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 Am={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 Ti({icon:e="inbox",headline:t,description:s,primaryAction:r,secondaryAction:i,className:a}){return n.jsxs(ue.div,{className:oe("flex flex-col items-center justify-center py-12 px-6 text-center max-w-md mx-auto",a),initial:"hidden",animate:"visible",variants:{visible:{transition:{staggerChildren:.04}}},children:[n.jsx(ue.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:Xr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:Am[e]})}),n.jsx(ue.h4,{className:"mt-5 text-heading font-semibold text-white",variants:Xr,custom:1,children:t}),n.jsx(ue.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:Xr,custom:2,children:s}),(r||i)&&n.jsxs(ue.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 Sm=new Set(["awaiting_input","needs_review","failed"]);function Ro(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function _m(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 Hl(e){const t=e.filter(r=>Sm.has(r.status)).sort((r,i)=>Ro(i.updatedAt??i.lastEventAt??"")-Ro(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=_m(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function Cm(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 Mm(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function Tm(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 Em(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 Rm(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 wa(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Vn(s)?`${t} ${xs(s)}`:s}function Lm(e){if(!e)return null;const t=Zt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function $m(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!Vn(r)){const a=Zt(r);if(a!=="Untitled session")return a}const i=Lm(e.statusExplainer);return i||(s?wa(s,"Workstream"):wa(e.sliceRunId,"Slice"))}const Dm=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(()=>Hl(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 v of I.workstreams??[])v.id&&(y.has(v.id)||y.set(v.id,v.name??v.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 v=(I=y.artifacts.find(N=>N.url))==null?void 0:I.url;if(v&&typeof window<"u"){window.open(v,"_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(nr,{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(Ti,{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},v)=>{var Se;const N=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,f=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,C=(N?b.get(N):null)??wa(N,"Initiative"),H=y.workstreamTitle??(f?g.get(f)??null:null),Z=$m(y,H,f),U=(Se=y.statusExplainer)!=null&&Se.trim().length?y.statusExplainer:"Review this slice to continue execution.",fe=Zt(Rm(y)),K=Zt(U),re=Zt(C),be=y.scope?y.scope.replace(/_/g," "):null,ve=y.updatedAt??y.lastEventAt??null;return n.jsxs(ue.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(v,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:me=>{(me.key==="Enter"||me.key===" ")&&(me.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 ${Tm(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(vn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:re})]}),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:Z,children:[n.jsx(vn,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:Z})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:fe,children:fe}),K!==fe&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:K,children:K})]}),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] ${Cm(y.status)}`,children:Mm(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:me=>me.stopPropagation(),children:y.decisionOptions.slice(0,3).map(me=>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:me.description??me.label,children:me.label},me.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:me=>me.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:Em(y)})]})]},y.sliceRunId)})})]})});function Fm(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Pm(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 Om(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Bm(e){return{id:e.id,name:e.title,status:Fm(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Pm(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 Lo=150,qm=12;function $o(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function zm(){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 Vl(e,t=null){return Os({queryKey:ys.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if(Xt())return zm();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<qm;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(Lo),offset:String(i)});r&&vs(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+=Lo}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}$o(d.updated_at??d.created_at)>$o(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=>Om(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(Bm)},enabled:e,staleTime:6e4})}const Jr=50,Do=8;function Wm(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Um(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Hm(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Vm(e){const t=Hm(e.sequence);return{id:e.id,name:e.title,status:Wm(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 Km(e,t=null){return Os({queryKey:ys.liveInitiatives({limit:Jr*Do,projectId:t}),queryFn:async()=>{var c;if(Xt())return[];const s=[];let r=0;for(let l=0;l<Do;l+=1){const d=new URLSearchParams({limit:String(Jr),offset:String(r)});t&&t.trim().length>0&&vs(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=>Um(l.status)).map(Vm)},enabled:e,staleTime:3e4})}const Kl=o.createContext(null);function Gm({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(Kl.Provider,{value:{state:t,open:r,close:i},children:e})}function Gl(){const e=o.useContext(Kl);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Xm(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:M.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]};if(t===0&&d===0)return{key:"idle-done",segments:[{text:`${i} done today`,color:M.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:M.textMuted,clickable:!0,onClick:c},{text:" · "},{text:`${r} decisions`,color:M.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:M.textMuted,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}}return r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:M.lime},{text:" · "}]:[],{text:`${r} decisions`,color:M.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:M.lime},{text:" · all systems go"}]}}function Fo(e){const{className:t}=e,{key:s,segments:r}=Xm(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(yt,{mode:"wait",children:n.jsx(ue.span,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.18,ease:[.22,1,.36,1]},className:"inline-flex flex-wrap items-baseline gap-0",children: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 _g={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"},Qm={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"},Cg=e=>Qm[en(e)]??"text-white/60 bg-white/5 border-white/10",Mg=e=>{const t=en(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"},Tg=e=>{const t=en(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"},Eg=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Rg=e=>{const t=en(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},Es=e=>{const t=en(e);return t==="blocked"||t==="failed"||t==="cancelled"?M.red:t==="active"||t==="in_progress"||t==="running"?M.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?M.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?M.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},ki={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:M.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:M.teal,tint:"rgba(20, 184, 166, 0.18)"}},Jm=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function hi(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)hi(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"?(Jm.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&hi(a,t,s+1,r):typeof a=="object"&&a!==null&&hi(a,t,s+1,r)}}}}function Ym(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 bs(...e){const t=[],s=new Set;for(const r of e)hi(r,t,0,s);for(const r of t){const i=Ym(r);if(i)return ki[i]}return ki.unknown}function Zm(e){return ki[e]??ki.unknown}const ep={xs:18,sm:24,md:30};function tp({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:Ci,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 sr({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=Zm(e),a=ep[t];return n.jsx("span",{className:oe("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(tp,{provider:e})})})}function Xl({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=ss(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const g=[];return e>0&&g.push({color:M.lime,fraction:e/c}),t>0&&g.push({color:M.red,fraction:t/c}),s>0&&g.push({color:M.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(ue.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 La(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function $a(e,t){if(typeof t=="number")return`${e}${t+1}`}const np=(e,t)=>{const s=La(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:$a("W",s)}},sp=(e,t)=>{const s=La(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:$a("M",s)}},rp=(e,t)=>{const s=La(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:$a("T",s)}};function Ji(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 ip(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 ap({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var l;const i=Cd(e),a=o.useMemo(()=>ys.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=Os({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Yr;if(Xt())return ip(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 v=>{try{const N=new URLSearchParams({type:v,initiative_id:e,limit:"100"}),f=await fetch(`/orgx/api/entities?${N.toString()}`,{headers:u});return f.ok?await f.json():{data:[]}}catch{return{data:[]}}},[x,b,g]=await Promise.all([p("workstream"),p("milestone"),p("task")]),j=Array.isArray(x.data)?Ji(x.data.map(v=>np(v,e))):[],y=Array.isArray(b.data)?Ji(b.data.map(v=>sp(v,e))):[],I=Array.isArray(g.data)?Ji(g.data.map(v=>rp(v,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 op(){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 Da({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return Os({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Xt())return op();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 jr(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:M.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:M.iris,bg:"rgba(124,124,255,0.10)"}}function lp(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function cp(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function dp({open:e,onClose:t,onLaunched:s}){var Q,xe,je,ne,ye,ge;const r=Da({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=Vl(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(""),[v,N]=o.useState(null),[f,C]=o.useState(null),[H,Z]=o.useState("starter"),[U,fe]=o.useState(!1),[K,re]=o.useState(1),be=Xt(),ve=o.useMemo(()=>{const E=l.trim();return E?(i==null?void 0:i.find(B=>B.id===E))??null:null},[i,l]),{details:Se}=ap({initiativeId:ve?ve.id:null,enabled:e&&!!ve}),me=o.useMemo(()=>lp(Se),[Se]),Ke=o.useMemo(()=>cp(Se,u||null),[Se,u]),pe=((Q=r.data)==null?void 0:Q.agents)??[],ae=o.useMemo(()=>{const E=a.trim();return E?pe.find(B=>B.id===E)??null:null},[pe,a]);o.useEffect(()=>{var B,G;if(!e)return;const E=((B=pe.find(se=>se.isDefault))==null?void 0:B.id)??((G=pe[0])==null?void 0:G.id)??"";!a&&E&&c(E)},[pe,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const E=i??[],B=E.length===1?E[0]:null;B&&d(B.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const E=(ae==null?void 0:ae.model)??"",B=E.includes("openrouter")?"openrouter":E.includes("anthropic")?"anthropic":E.includes("openai")?"openai":"auto";j(B)},[e,ae==null?void 0:ae.model,a]),o.useEffect(()=>{e&&(N(null),C(null),Z("starter"),re(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 te=!!a.trim()&&!!l.trim(),ie=K===1?!!a.trim():K===2?!!l.trim():te,ke=async()=>{var Ge;const E=(f==null?void 0:f.checkout)??"/orgx/api/billing/checkout",B=H&&H.trim().length>0?H.trim():"starter",se=await(await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:B,billingCycle:"monthly"})})).json().catch(()=>null),Re=((Ge=se==null?void 0:se.data)==null?void 0:Ge.url)??(se==null?void 0:se.url)??null;if(!Re)throw new Error((se==null?void 0:se.error)??"Checkout unavailable");window.open(Re,"_blank","noopener,noreferrer")},V=async()=>{var Re;const E=(f==null?void 0:f.portal)??"/orgx/api/billing/portal",G=await(await fetch(E,{method:"POST"})).json().catch(()=>null),se=((Re=G==null?void 0:G.data)==null?void 0:Re.url)??(G==null?void 0:G.url)??null;if(!se)throw new Error((G==null?void 0:G.error)??"Billing portal unavailable");window.open(se,"_blank","noopener,noreferrer")},T=async()=>{if(!(!te||U)){if(be){t(),s==null||s();return}N(null),C(null),fe(!0);try{const E={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},B=new URLSearchParams;B.set("agentId",E.agentId),B.set("initiativeId",E.initiativeId),E.initiativeTitle&&B.set("initiativeTitle",E.initiativeTitle),E.workstreamId&&B.set("workstreamId",E.workstreamId),E.taskId&&B.set("taskId",E.taskId),E.message&&B.set("message",E.message),E.provider&&B.set("provider",E.provider);const G=await fetch(`/orgx/api/agents/launch?${B.toString()}`,{method:"POST"}),se=await G.json().catch(()=>null);if(!G.ok||!(se!=null&&se.ok))throw(se==null?void 0:se.code)==="upgrade_required"&&(C(se.actions??null),Z(se.requiredPlan??"starter")),new Error((se==null?void 0:se.error)??`Launch failed (${G.status})`);t(),s==null||s()}catch(E){N(E instanceof Error?E.message:"Launch failed")}finally{fe(!1)}}},z=!!((xe=ae==null?void 0:ae.run)!=null&&xe.runId)&&!!((je=ae==null?void 0:ae.run)!=null&&je.pid),P=async()=>{var E;if(!(!((E=ae==null?void 0:ae.run)!=null&&E.runId)||!z||U)&&!be){N(null),fe(!0);try{const B=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(ae.run.runId)}`,{method:"POST"}),G=await B.json().catch(()=>null);if(!B.ok||!(G!=null&&G.ok))throw new Error((G==null?void 0:G.error)??`Stop failed (${B.status})`);await r.refetch()}catch(B){N(B instanceof Error?B.message:"Stop failed")}finally{fe(!1)}}},W=async()=>{var E;if(!(!((E=ae==null?void 0:ae.run)!=null&&E.runId)||U)){if(be){t(),s==null||s();return}N(null),fe(!0);try{const B=new URLSearchParams;B.set("runId",ae.run.runId),y.trim()&&B.set("message",y.trim()),g&&g!=="auto"&&B.set("provider",g);const G=await fetch(`/orgx/api/agents/restart?${B.toString()}`,{method:"POST"}),se=await G.json().catch(()=>null);if(!G.ok||!(se!=null&&se.ok))throw new Error((se==null?void 0:se.error)??`Restart failed (${G.status})`);t(),s==null||s()}catch(B){N(B instanceof Error?B.message:"Restart failed")}finally{fe(!1)}}};return e?n.jsx(Mi,{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(([E,B])=>n.jsxs("button",{type:"button",onClick:()=>re(E),className:oe("rounded-full px-3 py-1 transition-colors",K===E?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[E,". ",B]},E))})]}),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(yt,{mode:"wait",children:n.jsxs(ue.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.22,ease:[.16,1,.3,1]},className:"mt-3 space-y-4",children:[K===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:E=>c(E.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(E=>{const B=jr(E.status);return n.jsxs("option",{value:E.id,children:[E.name," (",E.id,") · ",B.label]},E.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:`${jr(ae.status).color}55`,color:jr(ae.status).color,backgroundColor:jr(ae.status).bg},children:jr(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"]}),((ne=ae.context)==null?void 0:ne.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:E=>j(E.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:!z||U,className:"rounded-lg border border-rose-300/25 bg-rose-400/10 px-3 py-2 text-caption font-semibold text-rose-100 transition-colors hover:bg-rose-400/20 disabled:opacity-45",children:"Stop Run"}),n.jsx("button",{type:"button",onClick:W,disabled:U,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"})]})]})]})]}),K===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:E=>d(E.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(E=>n.jsx("option",{value:E.id,children:E.name},E.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:E=>p(E.target.value),disabled:!ve,className:oe("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"}),me.map(E=>n.jsx("option",{value:E.id,children:E.name},E.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:E=>b(E.target.value),disabled:!ve,className:oe("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(E=>n.jsx("option",{value:E.id,children:E.title},E.id))]}),Ke.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),K===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:E=>I(E.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=me.find(E=>E.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()?((ge=Ke.find(E=>E.id===x))==null?void 0:ge.title)??x:"Any"})]})]})]})]})]},K)}),v&&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:v}),f&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void ke().catch(E=>N(E instanceof Error?E.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 V().catch(E=>N(E instanceof Error?E.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"}),f.pricing&&n.jsx("a",{href:f.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:K===1?"Pick an agent to configure.":K===2?"Select an initiative scope (required).":te?"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:[K>1&&n.jsx("button",{type:"button",onClick:()=>re(E=>E>1?E-1:E),disabled:U,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"}),K<3?n.jsx("button",{type:"button",onClick:()=>re(E=>E<3?E+1:E),disabled:!ie||U,className:oe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ie&&!U?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ie&&!U?{backgroundColor:M.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:T,disabled:!te||U,className:oe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",te&&!U?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:te&&!U?{backgroundColor:M.lime}:void 0,children:U?"Launching…":"Launch"})]})]})]})}):null}function up({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(vn,{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 Yi=10,mp=20;function pp(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:M.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:M.iris,bg:"rgba(124,124,255,0.10)"}}function fp(e){return e?e.includes("error")||e.includes("fail")?M.red:e.includes("decision")||e.includes("block")?M.amber:e.includes("complete")||e.includes("success")?M.teal:e.includes("start")||e.includes("launch")?M.lime:M.iris:M.iris}const hp={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 gp(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function xp({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var re,be,ve,Se,me,Ke;const[d,u]=o.useState(!1),[p,x]=o.useState(!1),[b,g]=o.useState(null),j=ya(s),y=pp((r==null?void 0:r.status)??null),I=Dl(s),v=o.useMemo(()=>{let pe=0,ae=0,te=0,ie=0;for(const ke of i)ke.status==="running"||ke.status==="queued"||ke.status==="pending"?pe++:ke.status==="blocked"?ae++:ke.status==="failed"||ke.status==="cancelled"?te++:(ke.status==="completed"||ke.status==="archived")&&ie++;return{running:pe,blocked:ae,failed:te,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]),f=d?N:N.slice(0,Yi),C=N.length>Yi,H=o.useMemo(()=>[...a].sort((pe,ae)=>Date.parse(ae.timestamp)-Date.parse(pe.timestamp)).slice(0,mp),[a]),Z=!!((re=r==null?void 0:r.run)!=null&&re.runId)&&!!((be=r==null?void 0:r.run)!=null&&be.pid),U=async()=>{var pe;if(!(!((pe=r==null?void 0:r.run)!=null&&pe.runId)||!Z||p)){g(null),x(!0);try{const ae=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),te=await ae.json().catch(()=>null);if(!ae.ok||!(te!=null&&te.ok))throw new Error((te==null?void 0:te.error)??`Stop failed (${ae.status})`);l==null||l()}catch(ae){g(ae instanceof Error?ae.message:"Stop failed")}finally{x(!1)}}},fe=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 te=await fetch(`/orgx/api/agents/restart?${ae.toString()}`,{method:"POST"}),ie=await te.json().catch(()=>null);if(!te.ok||!(ie!=null&&ie.ok))throw new Error((ie==null?void 0:ie.error)??`Restart failed (${te.status})`);l==null||l()}catch(ae){g(ae instanceof Error?ae.message:"Restart failed")}finally{x(!1)}}};if(!e)return null;const K=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:U,disabled:!Z||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:fe,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(Mi,{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(up,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:K,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(ue.div,{className:"flex items-start gap-5",variants:hp,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(Xl,{running:v.running,blocked:v.blocked+v.failed,paused:0,size:72,children:n.jsx(Qt,{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(ue.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:v.running,color:M.lime},{label:"Blocked",value:v.blocked,color:M.red},{label:"Failed",value:v.failed,color:M.amber},{label:"Completed",value:v.completed,color:M.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(ue.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:[f.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:Es(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-Yi} older sessions`})]})]}),n.jsxs(ue.div,{variants:Zr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),H.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:H.map((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:fp(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(gp,{}),r&&n.jsxs(ue.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":(Se=r.model)!=null&&Se.includes("anthropic")?"Anthropic":(me=r.model)!=null&&me.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:oe("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,Po=10,yp=24,Oo=520,bp=58,wp=56,vp=20,kp=8,Fa=new Set(["running","active","in_progress","working","planning","handoff","review"]),jp=new Set(["blocked","failed"]),Np=10,Ip=[{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"}],Ap=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,va=[{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 ot(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function bn(e,t){const s=ot(e),r=ot(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of va)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Sp(e){const t=bn(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=bn(null,r);if(i)return i}return null}function _p(e){const t=ot(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 Ql(e){const t=Sp(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=ot(e.agentId),r=ot(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=_p(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 Cp(e){const t=Ql(e),s=ot(t.agentId);if(s)return`id:${s}`;const r=ot(t.agentName);return r?`name:${r}`:"unassigned"}function Mp(e){const t=e.trim();return t?Ap.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function ji(e){const t=(e??"").trim();return t?Bs(t):!1}function Tp(e){var t,s;return!!(ji((t=e.context)==null?void 0:t.initiativeId)||ji(((s=e.run)==null?void 0:s.initiativeId)??null))}function ti(e){if(bn(e.agentId,e.agentName))return!0;const s=ot(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function yn(e){const t=ot(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=ot(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=ot(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":Fa.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function ka(e){const t=ot(e);return t?Fa.has(t)||jp.has(t):!1}function Bo(e){const t=ot(e);return t?Fa.has(t):!1}function Qs(e){return e?!!(ka(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function Ep(e){return e?e.state==="active":!1}function Rp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function En(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ni(e,t){return En(t.updatedAt??t.lastEventAt??t.startedAt)-En(e.updatedAt??e.lastEventAt??e.startedAt)}function Lp({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=Es(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(ue.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(yt,{children:i&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden pl-4",children:t.map((d,u)=>{const p=r===d.id,x=bs(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(ue.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(u*.02,.1)},className:oe("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(sr,{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 $p=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 kt;const[j,y]=o.useState(new Set),[I,v]=o.useState(!1),[N,f]=o.useState(!1),[C,H]=o.useState(0),[Z,U]=o.useState(null),[fe,K]=o.useState(!1),re=Da({enabled:!0}),be=((kt=re.data)==null?void 0:kt.agents)??[],ve=o.useMemo(()=>Fr(a),[a]),Se=o.useMemo(()=>ve===null?s:s.filter(O=>En(O.timestamp)>=ve),[s,ve]);o.useMemo(()=>{var he,Me,Qe;const O=new Map,_e=[...Se].sort((nt,J)=>En(J.timestamp)-En(nt.timestamp));for(const nt of _e){const J=nt.runId;if(!J||O.has(J))continue;const ze=((he=nt.summary)==null?void 0:he.trim())??((Me=nt.description)==null?void 0:Me.trim())??((Qe=nt.title)==null?void 0:Qe.trim())??"";ze.length>0&&O.set(J,ze)}return O},[Se]);const{agents:me,hiddenGroupCount:Ke,filteredOutGroupsByDate:pe,filteredOutSessionsByDate:ae,visibleSessionCount:te,archivedGroups:ie,sessionCountInScope:ke}=o.useMemo(()=>{var Dt;const O=b?t.nodes:t.nodes.filter(q=>!ji(q.initiativeId)),_e=b?be:be.filter(q=>!Tp(q)),he=b?x:x.filter(q=>!ji(q.initiativeId)),Me=new Map,Qe=new Map,nt=[...he].sort((q,Ie)=>En(Ie.lastEventAt??Ie.lastHeartbeatAt)-En(q.lastEventAt??q.lastHeartbeatAt));for(const q of nt){q.runId&&!Me.has(q.runId)&&Me.set(q.runId,q);const Ie=bn(q.agentId,q.agentName??q.displayName),Ue=ot((Ie==null?void 0:Ie.agentId)??q.agentId);if(Ue){const Ve=Qe.get(Ue)??[];Ve.push(q),Qe.set(Ue,Ve)}}const J=new Map;for(const q of O){const Ie=Ql(q),Ue=Cp(q),Ve=ot(Ie.agentId),qe=ot(Ie.agentName);let Be=J.get(Ue)??null;if(!Be&&Ve&&qe){const Pe=`name:${qe}`,mt=J.get(Pe);mt&&(J.delete(Pe),mt.groupKey=Ue,J.set(Ue,mt),Be=mt)}if(!Be&&qe){const Pe=Array.from(J.values()).find(mt=>ot(mt.agentName)===qe);Pe&&(Be=Pe)}Be?(Be.nodes.push(q),!Be.agentId&&Ie.agentId&&(Be.agentId=Ie.agentId),(Be.agentName==="OrgX"||!Be.agentName)&&Ie.agentName&&(Be.agentName=Ie.agentName)):J.set(Ue,{groupKey:Ue,agentId:Ie.agentId,agentName:Ie.agentName??Ie.agentId??"OrgX",nodes:[q],latest:q,runtime:null,runtimeActiveCount:0})}for(const q of _e){const Ie=bn(q.id,q.name),Ue=(Ie==null?void 0:Ie.agentId)??q.id,Ve=(Ie==null?void 0:Ie.agentName)??q.name,qe=ot(Ue),Be=ot(Ve),Pe=qe?`id:${qe}`:null,mt=Be?`name:${Be}`:null;let Ft=null;if(Pe&&J.has(Pe))Ft=Pe;else if(mt&&J.has(mt))Ft=mt;else{const pt=Array.from(J.entries()).find(([,gt])=>qe&&ot(gt.agentId)===qe||Be&&ot(gt.agentName)===Be);Ft=(pt==null?void 0:pt[0])??null}if(Ft){const pt=J.get(Ft);pt.catalogAgent=q,!pt.agentId&&Ue&&(pt.agentId=Ue),(pt.agentName==="OrgX"||!pt.agentName)&&Ve&&(pt.agentName=Ve),Pe&&pt.groupKey!==Pe&&!J.has(Pe)&&(J.delete(pt.groupKey),pt.groupKey=Pe,J.set(Pe,pt))}else{const pt=Pe??mt??`catalog:${Ve.toLowerCase()}`;J.set(pt,{groupKey:pt,agentId:Ue,agentName:Ve,nodes:[],latest:null,catalogAgent:q,runtime:null,runtimeActiveCount:0})}}for(const q of va){const Ie=`orgx:${q.id}`,Ue=`id:${Ie}`;let Ve=J.get(Ue)??null;if(!Ve){const qe=Array.from(J.entries()).find(([,Be])=>{const Pe=bn(Be.agentId,Be.agentName);return ot(Pe==null?void 0:Pe.agentId)===ot(Ie)});qe&&(J.delete(qe[0]),Ve=qe[1],Ve.groupKey=Ue,J.set(Ue,Ve))}if(Ve||(Ve={groupKey:Ue,agentId:Ie,agentName:q.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},J.set(Ue,Ve)),Ve.agentId=Ie,Ve.agentName=q.name,!Ve.catalogAgent){const qe=_e.find(Be=>{const Pe=bn(Be.id,Be.name);return ot(Pe==null?void 0:Pe.agentId)===ot(Ie)});qe&&(Ve.catalogAgent=qe)}}const ze=new Map(va.map((q,Ie)=>[ot(`orgx:${q.id}`),Ie]));for(const q of J.values()){q.nodes.length>0&&(q.nodes.sort(ni),q.latest=q.nodes[0]);const Ie=[],Ue=new Set;if((Dt=q.latest)!=null&&Dt.runId){const qe=Me.get(q.latest.runId);qe&&!Ue.has(qe.id)&&(Ie.push(qe),Ue.add(qe.id))}for(const qe of q.nodes){if(!qe.runId)continue;const Be=Me.get(qe.runId);Be&&!Ue.has(Be.id)&&(Ie.push(Be),Ue.add(Be.id))}const Ve=ot(q.agentId);if(Ve)for(const qe of Qe.get(Ve)??[])Ue.has(qe.id)||(Ie.push(qe),Ue.add(qe.id));Ie.sort((qe,Be)=>En(Be.lastEventAt??Be.lastHeartbeatAt)-En(qe.lastEventAt??qe.lastHeartbeatAt)),q.runtime=Ie[0]??null,q.runtimeActiveCount=Ie.filter(qe=>Ep(qe)).length}const we=Array.from(J.values()).sort((q,Ie)=>{const Ue=ti(q),Ve=ti(Ie);if(Ue!==Ve)return Ue?-1:1;if(Ue&&Ve){const qe=q.nodes.length>0||(q.runtimeActiveCount??0)>0,Be=Ie.nodes.length>0||(Ie.runtimeActiveCount??0)>0;if(qe!==Be)return qe?-1:1;if(qe&&Be){if(q.latest&&Ie.latest)return ni(q.latest,Ie.latest);if(q.latest&&!Ie.latest)return-1;if(!q.latest&&Ie.latest)return 1}const Pe=bn(q.agentId,q.agentName),mt=bn(Ie.agentId,Ie.agentName),Ft=ze.get(ot((Pe==null?void 0:Pe.agentId)??q.agentId))??999,pt=ze.get(ot((mt==null?void 0:mt.agentId)??Ie.agentId))??999;if(Ft!==pt)return Ft-pt}return q.latest&&Ie.latest?ni(q.latest,Ie.latest):q.latest&&!Ie.latest?-1:!q.latest&&Ie.latest?1:q.agentName.localeCompare(Ie.agentName)}),X=Ml(a),$e=X.id==="live",He=X.minutes===null||$e?null:Date.now()-X.minutes*6e4,De=[],rt=[];let ut=0,_t=0;for(const q of we){const Ie=(q.runtimeActiveCount??0)>0,Ue=ti(q);if(q.nodes.length===0){const Pe=Qs(q.catalogAgent);(Ue||$e&&(Pe||Ie))&&De.push(q);continue}if($e){const Pe=q.nodes.filter(pt=>ka(yn(pt))),mt=q.nodes.filter(pt=>!ka(yn(pt))),Ft=Qs(q.catalogAgent);if(Pe.length===0){Ue||Ft||Ie?De.push({...q,nodes:[],latest:null}):(ut+=1,_t+=q.nodes.length,rt.push(q));continue}_t+=mt.length,mt.length>0&&rt.push({...q,nodes:mt,latest:mt[0]??null}),De.push({...q,nodes:Pe,latest:Pe[0]??null});continue}if(He===null){De.push(q);continue}const Ve=q.nodes.filter(Pe=>Bo(yn(Pe))?!0:En(Pe.updatedAt??Pe.lastEventAt??Pe.startedAt)>=He),qe=Qs(q.catalogAgent);if(Ve.length===0){Ue||qe||Ie?De.push({...q,nodes:[],latest:null}):(ut+=1,_t+=q.nodes.length,rt.push(q));continue}const Be=q.nodes.filter(Pe=>Bo(yn(Pe))?!1:En(Pe.updatedAt??Pe.lastEventAt??Pe.startedAt)<He);_t+=Be.length,Be.length>0&&rt.push({...q,nodes:Be,latest:Be[0]}),De.push({...q,nodes:Ve,latest:Ve[0]})}return{agents:De.slice(0,ei),hiddenGroupCount:Math.max(0,De.length-ei),filteredOutGroupsByDate:ut,filteredOutSessionsByDate:_t,visibleSessionCount:De.slice(0,ei).reduce((q,Ie)=>q+Ie.nodes.length,0),archivedGroups:rt,sessionCountInScope:O.length}},[a,t.nodes,be,x,b]);o.useEffect(()=>{f(!1),H(0)},[a]);const V=o.useMemo(()=>ie.reduce((O,_e)=>O+_e.nodes.length,0),[ie]),T=o.useMemo(()=>me.filter(O=>O.nodes.length>0).map(O=>O.groupKey),[me]),{activeAgents:z,idleOrgxAgents:P,activeAgentCount:W}=o.useMemo(()=>{const O=[],_e=[];for(const he of me)he.nodes.length>0||(he.runtimeActiveCount??0)>0||Qs(he.catalogAgent)?O.push(he):ti(he)?_e.push(he):O.push(he);return{activeAgents:O,idleOrgxAgents:_e,activeAgentCount:O.filter(he=>he.nodes.length>0||(he.runtimeActiveCount??0)>0||Qs(he.catalogAgent)).length}},[me]),Q=o.useMemo(()=>{if(T.length===0)return{allCollapsed:!1,allExpanded:!0};let O=0;for(const _e of T)j.has(_e)&&(O+=1);return{allCollapsed:O===T.length,allExpanded:O===0}},[j,T]),xe=o.useMemo(()=>{const O=[];for(const _e of ie)for(const he of _e.nodes)O.push({node:he,agentName:_e.agentName});return O.sort((_e,he)=>ni(_e.node,he.node)),O.slice(0,(C+1)*Np)},[ie,C]),je=O=>{y(_e=>{const he=new Set(_e);return he.has(O)?he.delete(O):he.add(O),he})},ne=()=>{y(()=>Q.allCollapsed?new Set:new Set(T))},ye=o.useMemo(()=>Z?me.find(O=>O.groupKey===Z)??null:null,[me,Z]),ge=o.useMemo(()=>(ye==null?void 0:ye.nodes)??[],[ye]),E=o.useMemo(()=>{if(!ye)return[];const O=ot(ye.agentName),_e=ot(ye.agentId),he=bn(ye.agentId,ye.agentName);return Se.filter(Me=>{const Qe=ot(Me.agentName),nt=ot(Me.agentId),J=bn(Me.agentId,Me.agentName);return O!==null&&Qe===O||_e!==null&&nt===_e||he!==null&&J!==null&&ot(he.agentId)===ot(J.agentId)})},[Se,ye]),B=ke===0,G=be.length>0,se=o.useRef(null),[Re,Ge]=o.useState(0),[Te,L]=o.useState(0),at=o.useCallback(O=>{const _e=O.currentTarget.scrollTop;Ge(he=>Math.abs(he-_e)<1?he:_e)},[]);o.useEffect(()=>{const O=se.current;if(!O)return;const _e=()=>{const he=O.clientHeight,Me=O.scrollTop;L(Qe=>Qe===he?Qe:he),Ge(Qe=>Math.abs(Qe-Me)<1?Qe:Me)};if(_e(),typeof ResizeObserver<"u"){const he=new ResizeObserver(()=>_e());return he.observe(O),()=>he.disconnect()}return window.addEventListener("resize",_e),()=>window.removeEventListener("resize",_e)},[z.length]);const{visibleAgentGroups:Le,topVirtualSpacerPx:Xe,bottomVirtualSpacerPx:bt,virtualizationEnabled:vt}=o.useMemo(()=>{if(!(z.length>yp&&Te>0))return{visibleAgentGroups:z,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const _e=z.map(we=>{const $e=j.has(we.groupKey)?0:Math.min(we.nodes.length,Po);let He=bp;return $e>0&&(He+=vp+$e*wp,we.nodes.length>$e&&(He+=20)),He+kp}),he=new Array(_e.length+1).fill(0);for(let we=0;we<_e.length;we+=1)he[we+1]=he[we]+_e[we];const Me=he[he.length-1],Qe=Math.max(0,Re-Oo),nt=Re+Te+Oo;let J=0;for(;J<z.length&&he[J+1]<Qe;)J+=1;let ze=J;for(;ze<z.length&&he[ze]<nt;)ze+=1;return ze<=J&&(ze=Math.min(z.length,J+1)),{visibleAgentGroups:z.slice(J,ze),topVirtualSpacerPx:he[J],bottomVirtualSpacerPx:Math.max(0,Me-he[ze]),virtualizationEnabled:!0}},[z,j,Re,Te]);return n.jsxs(nr,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(dp,{open:I,onClose:()=>v(!1),onLaunched:()=>{re.refetch(),u==null||u()}}),n.jsx(xp,{open:Z!==null,onClose:()=>U(null),agentName:(ye==null?void 0:ye.agentName)??"",catalogAgent:(ye==null?void 0:ye.catalogAgent)??null,sessions:ge,activity:E,onSelectSession:i,onRefresh:()=>re.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[W," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:ne,disabled:T.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:()=>v(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:se,onScroll:at,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[me.length===0&&!B&&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."})]}),me.length===0&&B&&!d&&n.jsx(Ti,{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:[vt&&Xe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Xe}}),Le.map(O=>{var pt;const _e=O.groupKey,he=j.has(_e),Me=O.latest,Qe=Me?yn(Me):null,nt=(g==null?void 0:g.activeRunId)!=null&&(Me==null?void 0:Me.runId)!=null&&g.activeRunId===Me.runId,J=nt&&(g==null?void 0:g.state)==="running"?"running":Qe,ze=nt&&(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=Qs(O.catalogAgent),He=O.runtime??null,De=(O.runtimeActiveCount??0)>0,rt=!we&&De&&He!==null,ut=we||rt,_t=Me?r===Me.id:!1,Dt=O.agentName||((pt=O.catalogAgent)==null?void 0:pt.name)||O.agentId||"OrgX",q=bn(O.agentId,Dt),Ie=(q==null?void 0:q.agentName)??Mp(Dt),Ue=(q==null?void 0:q.role)??ya(Ie),Ve=bs(O.agentId,Ie,He==null?void 0:He.displayName,Me==null?void 0:Me.runtimeProvider,Me==null?void 0:Me.runtimeClient),qe=q===null&&(Ve.id==="codex"||Ve.id==="openai"||Ve.id==="anthropic"||Ve.id==="openclaw"),Be=Ue?`${Dt} — ${Ue}`:Dt,Pe=he?[]:we?O.nodes.slice(0,Po):[],mt=Math.max(0,we?O.nodes.length-Pe.length:0),Ft=ot(l)===ot(Ie)||ot(l)===ot(Be);return n.jsxs(ue.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:oe("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",_t&&"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):rt?je(_e):!we&&$e?U(_e):c?c(Ft?null:Ie):Me&&i(Me.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:[qe?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(sr,{provider:Ve.id,size:"sm",showRing:!1})}):n.jsx(Xl,{running:O.nodes.filter(gt=>{const At=yn(gt);return At==="running"||At==="handoff"||At==="review"}).length,blocked:O.nodes.filter(gt=>{const At=yn(gt);return At==="blocked"||At==="failed"}).length,paused:O.nodes.filter(gt=>{const At=yn(gt);return At==="paused"||At==="cancelled"}).length,size:36,children:n.jsx(Qt,{name:Ie,size:"sm",hint:`${O.agentId??""} ${Ie}`})}),q&&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"})}),Me&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Es(J??Me.status),borderColor:M.cardBg}}),!Me&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:$e?Es("running"):"rgba(255,255,255,0.2)",borderColor:M.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:[Ie,Ue&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Ue]})]})}),ze&&n.jsx("p",{className:"truncate text-micro text-teal-400",title:ze,children:ze}),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 gt={};for(const At of O.nodes){const st=yn(At);gt[st]=(gt[st]??0)+1}return Object.entries(gt).map(([At,st])=>`${st} ${At}`).join(" · ")})(),children:(()=>{const gt={};for(const st of O.nodes){const Pt=yn(st);gt[Pt]=(gt[Pt]??0)+1}const At=O.nodes.length;return Object.entries(gt).map(([st,Pt])=>n.jsx("span",{style:{width:`${Pt/At*100}%`,backgroundColor:Es(st)}},st))})()}),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:Es("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:()=>U(_e),"aria-label":`View ${Ie} 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:()=>{ut&&je(_e)},disabled:!ut,"aria-label":ut?he?"Expand sessions":"Collapse sessions":"No sessions to expand",className:oe("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",ut?"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:oe("transition-transform",ut&&!he?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(yt,{initial:!1,children:ut&&!he&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsxs("div",{className:"max-h-[500px] space-y-1.5 overflow-y-auto p-2",children:[(()=>{const gt=new Map,At=[];for(const Ye of Pe){const zt=yn(Ye);if(zt==="blocked"||zt==="paused"||zt==="failed"){const Ct=`${zt}:${Ye.blockerReason??""}`,St=gt.get(Ct)??[];St.push(Ye),gt.set(Ct,St)}else At.push(Ye)}const st=[];for(const[Ye,zt]of gt)zt.length>3?st.push({status:Ye.split(":")[0],nodes:zt}):At.push(...zt);const Pt=(Ye,zt)=>{const Ct=r===Ye.id,St=yn(Ye),Ht=bs(Ye.agentName,Ye.title,Ye.lastEventSummary,Ye);return n.jsx(ue.button,{onClick:()=>i(Ye.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(zt*.015,.12)},className:oe("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Ct?"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(sr,{provider:Ht.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Ye.title,children:Ye.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:Ht.accent},children:Ht.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:St}),n.jsx("span",{title:yi(Ye.updatedAt??Ye.lastEventAt??Ye.startedAt??Date.now()),children:$t(Ye.updatedAt??Ye.lastEventAt??Ye.startedAt??Date.now())})]}),Ye.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(Ye.progress)}%`,background:`linear-gradient(90deg, ${M.lime}, ${M.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:Es(St)},"aria-label":St,title:St})]})},Ye.id)};return n.jsxs(n.Fragment,{children:[At.map((Ye,zt)=>Pt(Ye,zt)),st.map(Ye=>n.jsx(Lp,{status:Ye.status,nodes:Ye.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Ye.status}-${Ye.nodes.length}`))]})})(),mt>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",mt," older sessions hidden"]})]})})})]},_e)}),vt&&bt>0&&n.jsx("div",{"aria-hidden":"true",style:{height:bt}})]}),P.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>K(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:oe("transition-transform",fe?"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(yt,{initial:!1,children:fe&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsx("div",{className:"space-y-1 p-2",children:P.map(O=>{const _e=bn(O.agentId,O.agentName),he=(_e==null?void 0:_e.agentName)??O.agentName,Me=(_e==null?void 0:_e.role)??ya(he);return n.jsxs("button",{type:"button",onClick:()=>U(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(Qt,{name:he,size:"sm",hint:`${O.agentId??""} ${he}`}),_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:[he,Me&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Me]})]})}),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:Ip.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:()=>{f(O=>!O),N&&H(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:oe("transition-transform",N?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[V," archived session",V===1?"":"s",pe>0?` across ${pe} agent${pe===1?"":"s"}`:""]})]}),n.jsx(yt,{initial:!1,children:N&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[xe.map(({node:O,agentName:_e})=>{const he=yn(O),Me=O.runtimeProvider?{id:Rp(O.runtimeProvider)}:bs(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(sr,{provider:Me.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:yi(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:he})]})]},O.id)}),xe.length<V&&n.jsxs("button",{onClick:()=>H(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 (",V-xe.length," remaining)"]})]})})})]})]})]})}),Dp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Fp=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),Pp=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),Op=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Bp=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function Js(e){return e?en(e):""}function Zi(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function qp(e){return e.some(t=>Dp.has(t))}function zp(e){return e.some(t=>Fp.has(t))}function Wp(e){return e.some(t=>Pp.has(t))}function Up(e){return e.some(t=>Op.has(t))}function Hp(e){return e.some(t=>Bp.has(t))}function Zn(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 Vp(e){const t=Js(e.sessionStatus),s=Js(e.sessionPhase),r=Js(e.sessionState),i=Js(e.sliceStatus),a=Js(e.activityStatus),c=Js(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(C=>C.length>0),u=Zi(e.blockingDecisionCount),p=Zi(e.nonBlockingDecisionCount),x=Zi(e.blockerCount),b=l==="run_failed",g=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",j=b||qp(d),y=zp(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,I=Wp(d)||x>0,v=g||Up(d),N=Hp(d)||l==="run_started";if(j)return Zn("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(v&&!y&&!j&&x===0&&!e.blockerReason)return p>0?Zn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Zn("completed","Execution completed successfully.",{tone:"positive"});if(y||I)return u>0||e.decisionRequired===!0||l==="decision_requested"?Zn("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Zn("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:I?"critical":"warning"});if(v)return p>0?Zn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Zn("completed","Execution completed successfully.",{tone:"positive"});if(N){const C=p>0?`Running with ${p} optional decision${p===1?"":"s"} available.`:"Running.";return Zn("in_progress",C,{tone:"neutral"})}return Zn("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const ea=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Kp(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Rs(e,t){const s=[];let r=0,i=0;ea.lastIndex=0;for(let a=ea.exec(e);a;a=ea.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&&Kp(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 Gp(e,t){const s=e.split(`
204
+ `),r=[];return s.forEach((i,a)=>{r.push(...Rs(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function gi(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Xp(e){const t=gi(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Qp(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function Jp(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("|")&&Xp(l)){const b=gi(i),j=gi(l).map(I=>Qp(I));r+=2;const y=[];for(;r<t.length;){const I=t[r]??"";if(!I.trim()||!I.includes("|"))break;y.push(gi(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,v)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:j[v]??"left"},children:Rs(I,`tbl-h-${r}-${v}`)},`tbl-h-${v}`))})}),n.jsx("tbody",{children:y.map((I,v)=>n.jsx("tr",{className:v<y.length-1?"border-b border-subtle":void 0,children:b.map((N,f)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:j[f]??"left"},children:Rs(I[f]??"",`tbl-r-${r}-${v}-${f}`)},`tbl-r-${v}-c-${f}`))},`tbl-r-${v}`))})]})},`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:oe("tracking-[-0.01em] text-white",j),children:Rs(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:Rs(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:Rs(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:Gp(x.join(`
208
+ `),`p-${r}`)},`p-${r}`))}return s}function Tr({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:Rs(r,"inline")}):n.jsx("div",{className:oe("space-y-2",s),children:Jp(r)}):null}function Jl(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yp(e){if(!e)return;const t=Jl(e.metadata);return t?{...e,...t}:e}const Yl={run_started:{icon:"play",label:"Run started",color:M.teal},run_completed:{icon:"check_circle",label:"Run completed",color:M.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:M.red},artifact_created:{icon:"file",label:"Artifact",color:M.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:M.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:M.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:M.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:M.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:M.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:M.red},milestone_completed:{icon:"flag",label:"Milestone",color:M.cyan},delegation:{icon:"workflow",label:"Delegation",color:M.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 ja(e){return e?e.toLowerCase():""}function Zp(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 ef(e,t){const s=ja(Hn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:M.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:M.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:M.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:M.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:M.cyan}:Yl.artifact_created}function tf(e){const t=Yp(Jl(e.metadata)),s=Zp(e,t),r=ja(Hn(t,["source"])),i=ja(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:M.teal};if(a==="auto_continue_stopped"){const l=Hn(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Needs attention",color:M.red}:l==="budget_exhausted"?{icon:"infinity",label:"Paused",color:M.amber}:{icon:"infinity",label:"Paused",color:M.amber}}if(a==="autopilot_transition"){const l=Hn(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Needs attention",color:M.red}:{icon:"infinity",label:"In progress",color:M.teal}}const c=Hn(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Completed",color:M.lime}:c==="blocked"||c==="needs_decision"?{icon:"infinity",label:"Needs attention",color:M.amber}:{icon:"infinity",label:"In progress",color:M.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:M.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:M.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:M.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:M.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:M.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:M.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:M.teal};if(e.type==="artifact_created")return ef(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:M.red}:{icon:"shield_check",label:"Decision approved",color:M.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:M.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:M.teal}}return Yl[e.type]??{icon:"message",label:"Activity",color:M.textMuted}}function nf({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(Fl,{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 Ni(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Na(e){if(!e)return;const t=Ni(e.metadata);return t?{...e,...t}:e}function sf(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function rf(e){let t=0;for(const s of e){const r=Na(Ni(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 af=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(()=>rf(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,v=null;for(const f of d){const C=Na(Ni(f.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),!v&&typeof C.kickoff_context_hash=="string"&&(v=C.kickoff_context_hash),g&&(j||y)&&I&&v))break}return!(g||j||y||I||v)?null:{domain:g,provider:j,model:y,modelTier:I,kickoffContextHash:v}},[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:M.lime,boxShadow:`0 0 12px ${M.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:lt(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(Qt,{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:lt(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"?`${M.lime}20`:s.status==="failed"?`${M.red}20`:`${M.teal}20`,color:s.status==="running"?M.lime:s.status==="failed"?M.red:M.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?`${lt(x.provider)} · `:"",x.model?Rr(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: ",lt(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(yt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${M.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((g,j)=>{var U;const y=tf(g),I=y.color,v=(U=Na(Ni(g.metadata)))==null?void 0:U.model,N=typeof v=="string"?Rr(v):null,f=lt(g.title??""),C=g.type==="run_failed",H=g.type==="artifact_created",Z=g.type==="decision_requested"||g.type==="decision_resolved";return n.jsxs(ue.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay: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(nf,{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":Z?"text-amber-300":H?"text-cyan-300":"text-bright"}`,children:f}),g.summary&&g.summary!==f&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:lt(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:yi(g.timestamp),children:sf(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:yi(d[d.length-1].timestamp),children:$t(d[d.length-1].timestamp)})]})]})]})});function of({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(yt,{children:r&&n.jsx(ue.div,{initial:{opacity:0,height:0,marginBottom:0},animate:{opacity:1,height:"auto",marginBottom:12},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{className:"rounded-xl px-4 py-3",style:{backgroundColor:`${M.teal}08`,border:`1px solid ${M.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 lf={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}},_r={pr:"#BFFF00",commit:"#BFFF00",test:"#67e8f9",doc:"#0AD4C4",artifact:"#F5B700"};function qo(e){if(!e)return"#67e8f9";const t=e.toLowerCase();return t.includes("code")||t.includes("pull")||t.includes("commit")||t.includes("pr")?_r.pr:t.includes("doc")||t.includes("spec")?_r.doc:t.includes("test")?_r.test:_r.artifact}const cf={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 df({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,userStateLabel:l,userStateWhy:d,relativeTime:u,timeLabel:p,isRecent:x,enableMotion:b,onOpen:g,ariaLabel:j,artifactSnippet:y,evidenceChips:I,actorCategory:v,queuePosition:N}){const f=(I==null?void 0:I.slice(0,2))??[],C=((I==null?void 0:I.length)??0)-f.length,H="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=v==="system",U=n.jsxs("div",{className:oe("flex items-start gap-3",Z&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Qt,{name:v==="user"?"You":a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:oe("absolute inset-y-0 left-0 w-[2px] rounded-full",x&&!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:oe("truncate text-caption",Z?"text-muted italic":"text-secondary"),title:r,children:Z?`OrgX · ${r}`:r}),n.jsx("p",{className:oe("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:p}),n.jsx("span",{className:"text-micro text-muted",children:u})]})]}),y?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5",style:{borderColor:`${qo(y.typeBadge)}33`,backgroundColor:`${qo(y.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:[y.typeBadge&&n.jsxs("span",{className:"mr-1.5 text-micro font-semibold uppercase tracking-wider opacity-70",children:["[",y.typeBadge,"]"]}),n.jsx("span",{className:"font-semibold text-bright",children:y.title??y.label}),y.preview&&!y.title&&n.jsx("span",{className:"ml-1.5 opacity-60",children:y.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(Tr,{mode:"inline",text:i})}):null,f.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[f.map(fe=>{const K=_r[fe.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:K,backgroundColor:`${K}14`,border:`1px solid ${K}30`},children:[fe.kind==="pr"&&"PR",fe.kind==="commit"&&"Commit",fe.kind==="test"&&"Tests",fe.kind==="doc"&&"Doc",fe.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${K}CC`},children:fe.label})]},`${fe.kind}-${fe.label}`)}),C>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",C," more"]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${c}55`,backgroundColor:`${c}1A`,color:c},title:d,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c}}),l]}),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})}),N&&(()=>{const fe=cf[N.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:`${fe}55`,backgroundColor:`${fe}1A`,color:fe},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:fe}}),N.state==="running"?"Active":`#${N.rank}`]})})()]})]})]});return b?n.jsx(ue.button,{type:"button",variants:lf,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:g,className:H,"aria-label":j,children:U},e):n.jsx("button",{type:"button",onClick:g,className:oe(H,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":j,children:U},e)}function uf({open:e,onClose:t,children:s}){return n.jsx(Mi,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function mf(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 pf={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 ff({item:e,className:t}){var u,p,x;const s=o.useMemo(()=>Bc(e),[e]),r=mf(e),i=pf[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(ta,{label:"Task",value:s.taskDescription??d,styles:i}),s.outcomeDescription&&n.jsx(ta,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(ta,{label:"Next step",value:s.nextStep,styles:i})]})}function ta({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 zo=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),hf=[{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"}],Nr=[{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"}],Wo={type:"spring",stiffness:400,damping:25},Uo={scale:.985};function cn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function gf(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 Ir(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?Zt(Ut(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function xf(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function yf(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 Ii(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function rr(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 Zl(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function bf(e){return e==="agent"?"assistant":e}function wf(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function vf(e,t){return t.map(s=>({id:s.id,role:bf(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function ec(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function ir(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function xi(e){const t=ir(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=ir(t.latestMessage),i=ir(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 kf(e){const t=ir(e);if(!t)return null;const s=xi({...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=>ir(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=>ir(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 jf(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=Fr(t,Date.now());return i?r>=i:!0}async function Ar(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 na(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 Nf(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 tc=o.createContext(null),nc=o.createContext(null);function Pa(){const e=o.useContext(tc);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function Oa(){const e=o.useContext(nc);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function If({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),[v,N]=o.useState(!1),[f,C]=o.useState(null),[H,Z]=o.useState("resting"),[U,fe]=o.useState(""),[K,re]=o.useState(!1),[be,ve]=o.useState(!1),[Se,me]=o.useState(null),[Ke,pe]=o.useState(null),[ae,te]=o.useState([]),[ie,ke]=o.useState(""),[V,T]=o.useState([]),[z,P]=o.useState(""),[W,Q]=o.useState(null),[xe,je]=o.useState(""),[ne,ye]=o.useState(!1),[ge,E]=o.useState(""),[B,G]=o.useState([]),[se,Re]=o.useState(!1),[Ge,Te]=o.useState("auto"),[L,at]=o.useState(!1),[Le,Xe]=o.useState(!1),[bt,vt]=o.useState(!1),kt=o.useRef(null),O=o.useRef(null),_e=o.useRef(null),he=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b($=>Nf($,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{g&&b($=>$.sort((le,de)=>cn(de.lastActivityAt)-cn(le.lastActivityAt)))},[g]);const{data:Me}=Da({enabled:!0,refetchInterval:8e3}),Qe=o.useMemo(()=>{var le,de;const $=new Map;for(const Ee of hf)$.set(Ee.id,{id:Ee.id,name:Ee.name,handle:Ee.handle,domain:Ee.domain,domainLabel:Ee.domainLabel,role:Ee.role,status:"idle",currentTask:null,isSystem:!1});if(Me!=null&&Me.agents)for(const Ee of Me.agents){const wt=$.get(Ee.id);wt?(wt.status=Ee.status==="running"?"running":(le=Ee.blockers)!=null&&le.length?"blocked":"idle",wt.currentTask=Ee.currentTask??null):$.set(Ee.id,{id:Ee.id,name:Ee.name,handle:Ee.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Ee.status==="running"?"running":(de=Ee.blockers)!=null&&de.length?"blocked":"idle",currentTask:Ee.currentTask??null,isSystem:zo.has(Ee.id)})}for(const Ee of t){const wt=(Ee.agentId??"").trim(),Bt=(Ee.agentName??"").trim();!wt||!Bt||$.has(wt)||$.set(wt,{id:wt,name:Bt,handle:wt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:zo.has(wt)})}return Array.from($.values()).filter(Ee=>!Ee.isSystem).sort((Ee,wt)=>Ee.name.localeCompare(wt.name))},[Me,t]),nt=o.useMemo(()=>s.map($=>({id:$.id,name:$.name})).sort(($,le)=>$.name.localeCompare(le.name)),[s]),J=o.useMemo(()=>Qe.find($=>$.id===ie)??null,[Qe,ie]),ze=o.useMemo(()=>{const $=new Set(V);return Qe.filter(le=>$.has(le.id))},[Qe,V]),we=o.useMemo(()=>nt.find($=>$.id===z)??null,[nt,z]);o.useEffect(()=>{ie&&T($=>$.filter(le=>le!==ie))},[ie]);const X=o.useMemo(()=>Qe.slice(0,8),[Qe]),$e=o.useMemo(()=>{const $=xe.trim().toLowerCase();return $?Qe.filter(le=>le.name.toLowerCase().includes($)||le.handle.toLowerCase().includes($)||le.domain.toLowerCase().includes($)||le.role.toLowerCase().includes($)):Qe},[Qe,xe]),He=o.useMemo(()=>{const $=ge.trim().toLowerCase();return $?nt.filter(le=>le.name.toLowerCase().includes($)):nt},[nt,ge]),De=o.useMemo(()=>{const $=i.trim().toLowerCase(),le=x.filter(de=>!yf(de,a)||!jf(de,l,d)?!1:$.length===0?!0:xf(de).includes($));return le.sort((de,Ee)=>{const wt=cn(Ee.lastActivityAt)-cn(de.lastActivityAt);return c==="newest"?wt:-wt}),le},[d,i,c,a,x,l]),rt=o.useMemo(()=>{if(!g||De.some(le=>le.id===g))return De;const $=x.find(le=>le.id===g);return $?[$,...De]:De},[g,De,x]),ut=o.useMemo(()=>x.find($=>$.id===g)??null,[g,x]),_t=o.useMemo(()=>ae.filter($=>$.status!=="ready").length,[ae]),q=U.trim().length>0&&!K,Ie=o.useMemo(()=>_t>0?`${_t} attachment(s) still processing.`:"Press Enter to send.",[_t]),Ue=o.useMemo(()=>K?"Sending…":be?"Launching…":"Send",[be,K]),Ve=o.useMemo(()=>new Mc({api:"/orgx/api/chat/usechat"}),[]),{messages:qe,setMessages:Be,sendMessage:Pe,status:mt,error:Ft,clearError:pt}=Tc({id:`orgx-chat-guidance-${r??"global"}`,transport:Ve,onError:$=>{me(Ir(($==null?void 0:$.message)??null,"send"))}});o.useEffect(()=>{if(!y){Be([]);return}Be(vf(y.id,y.messages))},[y,Be]);const gt=o.useMemo(()=>{const $=[...qe].reverse().find(de=>de.role==="assistant");if(!$)return null;const le=wf($);return le.length>0?le:null},[qe]),At=o.useRef(null);o.useEffect(()=>{if(mt!=="ready"&&mt!=="error"||!gt)return;const $=[...qe].reverse().find(le=>le.role==="assistant");!$||$.id===At.current||(At.current=$.id,G(le=>[...le,{id:`guidance_${$.id}`,role:"agent",body:gt,timestamp:new Date().toISOString()}]))},[mt,gt,qe]);const st=o.useCallback(()=>{fe(""),te([]),Xe(!1),vt(!1),me(null),pe(null)},[]),Pt=o.useCallback($=>{G(le=>[...le,{...$,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Ye=o.useCallback(()=>G([]),[]),zt=o.useCallback(()=>Re($=>!$),[]),Ct=o.useMemo(()=>Nr.find($=>$.id===Ge)??Nr[0],[Ge]),St=o.useCallback(()=>{Te($=>{const le=Nr.findIndex(de=>de.id===$);return Nr[(le+1)%Nr.length].id})},[]),Ht=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),jt=o.useCallback(async $=>{var Ee;N(!0),C(null);const le=await Ar(`/orgx/api/chat/threads/${encodeURIComponent($)}`);if(!le.ok||!((Ee=le.data)!=null&&Ee.thread))return N(!1),C(Ir(le.error,"load")),null;const de=kf(le.data.thread);return de?(I(de),N(!1),de):(N(!1),C("Thread detail payload was invalid."),null)},[]),ln=o.useCallback(async($,le)=>{le&&(_e.current=le),j($),await jt($),requestAnimationFrame(()=>{var de;return(de=O.current)==null?void 0:de.focus()})},[jt]),rs=o.useCallback(()=>{var $;j(null),I(null),C(null),N(!1),($=_e.current)==null||$.focus()},[]),is=o.useCallback($=>{window.setTimeout(()=>{te(le=>le.map(de=>de.id===$?{...de,status:"indexing",updatedAt:new Date().toISOString()}:de))},80),window.setTimeout(()=>{te(le=>le.map(de=>{var Bt;if(de.id!==$)return de;const Ee=((Bt=de.mimeType)==null?void 0:Bt.toLowerCase())==="application/x-msdownload"||de.name.toLowerCase().endsWith(".exe"),wt=(de.sizeBytes??0)>25*1024*1024;return Ee?{...de,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:wt?{...de,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...de,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),ks=o.useCallback($=>{if(!$||$.length===0)return;const le=new Date().toISOString(),de=Array.from($).map(Ee=>({id:`draft_att_${crypto.randomUUID()}`,name:Ee.name,mimeType:Ee.type||null,sizeBytes:Number.isFinite(Ee.size)?Ee.size:null,status:"preparing",error:null,masked:!1,createdAt:le,updatedAt:le}));te(Ee=>Ee.concat(de)),de.forEach(Ee=>is(Ee.id)),hs("chat_attachment_state_changed",{count:de.length,state:"preparing"})},[is]),Rn=o.useCallback($=>{te(le=>le.map(de=>de.id===$?{...de,status:"preparing",error:null,updatedAt:new Date().toISOString()}:de)),is($),hs("chat_attachment_state_changed",{state:"retry"})},[is]),Vt=o.useCallback($=>{ke(le=>le===$?"":$),T(le=>le.filter(de=>de!==$)),Q(null),je("")},[]),kn=o.useCallback($=>{T(le=>le.includes($)?le.filter(de=>de!==$):le.concat($))},[]),js=o.useCallback(()=>{ye(!1),E(""),Q($=>$==="assignee"?null:"assignee"),je("")},[]),rn=o.useCallback(()=>{ye(!1),E(""),Q($=>$==="watcher"?null:"watcher"),je("")},[]),as=o.useCallback(()=>{Q(null),je(""),ye($=>!$),E("")},[]),An=o.useCallback(async($,le)=>{var Bt;at(!0);const de=nt.find(it=>it.id===le)??null,Ee=await Ar("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:$,project_id:r??void 0,initiativeId:(de==null?void 0:de.id)??null,initiativeTitle:(de==null?void 0:de.name)??null,relinked:!0})});if(at(!1),!Ee.ok||!((Bt=Ee.data)!=null&&Bt.thread)){C(Ee.error??"Scope link failed.");return}const wt=xi(Ee.data.thread);wt&&b(it=>na(it,wt)),await jt($),await Ht(),hs("chat_thread_linked_initiative",{threadId:$,initiativeId:(de==null?void 0:de.id)??null})},[nt,jt,Ht,r]),Kn=o.useCallback(async $=>{pt(),await Pe({text:$.prompt},{body:{threadId:$.thread.id,project_id:r??void 0,initiativeId:$.thread.initiativeId??(we==null?void 0:we.id)??void 0,initiativeTitle:$.thread.initiativeTitle??(we==null?void 0:we.name)??void 0,assigneeId:(J==null?void 0:J.id)??$.thread.assigneeId??void 0,assigneeName:(J==null?void 0:J.name)??$.thread.assigneeName??void 0,watcherIds:ze.map(le=>le.id),watcherNames:ze.map(le=>le.name)}}),await Ht(),await jt($.thread.id)},[pt,jt,Ht,J==null?void 0:J.id,J==null?void 0:J.name,we==null?void 0:we.id,we==null?void 0:we.name,ze,Pe,r]),Ln=o.useCallback(async()=>{var wt,Bt;const $=U.trim();if(!$)return me("Write a message before sending."),{thread:null,messageId:null};me(null),pe(null),re(!0);const le=await Ar("/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:(J==null?void 0:J.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(J==null?void 0:J.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:ze.map(it=>it.id),watcherNames:ze.map(it=>it.name),body:$,attachments:ae.map(it=>({id:it.id,name:it.name,mimeType:it.mimeType,sizeBytes:it.sizeBytes,status:it.status,error:it.error,masked:it.masked}))})});if(re(!1),!le.ok||!((wt=le.data)!=null&&wt.thread))return me(Ir(le.error,"send")),hs("chat_message_send_failed",{reason:le.error??"unknown"}),{thread:null,messageId:null};const de=xi(le.data.thread);if(!de)return me("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(it=>na(it,de)),Pt({role:"user",body:$}),Ge!=="auto"&&J&&Pt({role:"system",body:`Routing to ${J.name} via ${Ct.label}`}),hs("chat_message_sent",{threadId:de.id,watcherCount:de.watcherIds.length}),await Ht();const Ee=le.data.message&&typeof le.data.message.id=="string"?le.data.message.id:((Bt=de.latestMessage)==null?void 0:Bt.id)??null;return j(de.id),await jt(de.id),Kn({thread:de,prompt:$}).catch(it=>{Pt({role:"error",body:Ir(it instanceof Error?it.message:String(it??""),"send")})}),st(),Z("reviewing"),{thread:de,messageId:Ee}},[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,U,ae,jt,Ht,st,Kn,J==null?void 0:J.id,J==null?void 0:J.name,we==null?void 0:we.id,we==null?void 0:we.name,Ge,Ct,ze,r]),Gn=o.useCallback(async($,le)=>{var Ns,Tt,Nt,pn,Xn,_n,Is;if(!le){Pt({role:"error",body:"Send a message first to launch."});return}if(!J){Pt({role:"error",body:"Pick an agent with @ before launching."});return}if(_t>0&&!bt){Xe(!0),Pt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ve(!0),me(null),pe(null);const de=await Ar("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:J.id,message:U.trim().length>0?U.trim():$.lastSnippet??$.title,initiativeId:$.initiativeId??(we==null?void 0:we.id)??void 0,initiativeTitle:$.initiativeTitle??(we==null?void 0:we.name)??void 0,workstreamId:$.workstreamId??void 0,taskId:$.taskId??void 0,provider:Ge!=="auto"?Ge:void 0})}),Ee=((Ns=de.data)==null?void 0:Ns.sessionId)??((Tt=de.data)==null?void 0:Tt.runId)??null,wt=de.ok&&Ee?"running":de.ok?"queued":"blocked",Bt=de.ok?null:de.error??"Launch request failed before queueing.",it=await Ar("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:$.id,messageId:le,assigneeId:J.id,assigneeName:J.name,watcherIds:ze.map(fn=>fn.id),watcherNames:ze.map(fn=>fn.name),executionMode:"local_queue",provider:((Nt=de.data)==null?void 0:Nt.provider)??(Ge!=="auto"?Ge:"openclaw"),runId:Ee??void 0,status:wt,blockedReason:Bt??void 0,warnings:_t>0?[`${_t} attachment(s) were not ready at launch.`]:[]})});if(ve(!1),vt(!1),Xe(!1),!it.ok||!((pn=it.data)!=null&&pn.thread)){me(it.error?Ir(it.error,"launch"):Bt??"Launch state could not be persisted. Message remained saved."),hs("chat_launch_failed",{threadId:$.id,reason:it.error??Bt??"unknown"});return}const Lt=xi(it.data.thread);if(Lt&&b(fn=>na(fn,Lt)),await jt($.id),await Ht(),!de.ok){me(`Launch blocked: ${Bt??"Set assignee and retry."}`),hs("chat_launch_blocked",{threadId:$.id,reason:Bt??"unknown"});return}const qs=((Xn=de.data)==null?void 0:Xn.provider)==="anthropic"?"Claude Code":((_n=de.data)==null?void 0:_n.provider)==="openai"?"Codex":Ct.shortLabel,ht=(Is=de.data)!=null&&Is.model?` (${de.data.model})`:"";pe(Ee?`Launch started via ${qs}${ht}. Thread timeline now tracks execution state.`:`Launch queued locally via ${qs}. Run starts when a worker is available.`),hs(Ee?"chat_launch_started":"chat_launch_queued",{threadId:$.id,runId:Ee,assigneeId:J.id})},[U,bt,jt,Ht,J,we==null?void 0:we.id,we==null?void 0:we.name,Ge,Ct,ze,_t]),os=o.useCallback(async()=>{var le;const $=await Ln();(le=$.thread)!=null&&le.id&&await ln($.thread.id)},[ln,Ln]),Kt=o.useCallback(async()=>{const $=await Ln();$.thread&&(await Gn($.thread,$.messageId),await ln($.thread.id))},[Gn,ln,Ln]),Sn=o.useCallback(async()=>{if(q){if(J){await Kt();return}await os()}},[q,Kt,os,J]),jn=o.useMemo(()=>({threads:x,activeThreadId:g,activeThread:y,activeThreadSummary:ut,displayedThreads:rt,composerMode:H,draft:U,draftAttachments:ae,sending:K,launching:be,composerError:Se,composerNotice:Ke,selectedAssigneeId:ie,selectedAssignee:J,selectedWatcherIds:V,selectedWatchers:ze,selectedInitiativeId:z,selectedInitiative:we,agentOptions:Qe,quickAssigneeOptions:X,initiativeOptions:nt,agentPickerMode:W,agentPickerQuery:xe,filteredAgentOptions:$e,scopePickerOpen:ne,scopePickerQuery:ge,filteredInitiativeOptions:He,panelLoading:v,panelError:f,scopeSaving:L,launchWarningOpen:Le,launchWarningAccepted:bt,unresolvedAttachmentCount:_t,canSend:q,composerGuidance:Ie,primaryActionLabel:Ue,guidanceStatus:mt,guidancePreview:gt,guidanceError:Ft??null,inlineMessages:B,threadSidebarOpen:se,workspaceId:r,selectedProvider:Ge,selectedProviderDef:Ct}),[x,g,y,ut,rt,H,U,ae,K,be,Se,Ke,ie,J,V,ze,z,we,Qe,X,nt,W,xe,$e,ne,ge,He,v,f,L,Le,bt,_t,q,Ie,Ue,mt,gt,Ft,B,se,r,Ge,Ct]),ls=o.useMemo(()=>({setDraft:fe,setComposerMode:Z,setDraftAttachments:te,selectAssignee:Vt,toggleWatcher:kn,setSelectedInitiativeId:P,toggleAssigneePicker:js,toggleWatcherPicker:rn,toggleScopePicker:as,setAgentPickerQuery:je,setScopePickerQuery:E,setAgentPickerMode:Q,setScopePickerOpen:ye,handlePrimaryAction:Sn,handleFilesAdded:ks,handleRetryAttachment:Rn,openThreadPanel:ln,closeThreadPanel:rs,loadThreadDetail:jt,applyScopeLink:An,resetComposer:st,setComposerError:me,setComposerNotice:pe,setLaunchWarningAccepted:vt,pushInlineMessage:Pt,clearInlineMessages:Ye,toggleThreadSidebar:zt,setSelectedProvider:Te,cycleProvider:St,fileInputRef:kt,panelHeadingRef:O,composerShellRef:he}),[Vt,kn,js,rn,as,Sn,ks,Rn,ln,rs,jt,An,st,Pt,Ye,zt,St]);return n.jsx(tc.Provider,{value:jn,children:n.jsx(nc.Provider,{value:ls,children:e})})}const Af={type:"spring",stiffness:500,damping:35,mass:.5};function Sf({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=ss(),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(ue.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:oe("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(yt,{initial:!1,children:c.map(d=>n.jsx(ue.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:Af,className:oe("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:oe("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:oe("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:oe("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 Ho({open:e,onClose:t}){const s=ss(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:p}=Pa(),{openThreadPanel:x,closeThreadPanel:b,loadThreadDetail:g,applyScopeLink:j,panelHeadingRef:y}=Oa(),I=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,v=o.useCallback((f,C)=>{x(f,C)},[x]),N=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(yt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ue.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(ue.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Jt.durationEntrance/1e3,ease:Jt.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:oe("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(Ti,{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(f=>n.jsxs("button",{type:"button",onClick:C=>v(f.id,C.currentTarget),className:oe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===f.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:f.lastSnippet?`"${f.lastSnippet.length>40?f.lastSnippet.slice(0,40)+"...":f.lastSnippet}"`:f.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:f.lastActivityAt,children:$t(f.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[f.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",f.assigneeName]}),n.jsx("span",{children:f.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:oe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",rr(f.status)),children:Ii(f.status)})]})]},f.id))})}),n.jsx(yt,{initial:!1,children:i&&n.jsxs(ue.div,{initial:s?!1:{opacity:0,x:12},animate:s?{}:{opacity:1,x:0},exit:s?{}:{opacity:0,x:12},transition:s?void 0:{duration:Jt.durationStandard/1e3,ease:Jt.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:oe("rounded-full border px-2 py-0.5 text-micro font-semibold",rr((c==null?void 0:c.status)??"message_only")),children:Ii((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(f=>n.jsx("article",{className:oe("flex",f.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:oe("max-w-[90%] rounded-xl border px-2.5 py-1.5",f.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":f.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:f.senderName??Zl(f.role)}),n.jsx("time",{dateTime:f.createdAt,children:$t(f.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:f.body})]})},f.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(f=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:oe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",rr(ec(f.status))),children:f.status}),n.jsx("span",{children:f.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:f.requestedAt,children:$t(f.requestedAt)})]},f.id))]})]})})]})]})]})})}function Vo(){const e=ss(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=Pa(),{openThreadPanel:p,closeThreadPanel:x,loadThreadDetail:b,applyScopeLink:g,setComposerMode:j,toggleThreadSidebar:y,panelHeadingRef:I}=Oa(),v=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,N=o.useCallback(()=>{y()},[y]);return u?n.jsx(yt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ue.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(ue.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Jt.durationEntrance/1e3,ease:Jt.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(ue.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:Uo,transition:Wo,onClick:()=>{N(),j("focused"),requestAnimationFrame(()=>{const f=document.getElementById("chat-dock-input");f instanceof HTMLTextAreaElement&&f.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((f,C)=>n.jsxs(ue.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:Wo,delay:e?0:Math.min(C*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Uo,onClick:H=>void p(f.id,H.currentTarget),className:oe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===f.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:f.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:f.lastActivityAt,children:$t(f.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:f.lastSnippet??f.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[f.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Qt,{name:f.assigneeName,hint:f.assigneeName,size:"xs"}),n.jsx("span",{children:f.assigneeName})]}),n.jsx("span",{children:f.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:oe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",rr(f.status)),children:Ii(f.status)})]})]},f.id))})}),n.jsx(yt,{initial:!1,children:s&&n.jsxs(ue.div,{initial:e?!1:{opacity:0,y:12},animate:e?{}:{opacity:1,y:0},exit:e?{}:{opacity:0,y:12},transition:e?void 0:{duration:Jt.durationStandard/1e3,ease:Jt.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:oe("rounded-full border px-2 py-0.5 text-micro font-semibold",rr((i==null?void 0:i.status)??"message_only")),children:Ii((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}),v&&n.jsx("button",{type:"button",onClick:()=>void b(v),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(f=>n.jsx("article",{className:oe("flex",f.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:oe("max-w-[90%] rounded-xl border px-2.5 py-1.5",f.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":f.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:f.senderName??Zl(f.role)}),n.jsx("time",{dateTime:f.createdAt,children:$t(f.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:f.body})]})},f.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(f=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:oe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",rr(ec(f.status))),children:f.status}),n.jsx("span",{children:f.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:f.requestedAt,children:$t(f.requestedAt)})]},f.id))]})]})})]},"sidebar-panel")]})}):null}const _f={type:"spring",stiffness:500,damping:30,mass:.5};function Cf({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=ss(),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(yt,{children:n.jsx(ue.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:_f,className:oe("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:oe("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(Qt,{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 Mf={type:"spring",stiffness:500,damping:30,mass:.5};function Tf({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=ss(),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(yt,{children:n.jsx(ue.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:Mf,className:oe("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:oe("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:oe("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 Ef({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=ss();return n.jsx(yt,{children:e&&n.jsxs(ue.div,{initial:g?!1:{opacity:0,scale:.95,y:8},animate:g?{}:{opacity:1,scale:1,y:0},exit:g?{}:{opacity:0,scale:.95,y:8},transition:g?void 0:Jt.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:oe("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:oe("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:oe("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(Qt,{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:oe("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(Qt,{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 Ko=24,Go=200;function Xo(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 Rf(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 Qo({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 Ia="orgx-chat-dock-collapsed";function Lf(){try{return localStorage.getItem(Ia)==="1"}catch{return!1}}function $f(){const e=Pa(),t=Oa(),s=ss(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState(Lf),l=o.useCallback(()=>{c(X=>{const $e=!X;try{localStorage.setItem(Ia,$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(""),[v,N]=o.useState(0),[f,C]=o.useState(-1),[H,Z]=o.useState(!1),[U,fe]=o.useState(""),[K,re]=o.useState(0),[be,ve]=o.useState(-1),{composerMode:Se,draft:me,draftAttachments:Ke,sending:pe,launching:ae,selectedAssigneeId:te,selectedAssignee:ie,selectedWatcherIds:ke,selectedInitiative:V,agentOptions:T,quickAssigneeOptions:z,agentPickerMode:P,agentPickerQuery:W,filteredAgentOptions:Q,initiativeOptions:xe,canSend:je,activeThreadId:ne,guidanceStatus:ye,inlineMessages:ge,displayedThreads:E,launchWarningOpen:B,launchWarningAccepted:G,selectedProvider:se,selectedProviderDef:Re}=e,Ge=me.trim(),Te=ge.length>0;Ge.length>0;const L=o.useCallback(()=>{const X=r.current;if(!X)return;X.style.height="0";const $e=Math.min(Math.max(X.scrollHeight,Ko),Go);X.style.height=`${$e}px`},[]);o.useLayoutEffect(()=>{L()},[me,L]);const at=o.useMemo(()=>{if(!g)return T;const X=y.toLowerCase();return X?T.filter($e=>$e.name.toLowerCase().includes(X)||$e.handle.toLowerCase().includes(X)||$e.domain.toLowerCase().includes(X)||$e.role.toLowerCase().includes(X)):T},[T,g,y]),Le=o.useMemo(()=>{if(!H)return xe;const X=U.toLowerCase();return X?xe.filter($e=>$e.name.toLowerCase().includes(X)):xe},[xe,H,U]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),ge.length<=2){x(!1);return}return x(!1),b.current=window.setTimeout(()=>{x(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[ge.length]),o.useEffect(()=>{const X=$e=>{if(($e.metaKey||$e.ctrlKey)&&$e.key==="k"){if($e.preventDefault(),a){c(!1);try{localStorage.setItem(Ia,"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(()=>{Se==="resting"&&t.setComposerMode("focused")},[Se,t]),bt=o.useCallback(()=>{window.setTimeout(()=>{Ge.length===0&&!Te&&!g&&!H&&Ke.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),j(!1),Z(!1))},100)},[Ge,Te,g,H,Ke.length,t]),vt=o.useCallback(X=>{const $e=X.target.value,He=X.target.selectionStart??$e.length;t.setDraft($e),(Se==="resting"||Se==="focused")&&t.setComposerMode("composing");const De=$e.slice(0,He),rt=De.match(/@(\w*)$/);if(rt){j(!0),I(rt[1]),N(0),C(He-rt[0].length),Z(!1);return}const ut=De.match(/#(\w*)$/);if(ut){Z(!0),fe(ut[1]),re(0),ve(He-ut[0].length),j(!1);return}g&&j(!1),H&&Z(!1)},[Se,t,g,H]),kt=o.useCallback(X=>{var rt;const $e=me.slice(0,f),He=me.slice(((rt=r.current)==null?void 0:rt.selectionStart)??me.length),De=`${$e}@${X.name} ${He}`;t.setDraft(De),t.selectAssignee(X.id),j(!1),I(""),requestAnimationFrame(()=>{if(r.current){const ut=$e.length+X.name.length+2;r.current.setSelectionRange(ut,ut),r.current.focus()}})},[me,f,t]),O=o.useCallback(X=>{var De;const $e=me.slice(0,be),He=me.slice(((De=r.current)==null?void 0:De.selectionStart)??me.length);if(X){const rt=`${$e}#${X.name} ${He}`;t.setDraft(rt),t.setSelectedInitiativeId(X.id),requestAnimationFrame(()=>{if(r.current){const ut=$e.length+X.name.length+2;r.current.setSelectionRange(ut,ut),r.current.focus()}})}else{const rt=`${$e}${He}`;t.setDraft(rt),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange($e.length,$e.length),r.current.focus())})}Z(!1),fe("")},[me,be,t]),_e=o.useCallback(X=>{if(g&&at.length>0){if(X.key==="ArrowDown"){X.preventDefault(),N($e=>($e+1)%at.length);return}if(X.key==="ArrowUp"){X.preventDefault(),N($e=>($e-1+at.length)%at.length);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),kt(at[v]);return}if(X.key==="Escape"){X.preventDefault(),j(!1);return}}if(H){const $e=Le.length+1;if(X.key==="ArrowDown"){X.preventDefault(),re(He=>(He+1)%$e);return}if(X.key==="ArrowUp"){X.preventDefault(),re(He=>(He-1+$e)%$e);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),O(K===0?null:Le[K-1]);return}if(X.key==="Escape"){X.preventDefault(),Z(!1);return}}if(X.key==="Enter"&&!X.shiftKey){X.preventDefault(),t.handlePrimaryAction();return}X.key==="Escape"&&(X.preventDefault(),P?t.setAgentPickerMode(null):Te?t.clearInlineMessages():(t.setComposerMode("resting"),X.target.blur()))},[t,P,Te,g,at,v,kt,H,Le,K,O]),he=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),Me=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=(Se==="reviewing"||Te)&&ge.length>0,nt=ye==="submitted"||ye==="streaming",J=o.useRef(ge.length),[ze,we]=o.useState(0);return o.useEffect(()=>{if(!a){J.current=ge.length,we(0);return}const X=ge.length-J.current;X>0&&we(X)},[a,ge.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(Ho,{open:d,onClose:()=>u(!1)}),n.jsx(Vo,{}),n.jsx("div",{className:"sticky bottom-0 z-20 flex justify-end px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:n.jsxs(ue.button,{type:"button",onClick:()=>{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:oe("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(yt,{children:ze>0&&n.jsx(ue.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:oe("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:ze>9?"9+":ze},"unread")}),ne&&ze===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(Ho,{open:d,onClose:()=>u(!1)}),n.jsx(Vo,{}),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(yt,{children:B&&n.jsxs(ue.div,{initial:s?!1:{opacity:0,y:4},animate:s?{}:{opacity:1,y:0},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mb-2 rounded-lg border border-amber-300/35 bg-amber-300/[0.12] px-2.5 py-2 text-caption text-amber-100",children:[n.jsx("p",{children:"Launch includes non-ready attachments. Continue anyway?"}),n.jsxs("label",{className:"mt-1.5 flex items-center gap-2",children:[n.jsx("input",{type:"checkbox",checked: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(Ef,{open:P!==null,mode:P??"assignee",agents:Q,quickAgents:z,query:W,selectedAssigneeId:te,selectedWatcherIds:ke,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(ue.section,{"data-testid":"chat-dock","data-state":Se,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Jt.durationEntrance/1e3,ease:Jt.easingEntrance},className:oe("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",Se!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:l,className:oe("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(yt,{children:Qe&&n.jsx(Sf,{messages:ge,isStreaming:nt,collapsed:p,onClick:he})}),n.jsxs("div",{className:"relative",children:[n.jsx(Cf,{open:g,agents:at,query:y,activeIndex:v,anchorRect:null,onSelect:kt,onClose:()=>j(!1)}),n.jsx(Tf,{open:H,initiatives:Le,query:U,activeIndex:K,onSelect:O,onClose:()=>Z(!1)})]}),n.jsx(yt,{initial:!1,children:Ke.length>0&&n.jsx(ue.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:Ke.map(X=>n.jsxs("div",{className:oe("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:`${Xo(X.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Xo(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:[Rf(X.mimeType,X.name),X.sizeBytes?` · ${gf(X.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments($e=>$e.filter(He=>He.id!==X.id)),className:oe("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:oe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(ue.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:oe("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",se==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":se==="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(Qo,{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:me,onFocus:Xe,onBlur:bt,onChange:vt,onKeyDown:_e,placeholder:"Ask anything",rows:1,className:oe("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:Ko,maxHeight:Go,overflowY:"auto"},"aria-expanded":Se!=="resting"})]}),E.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:oe("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":`${E.length} thread${E.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"})}),E.length]}),n.jsx(ue.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!je,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:oe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",je?"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:Me})]}),n.jsx(yt,{children:(ie||V)&&Se!=="resting"&&n.jsxs(ue.div,{initial:s?!1:{opacity:0},animate:s?{}:{opacity:1},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mt-1.5 flex items-center gap-2 px-10",children:[ie&&n.jsxs("button",{ref:X=>{i.current=X},type:"button",onClick:t.toggleWatcherPicker,className:oe("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(Qt,{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"})]}),V&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",V.name]}),se!=="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(Qo,{icon:Re.icon}),Re.shortLabel]})]})})]})]})]})}const Jo={completed:M.lime,needs_attention:M.amber,in_progress:M.teal,blocked:M.red,unknown:"rgba(255,255,255,0.4)"};function Yo({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:M.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:M.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:M.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:M.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:M.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(yt,{children:a&&n.jsx(ue.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:n.jsx("div",{className:"mt-3 space-y-1.5 border-t border-white/[0.06] pt-3",children:t.map((p,x)=>n.jsxs(ue.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:Jo[p.status]??Jo.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 sa=50,Df=50,Sr=20,Zo=3600,el=12e3,si={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},tl=["live","24h","7d","all"];function nl(e){if(e==="custom"||e==="all")return null;const t=tl.indexOf(e);return t<0?null:tl[t+1]??null}function sl(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 Ff(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function rl(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function ns(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 ra(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function il(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Ps(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ba(e){if(!e)return;let t={...e},s=Ps(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=Ps(s.metadata),r+=1;return t}function dt(e){const t=Ps(e==null?void 0:e.metadata);return Ba(t)}function Pf(e){const t=Ba(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 Aa(e){if(e.runId)return e.runId;const t=dt(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 tr(e){const t=dt(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 al(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Of=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bf=/^[0-9a-f]{20,}$/i,sc=/^\d+$/,rc=/^(user|usr|clerk)_[a-z0-9]+$/i;function mn(e){if(!e)return null;const t=e.trim();return!t||Of.test(t)||Bf.test(t)||sc.test(t)||rc.test(t)?null:t}const qf=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function zf(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return qf.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function ol(e,t,s){if(!e)return null;let r=null;for(const a of t){const c=mn(al(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=mn(al(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Wf(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 ll(e){const t=dt(e),s=tr(e),r=Dr(e),i=mn(s.agentId),a=mn(s.agentName),c=mn(e.requesterAgentId??null),l=mn(e.requesterAgentName??null),u=(c||l?{id:c,name:l,label:l??c??"OrgX"}:null)??ol(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=mn(e.executorAgentId??null),x=mn(e.executorAgentName??null),g=(p||x?{id:p,name:x,label:x??p??"Agent"}:null)??ol(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?Wf(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:mn(e.agentName??null)??mn(e.agentId??null)??"OrgX",subtitle:mn(e.agentName??null)??mn(e.agentId??null)??"OrgX"}}function cl(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const Uf=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Hf=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Vf(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=dt(e),r=Ce(s,["event","event_name","eventName"])??"";return(Ce(s,["source"])??"")==="user"?"user":Uf.has(r)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Hf.has(r)?"system":"agent"}const Kf={user:M.lime,system:"rgba(255,255,255,0.15)",orchestrator:M.iris,agent:""};function Gf(e){switch(e){case"user":return"You";case"system":return"OrgX";case"orchestrator":return"Xandy";case"agent":return""}}function Zs(e){const t=dt(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 ia(e){const t=dt(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 dl=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 ai(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function ic(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 Ds(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 Xf(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 Qf(e){const t=dt(e),s=ai(e.kind)??ai(t==null?void 0:t.activity_bucket)??ai(t==null?void 0:t.activityBucket)??ai(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=Xf(t),i=e.decisionRequired===!0||ic(t,["decision_required","decisionRequired"])===!0,a=Ds(t,["artifacts","artifact_count","artifactCount"])??0,c=Ds(t,["decisions","decision_count","decisionCount"])??0,l=Ds(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ds(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=In(Ce(t,["stop_reason","stopReason"])??"");if(p==="blocked"||p==="error")return"decision"}return r&&dl.has(r)?dl.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 Jf(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=Ce(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if(Pr(s))return!0;const r=Ce(t,["stop_reason","stopReason"]);if(In(r)==="completed")return!0;const i=t?ac(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||ic(t,["decision_required","decisionRequired"])===!0,c=Ds(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0;return i!==null&&i>=100&&!a&&c===0}function Ai(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 Yf(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 Zf(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 aa(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function oa(e){return e==="completed"?M.lime:e==="needs_input"?M.amber:e==="issue"?M.red:M.teal}function eh(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 ul(e){let t="Workstream";const s=e.allItems.map(r=>{const i=dt(r.item),a=Ce(i,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const l=Ce(i,["task_title","taskTitle","dispatch_task_title"])??Dr(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 ml(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function ws(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 es(e){const t=ws(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=ws(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function th(e){const t=ws(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 ac(e,t){for(const s of t){const r=th(e[s]);if(r!==null)return r}return null}function oi(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 oc(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=oi(e,["blocking_decision_ids","blockingDecisionIds"]),s=oi(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=oi(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=oi(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 lc(e){if(!e)return null;const t=dt(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=tr(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=ch(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=Ce(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),v=Ce(t,["initiative_title","initiativeTitle"]),N=Ce(t,["initiative_status","initiativeStatus"]),f=Zs(e),C=Ce(t,["workstream_title","workstreamTitle"]),H=Ce(t,["workstream_status","workstreamStatus"]),Z=Ce(t,["task_title","taskTitle"]),U=Ce(t,["milestone_title","milestoneTitle"]),fe=Ce(t,["domain"]),K=Ce(t,["phase","slice_phase","slicePhase"]),re=Ce(t,["next_step","nextStep"]),be=ac(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,Se=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,me=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=es(t.artifacts??t.artifact_count??t.artifactCount),te=es(t.decisions??t.decision_count??t.decisionCount),ie=oc(t),ke=t.decisions_needed??t.decisionsNeeded;let V=es(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),T=es(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((V===null||T===null)&&Array.isArray(ke)){let G=0,se=0;for(const Re of ke){if(!Re||typeof Re!="object"||Array.isArray(Re))continue;Re.blocking===!1?se+=1:G+=1}V===null&&(V=G),T===null&&(T=se)}V===null&&te!==null&&e.decisionRequired===!0&&(V=te>0?te:1),T===null&&te!==null&&V!==null&&(T=Math.max(0,te-V)),V===null&&te!==null&&T!==null&&(V=Math.max(0,te-T));const z=es(t.status_updates_applied??t.statusUpdatesApplied),P=es(t.task_updates??t.taskUpdates),W=es(t.milestone_updates??t.milestoneUpdates),Q=z??(P!==null||W!==null?(P??0)+(W??0):null),xe=es(t.status_updates_buffered??t.statusUpdatesBuffered),je=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,ne=ws(t.token_budget??t.tokenBudget),ye=ws(t.tokens_used??t.tokensUsed),ge=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),E=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,B=x&&!a.agentName?null:ge;return{event:s,agentId:B,agentName:E,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:I,domain:fe,phase:K,progressPct:be,nextStep:re,requiredSkills:p,initiativeStatus:N,initiativeTitle:v,workstreamId:f,workstreamStatus:H,workstreamTitle:C,taskTitle:Z,milestoneTitle:U,taskIds:g,milestoneIds:y,parsedStatus:ve,hasOutput:Se,artifacts:ae,decisions:te,blockingDecisions:V,nonBlockingDecisions:T,decisionIds:ie.decisionIds,blockingDecisionIds:ie.blockingDecisionIds,nonBlockingDecisionIds:ie.nonBlockingDecisionIds,statusUpdatesApplied:Q,statusUpdatesBuffered:xe,stopReason:je,tokenBudget:ne,tokensUsed:ye,logPath:me,outputPath:Ke,error:pe}}function la(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function nh(e){const t=Ba(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,v=s.required_skills??s.requiredSkills,N=Array.isArray(v)?v.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 cc(e){if(!e)return null;const t=dt(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 sh(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":lt(e)}function rh(e){const t=dt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=cc(e);if(!r&&!s)return null;const i=Ce(t,["artifact_type","artifactType","atomic_unit_type"]),a=Ce(t,["artifact_title","title","name"]),c=Ce(t,["url","pr_url","commit_url"]),l=sh(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 ih(e){const t=dt(e);if(!t)return[];const s=[],r=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,i=Ce(t,["pr_url"])??(r?Ce(r,["pr_url"]):null),a=Ce(t,["pr_number"])??(r?Ce(r,["pr_number"]):null);(a||i)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:i});const c=Ce(t,["commit_sha"])??(r?Ce(r,["commit_sha"]):null),l=Ce(t,["commit_url"])??(r?Ce(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 ah(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 dc(e){const t=dt(e);if(!t)return[];const s=[],r=new Set,i=(c,l)=>{if(typeof l!="string")return;const d=l.trim();if(!d||!ah(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 Ce(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 Cr(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 li(e){for(const t of e){const s=Cr(t.value,t.idHint);if(s)return s}return null}function oh(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 lh(e,t){if(!e)return null;const s=dt(e);if(!s)return null;const r=Ce(s,["event","event_name","eventName"]),i=Ps(s.spawn_guard),a=Ps(i==null?void 0:i.checks),c=Ps((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=Ce(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=oh(l),u=ws(c==null?void 0:c.current)??d.domainCurrent,p=ws(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:Ce(s,["domain"])??Ce(i,["domain","task_domain"]),modelTier:Ce(s,["spawn_guard_model_tier","model_tier"])??Ce(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:p,totalCurrent:x,totalMax:b,retryAt:Ce(s,["next_retry_at","nextRetryAt"]),retryInMs:ws(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:j}}function ch(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 ${lt(i)}`}return null}function dh(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 ca(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&&dh(r)?a:r??a;if(c)return Di(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"?Di(i):Mr.test(i)||uh.test(i)||sc.test(i)||rc.test(i)?"OrgX":Di(i)}const Mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,uh=/^[0-9a-f]{20,}$/i,mh=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function Si(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(mh)??[]){const l=c.trim().toLowerCase();Mr.test(l)&&t.add(l)}typeof e.runId=="string"&&Mr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=dt(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();Mr.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();Mr.test(d)&&t.add(d)}}return t}function ph(e){if(!e)return[];const t=dt(e);return oc(t).decisionIds}function fh(e,t,s){if(!e)return[];const r=dt(e),i=Ce(r,["workstream_id","workstreamId"]),a=Ce(r,["initiative_id","initiativeId"]),c=Si(e);if(!i&&!a&&c.size===0)return[];const l=ns(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const g=dt(b);if(!g)continue;const j=Ce(g,["workstream_id","workstreamId"]),y=Ce(g,["initiative_id","initiativeId"]),I=Si(b),v=c.size>0&&Array.from(c).some(U=>I.has(U)),N=!!i&&!!j&&i===j;if(!v&&!N&&!(!!a&&!!y&&a===y))continue;const C=dc(b).filter(U=>!s.has(U.path));if(C.length===0)continue;const H=Math.abs(ns(b.timestamp)-l);if(!v&&H>7200*1e3)continue;const Z=v?0:N?1:2;!v&&H>1200*1e3||d.push({priority:Z,delta:H,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 hh(e,t){if(!e)return null;const s=dt(e),r=Ce(s,["workstream_id","workstreamId"]),i=Ce(s,["initiative_id","initiativeId"]),a=Si(e);if(!r&&!i&&a.size===0)return null;const c=ns(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const p=lc(u);if(!p)continue;const x=dt(u);if(!x)continue;const b=Ce(x,["workstream_id","workstreamId"]),g=Ce(x,["initiative_id","initiativeId"]),j=Si(u),y=a.size>0&&Array.from(a).some(H=>j.has(H)),I=!!r&&!!b&&r===b;if(!y&&!I&&!(!!i&&!!g&&i===g))continue;const N=Math.abs(ns(u.timestamp)-c);if(!y&&N>1200*1e3)continue;const f=y?"shared_id":I?"workstream":"initiative",C=f==="shared_id"?0:f==="workstream"?1:2;l.push({priority:C,delta:N,relation:f,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 In(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function Pr(e){const t=In(e);return["done","complete","completed","stopped","success"].includes(t)}function gh(e){const t=In(e.parsedStatus),s=In(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":Pr(t)||e.stopReason==="completed"?"positive":"neutral"}function xh(e){if(Pr(e.parsedStatus)||e.stopReason==="completed")return 100;const t=In(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 uc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function yh(e,t){if(!e&&t===null)return null;const s=e?gh(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=uc(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=xh(e);if(a===null)return null;const c=r(a);return{pct:a,source:"lifecycle",label:c?i:"Progress",tone:s,terminalStop:c}}function bh(e,t,s,r=null){var v;const i=dt(e),a=In(Ce(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=In(e.state??e.phase??e.kind??e.type),l=In((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=In((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=Ce(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"||Pr(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:nn(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:nn(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:nn(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:nn(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?nn(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?nn(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const N=g||(((v=r.nextAction)==null?void 0:v.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?nn(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 mc(e){if(typeof e=="string")return n.jsx(Tr,{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:mc(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:lt(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 nn(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=Rr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:lt(t)}const wh=[/^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 vh(e){return wh.some(t=>t.test(e))}function pc(e){const t=dt(e);if(!t)return null;const s=Ce(t,["user_summary","userSummary"]);if(s)return s;const r=Ce(t,["task_title","taskTitle","dispatch_task_title"])??Ce(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),i=Ce(t,["event","event_name","eventName"]),a=Ce(t,["parsed_status","status"]),c=Ce(t,["stop_reason","stopReason"]),l=Ce(t,["artifact_type","artifactType"]),d=Ce(t,["artifact_title","title","name"]),u=Ce(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?lt(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=Ce(t,["decision_title","decisionTitle","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(i==="decision_resolved"){const p=Ce(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 Dr(e){const t=pc(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";return vh(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:lt(s)||lt(Ai(e.type)),isSystem:!1}}const kh=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),jh=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 Er(e){const t=dt(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&&jh.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function pl(e){var d;if(!e||!Er(e))return null;const t=dt(e),s=es((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=Ce(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),c=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",l=a?` for ${lt(a).toLowerCase()}`:"";return`${c}${l} were synced from local replay.`}function da(e){if(!Er(e))return null;const t=dt(e);if(!t)return null;const s=Ce(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=Ce(t,["event","event_name","eventName"])??"",i=Ce(t,["changeset_id","changesetId"])??"",a=Ce(t,["entity_type","entityType"])??"",c=Ce(t,["entity_id","entityId"])??"",l=Aa(e)??"",d=Dr(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function Nh(e){if(!e)return null;const t=dt(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 fl(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 Ih=[/^Autopilot dispatched slice for\s*/i,/^Orchestrator (selected|dispatched)\s*/i,/^Auto[-_]?continue.*?dispatching\s*/i,/^Slice (started|dispatched) for\s*/i];function hl(e,t){const s=pc(e);if(s)return s;let i=(nn(t??e.summary)??nn(e.description)??lt(e.title||Ai(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 Ih)i=i.replace(l,"");i=i.trim();const a=i.split(`
211
+ `).map(l=>fl(l).trim()).filter(l=>l.length>0&&!/^\|?[:\-| ]+\|?$/.test(l));let c=a[0]??fl(i);return c.length<24&&a.length>1&&(c=`${c} ${a[1]}`.trim()),c.length>108?`${c.slice(0,107).trimEnd()}…`:c}const Ah=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:v,onClearSelection:N,onClearWorkstreamFilter:f,onClearAgentFilter:C,onFocusRunId:H,onOpenDecision:Z,requestedActivityItemId:U=null,onActivityItemRequestHandled:fe,onPlayNextUp:K,onStartAutopilot:re,onPauseWorkstream:be,onCreateInitiative:ve,onOpenMissionControl:Se,onOpenSettings:me,workspaceId:Ke=null,chatSnapshot:pe,onRefreshData:ae,isLoading:te=!1,onOpenNextUp:ie,devMode:ke=!1,nextUpQueue:V,autopilotState:T=null}){var za;const z=ss(),{open:P}=Gl(),W=o.useMemo(()=>{if(!V)return new Map;const h=new Map;for(let k=0;k<V.length;k++){const w=V[k];h.set(w.workstreamId,{rank:k+1,title:w.workstreamTitle,state:w.queueState})}return h},[V]),[Q,xe]=o.useState("all"),[je,ne]=o.useState(!1),[ye,ge]=o.useState(""),[E,B]=o.useState(new Set),[G,se]=o.useState({}),[Re,Ge]=o.useState("oldest"),[Te,L]=o.useState(!1),[at,Le]=o.useState(!1),[Xe,bt]=o.useState(sa),[vt,kt]=o.useState(null),[O,_e]=o.useState(null),[he,Me]=o.useState(!1),[Qe,nt]=o.useState(1),[J,ze]=o.useState("structured"),[we,X]=o.useState(null),[$e,He]=o.useState("feed"),[De,rt]=o.useState(null),[ut,_t]=o.useState(null),[Dt,q]=o.useState(!1),[Ie,Ue]=o.useState(null),[Ve,qe]=o.useState(null),[Be,Pe]=o.useState(!1),[mt,Ft]=o.useState(null),[pt,gt]=o.useState(!1),At=o.useRef(Date.now()),st=o.useRef(null),Pt=o.useRef(null),Ye=o.useRef(null),zt=o.useRef(null),Ct=o.useRef(null),[St,Ht]=o.useState(()=>ri(g.startIso)),[jt,ln]=o.useState(()=>ri(g.endIso)),[rs,is]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),ks=o.useMemo(()=>Ml(x),[x]),Rn=o.useMemo(()=>ri(g.startIso),[g.startIso]),Vt=o.useMemo(()=>ri(g.endIso),[g.endIso]),kn=o.useMemo(()=>!St||!jt?!1:jt.getTime()>=St.getTime(),[jt,St]),js=o.useMemo(()=>x!=="custom"?ks.label:Rn&&Vt?`${ii(Rn)} - ${ii(Vt)}`:"Custom range",[Vt,Rn,x,ks.label]);o.useEffect(()=>{Ht(Rn),ln(Vt)},[Vt,Rn]),o.useEffect(()=>{if(typeof window>"u")return;const h=()=>is(window.innerWidth<=640);return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]),o.useEffect(()=>{const k=()=>{At.current=Date.now()};window.addEventListener("pointerdown",k),window.addEventListener("keydown",k);const w=setInterval(()=>{Date.now()-At.current>3e5&&gt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",k),window.removeEventListener("keydown",k),clearInterval(w)}},[]);const rn=o.useMemo(()=>{const h=s.filter(_=>_.status==="completed").length,k=s.filter(_=>_.status==="blocked"||_.status==="failed").length,w=t.filter(_=>{var ce;return _.type==="decision_requested"&&((ce=_.metadata)==null?void 0:ce.status)==="pending"}).length;return{completed:h,blocked:k,decisions:w}},[s,t]),as=o.useMemo(()=>{const h=new Map;for(const k of s)h.set(k.runId,k.title),h.set(k.id,k.title);return h},[s]),An=o.useMemo(()=>{const h=new Map;for(const k of s)k.status&&(h.set(k.runId,k.status),h.set(k.id,k.status));return h},[s]),Kn=o.useRef(new Map),Ln=o.useMemo(()=>{var k;const h=new Map;for(const w of s){const _={status:w.status??null,phase:w.phase??null,state:w.state??null,blockerCount:Array.isArray(w.blockers)?w.blockers.length:0,blockerReason:w.blockerReason??((k=w.blockerDiagnostics)==null?void 0:k.reason)??null};h.set(w.runId,_),h.set(w.id,_)}return sl(Kn.current,h)?Kn.current:(Kn.current=h,h)},[s]),Gn=o.useRef(new Map),os=o.useMemo(()=>{const h=new Map;for(const k of r){const w={status:k.status??null,blockingDecisions:Math.max(0,k.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(k.decisionCount??0)-(k.blockingDecisionCount??0)),updatedEpoch:ns(k.updatedAt??k.lastEventAt??k.startedAt??null)},_=[k.runId,k.sliceRunId].filter(ce=>typeof ce=="string"&&ce.trim().length>0).map(ce=>ce.trim());for(const ce of _){const Ne=h.get(ce);(!Ne||w.updatedEpoch>=Ne.updatedEpoch)&&h.set(ce,w)}}return sl(Gn.current,h)?Gn.current:(Gn.current=h,h)},[r]),Kt=o.useMemo(()=>{const h=new Map;for(const k of s){const w=uc(k.progress);w!==null&&(h.set(k.runId,w),h.set(k.id,w))}return h},[s]),Sn=o.useMemo(()=>{const h=new Map;for(const k of s)!k.agentId||!k.agentName||h.set(k.agentId,k.agentName);return h},[s]),jn=o.useMemo(()=>{const h=new Map;for(const k of s){const w=k.workstreamId??null;h.set(k.runId,w),h.set(k.id,w)}return h},[s]),ls=o.useMemo(()=>{const h=new Map;for(const k of r){const w=k.workstreamId??null,_=Cr(k.workstreamTitle,w);if(!_)continue;const ce=[k.runId,k.sliceRunId].filter(Ne=>typeof Ne=="string"&&Ne.trim().length>0).map(Ne=>Ne.trim());for(const Ne of ce)h.set(Ne,_)}return h},[r]),$=o.useMemo(()=>{const h=new Map;for(const k of i){const w=Cr(k.name,k.id);w&&h.set(k.id,w)}return h},[i]),le=o.useMemo(()=>{const h=new Map;for(const k of i)for(const w of k.workstreams??[]){const _=Cr(w.name,w.id);_&&h.set(w.id,_)}for(const k of r){const w=k.workstreamId??null;if(!w||h.has(w))continue;const _=Cr(k.workstreamTitle,w);_&&h.set(w,_)}return h},[i,r]);o.useMemo(()=>{const h=[...s];return h.sort((k,w)=>{const _=ns(k.updatedAt??k.lastEventAt??k.startedAt??null);return ns(w.updatedAt??w.lastEventAt??w.startedAt??null)-_}),h},[s]);const de=o.useMemo(()=>t.map(h=>{const k=Aa(h),w=Qf(h),_=dt(h),ce=k?Ln.get(k)??null:null,Ne=k?os.get(k)??null:null,Fe=Jf(h,_),Je=Vp({sessionStatus:Fe?null:(ce==null?void 0:ce.status)??(k?An.get(k)??null:null),sessionPhase:Fe?null:(ce==null?void 0:ce.phase)??null,sessionState:Fe?null:(ce==null?void 0:ce.state)??null,sliceStatus:Fe?null:(Ne==null?void 0:Ne.status)??null,activityType:h.type,activityStatus:Ce(_,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:Ce(_,["stop_reason","stopReason"]),decisionRequired:h.decisionRequired??!1,blockingDecisionCount:Ds(_,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ne==null?void 0:Ne.blockingDecisions)??0,nonBlockingDecisionCount:Ds(_,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ne==null?void 0:Ne.nonBlockingDecisions)??0,blockerCount:Fe?0:(ce==null?void 0:ce.blockerCount)??0,blockerReason:Fe?null:(ce==null?void 0:ce.blockerReason)??null}),It=eh(w,Je),Mt=[h.title,h.description,h.summary,h.agentName,Pf(_)].filter(qt=>typeof qt=="string"&&qt.length>0).join(" ").toLowerCase(),Oe=k?(as.get(k)??k).toLowerCase():"",Et=_==null?void 0:_.scope,Yt=Et==="milestone"||Et==="workstream"?Et:void 0;return{item:h,bucket:w,userState:It.state,userStateWhy:It.why,canonicalProjection:Je,runId:k,timestampEpoch:ns(h.timestamp),searchText:Mt,runLabelSearch:Oe,scopeGroupId:Yt?k??null:null,scope:Yt}}),[t,as,Ln,An,os]),Ee=o.useMemo(()=>{const h=[...de];return h.sort((k,w)=>{const _=w.timestampEpoch-k.timestampEpoch;return _!==0?_:w.item.id.localeCompare(k.item.id)}),h},[de]),wt=o.useMemo(()=>[...Ee].reverse(),[Ee]),Bt=o.useMemo(()=>{let h=0;for(const k of de)h=Math.max(h,k.timestampEpoch);return h<=0?!1:Date.now()-h<6e4},[de]),it=o.useMemo(()=>new Set(c.filter(h=>h&&h.trim().length>0)),[c]),Lt=it.size>0,qs=o.useMemo(()=>Lr.filter(h=>["live","24h","7d","all"].includes(h.id)),[]),ht=o.useMemo(()=>{if(!Lt)return null;for(const h of it){const k=s.find(w=>w.runId===h||w.id===h);if(k)return k}return null},[Lt,it,s]),Ns=o.useMemo(()=>Lt?ht!=null&&ht.runtimeProvider?{id:Ff(ht.runtimeProvider)}:bs(ht==null?void 0:ht.agentId,ht==null?void 0:ht.agentName,ht==null?void 0:ht.title,ht==null?void 0:ht.lastEventSummary,ht==null?void 0:ht.runtimeClient,l):bs(),[ht,Lt,l]),Tt=o.useMemo(()=>p?bs(p):bs(),[p]),{filtered:Nt,filteredTotal:pn,hiddenCount:Xn,hiddenSyncCount:_n}=o.useMemo(()=>{const h=Re==="newest"?Ee:wt,k=[];let w=0,_=0,ce=0;const Ne=new Set,Fe=ye.trim().toLowerCase();for(const Oe of h){const Et=Oe.runId;if(Lt&&(!Et||!it.has(Et)))continue;if(d){const Vs=Zs(Oe.item),_s=Et?jn.get(Et)??null:null;if((Vs??_s)!==d)continue}const Yt=tr(Oe.item);if(p&&Yt.agentName!==p){ce++;continue}if(!ke){const Vs=dt(Oe.item),_s=Ce(Vs,["event","event_name","eventName"]);if(_s&&kh.has(_s))continue}const qt=da(Oe.item);if(qt){if(Ne.has(qt)){_+=1;continue}if(Ne.add(qt),!je){_+=1;continue}}else if(!je&&Er(Oe.item)){_+=1;continue}Q==="completed"&&Oe.userState!=="completed"||Q==="needs_attention"&&Oe.userState!=="needs_input"&&Oe.userState!=="issue"||Q==="in_progress"&&Oe.userState!=="in_progress"||Fe.length>0&&!`${Oe.searchText} ${Oe.runLabelSearch}`.includes(Fe)||(k.length<el?k.push(Oe):w+=1)}const Je=Math.min(Math.max(1,Math.min(Zo,Xe)),k.length),It=k.slice(0,Je),Mt=k.length+w;return{filtered:It,filteredTotal:Mt,hiddenCount:Math.max(0,Mt-It.length),hiddenSyncCount:_,skippedByAgent:ce}},[Q,p,Ee,wt,Lt,ye,Xe,d,it,jn,je,Re]),Is=o.useMemo(()=>{if(!p)return null;let h=0;for(const k of t)if(tr(k).agentName===p){const _=ns(k.timestamp);_>h&&(h=_)}return h===0?null:$t(h)},[p,t]),fn=o.useMemo(()=>{const h=new Map;for(const w of Nt){const _=Yf(w.item.timestamp),ce=h.get(_);ce?ce.push(w):h.set(_,[w])}return Array.from(h.keys()).sort((w,_)=>{const ce=Number(_)-Number(w);return Re==="newest"?ce:-ce}).map(w=>({key:w,label:Zf(w),items:h.get(w)??[]}))},[Nt,Re]),on=o.useMemo(()=>fn.map(h=>{const k=new Map;for(const w of h.items){const _=Dr(w.item).title.trim().toLowerCase(),ce=da(w.item),Ne=dt(w.item),Fe=Ce(Ne,["event","event_name","eventName"]),Je=(Fe==null?void 0:Fe.startsWith("autopilot_"))||(Fe==null?void 0:Fe.startsWith("auto_continue_")),It=Zs(w.item),Mt=ce?`${w.item.type}::sync::${ce}`:Je&&It?`autopilot::${It}::${Math.floor(w.timestampEpoch/3e5)}`:`${w.item.type}::${_}`,Oe=k.get(Mt);Oe?(Oe.count+=1,Oe.firstTimestamp=Math.min(Oe.firstTimestamp,w.timestampEpoch),Oe.allItems.push(w),w.timestampEpoch>Oe.representative.timestampEpoch&&(Oe.representative=w)):k.set(Mt,{key:Mt,representative:w,count:1,firstTimestamp:w.timestampEpoch,allItems:[w]})}return{...h,clusters:Array.from(k.values())}}),[fn]),$n=o.useCallback(h=>{B(k=>{const w=new Set(k);return w.has(h)?w.delete(h):w.add(h),w}),se(k=>{if(Object.prototype.hasOwnProperty.call(k,h)){const w={...k};return delete w[h],w}return{...k,[h]:Sr}})},[]),Qn=o.useCallback((h,k)=>{se(w=>{const _=w[h]??Sr,ce=Math.min(k,_+Sr);return ce===_?w:{...w,[h]:ce}})},[]),zs=o.useCallback(()=>{!j||!b||!St||!jt||jt.getTime()<St.getTime()||(j({startIso:St.toISOString(),endIso:jt.toISOString()}),b("custom"),Le(!1))},[jt,St,j,b]),Jn=o.useCallback(()=>{Ht(null),ln(null),j==null||j({startIso:null,endIso:null}),x==="custom"&&(b==null||b("live"))},[j,b,x]),Dn=o.useMemo(()=>Math.min(Zo,Math.min(el,pn)),[pn]);o.useEffect(()=>{bt(sa),B(new Set),se({})},[Q,p,Lt,ye,d,je,Re,x]),o.useEffect(()=>{if(!Te)return;const h=w=>{var ce;const _=w.target;_ instanceof Node&&((ce=st.current)!=null&&ce.contains(_)||L(!1))},k=w=>{w.key==="Escape"&&L(!1)};return window.addEventListener("pointerdown",h),window.addEventListener("keydown",k),()=>{window.removeEventListener("pointerdown",h),window.removeEventListener("keydown",k)}},[Te]),o.useEffect(()=>{if(!at)return;const h=w=>{var ce;const _=w.target;_ instanceof Node&&((ce=Pt.current)!=null&&ce.contains(_)||Le(!1))},k=w=>{w.key==="Escape"&&Le(!1)};return window.addEventListener("pointerdown",h),window.addEventListener("keydown",k),()=>{window.removeEventListener("pointerdown",h),window.removeEventListener("keydown",k)}},[at]);const Fn=o.useRef(v);Fn.current=v;const ar=o.useRef(y);ar.current=y;const Or=o.useRef(I);Or.current=I;const[Ws,Ei]=o.useState(!1),an=o.useRef(null),cs=o.useRef(x),Br=o.useRef(Date.now()),or=o.useRef(!1);o.useEffect(()=>{cs.current!==x&&(cs.current=x,an.current=null,Br.current=Date.now(),or.current=!1)},[x]),o.useEffect(()=>{const h=Ye.current,k=zt.current;if(!h||!k)return;const w=new IntersectionObserver(ce=>{const Ne=ce.some(Fe=>Fe.isIntersecting);Ei(Ne)},{root:h,rootMargin:"0px 0px 600px 0px"});w.observe(k);const _=()=>{or.current=!0};return h.addEventListener("scroll",_,{passive:!0}),()=>{w.disconnect(),h.removeEventListener("scroll",_)}},[]),o.useEffect(()=>{var h;if(Ws){if(Nt.length<Dn){bt(k=>Math.min(Dn,Math.max(k,sa)+Df));return}if(ar.current&&!Or.current){(h=Fn.current)==null||h.call(Fn);return}}},[Nt.length,Dn,Ws]),o.useEffect(()=>{if(!Ws||y||I||!b)return;const h=Ye.current,k=h?h.scrollHeight<=h.clientHeight+4:!1;if(!or.current&&!k||Date.now()-Br.current<3e3)return;const _=nl(x);_&&an.current!==_&&(an.current=_,b(_))},[Nt.length,y,I,b,Ws,x]);const Pn=o.useMemo(()=>vt?Nt.findIndex(h=>h.item.id===vt):-1,[vt,Nt]),R=Pn>=0?Nt[Pn]:null,On=o.useMemo(()=>{var k;const h=new Map;for(const w of a){const _=(k=w==null?void 0:w.sliceRunId)==null?void 0:k.trim();!_||h.has(_)||h.set(_,w)}return h},[a]),dn=o.useMemo(()=>{if(!R)return null;const h=R.runId??Aa(R.item);return h?On.get(h)??null:null},[R,On]),Bn=o.useMemo(()=>cc((R==null?void 0:R.item)??null),[R]),Yn=o.useMemo(()=>ia((R==null?void 0:R.item)??null),[R]),lr=o.useMemo(()=>lc((R==null?void 0:R.item)??null),[R]),ds=o.useMemo(()=>lr?null:hh((R==null?void 0:R.item)??null,t),[lr,R,t]),et=o.useMemo(()=>R?ll(R.item):null,[R]),qn=o.useMemo(()=>et?et.executor??et.requester:null,[et]),ee=lr??(ds==null?void 0:ds.detail)??null,un=o.useMemo(()=>{var h,k;return ca((ee==null?void 0:ee.requesterAgentName)??((h=et==null?void 0:et.requester)==null?void 0:h.name)??null,(ee==null?void 0:ee.requesterAgentId)??((k=et==null?void 0:et.requester)==null?void 0:k.id)??null,Sn)},[ee,et,Sn]),us=o.useMemo(()=>zf(un),[un]),zn=o.useMemo(()=>{var k,w;const h=ca((ee==null?void 0:ee.agentName)??((k=et==null?void 0:et.executor)==null?void 0:k.name)??null,(ee==null?void 0:ee.agentId)??((w=et==null?void 0:et.executor)==null?void 0:w.id)??null,Sn);return h==="—"?(et==null?void 0:et.primaryLabel)??"Codex":h},[ee,et,Sn]),qr=o.useMemo(()=>R!=null&&R.runId?Kt.get(R.runId)??null:null,[R,Kt]),Gt=o.useMemo(()=>yh(ee,qr),[ee,qr]),D=o.useMemo(()=>{const h=ee;if(!h)return null;const k=h.initiativeId??(R==null?void 0:R.item.initiativeId)??null,w=k?i.find(qt=>qt.id===k)??null:null,_=h.initiativeTitle??(w==null?void 0:w.name)??null,ce=h.initiativeStatus??(w==null?void 0:w.status)??null,Ne=(w==null?void 0:w.workstreams)??[],Fe=Ne.length>0?Ne.length:null,Je=Fe!==null?Ne.filter(qt=>Pr(qt.status)).length:null,It=Fe&&Je!==null?Math.round(Je/Fe*100):null,Mt=h.workstreamId??null,Oe=Mt&&Ne.length>0?Ne.find(qt=>qt.id===Mt)??null:null,Et=h.workstreamTitle??(Oe==null?void 0:Oe.name)??(Mt?le.get(Mt)??null:null),Yt=h.workstreamStatus??(Oe==null?void 0:Oe.status)??null;return{initiativeId:k,initiativeTitle:_,initiativeStatus:ce,totalInitiativeWorkstreams:Fe,doneInitiativeWorkstreams:Je,initiativeWorkstreamPct:It,workstreamId:Mt,workstreamTitle:Et,workstreamStatus:Yt,taskTitle:h.taskTitle,milestoneTitle:h.milestoneTitle,scopedTaskCount:h.taskIds.length,scopedMilestoneCount:h.milestoneIds.length,statusUpdatesApplied:h.statusUpdatesApplied,statusUpdatesBuffered:h.statusUpdatesBuffered,artifacts:h.artifacts,decisions:h.decisions,blockingDecisions:h.blockingDecisions,nonBlockingDecisions:h.nonBlockingDecisions,tokensUsed:h.tokensUsed,tokenBudget:h.tokenBudget,nextStep:h.nextStep,phase:h.phase,stopReason:h.stopReason,parsedStatus:h.parsedStatus}},[ee,R,i,le]),Wt=o.useMemo(()=>R?bh(R.item,ee,D?{decisions:D.decisions,blockingDecisions:D.blockingDecisions,nonBlockingDecisions:D.nonBlockingDecisions,stopReason:D.stopReason,parsedStatus:D.parsedStatus}:null,R.canonicalProjection??null):null,[ee,R,D]),cr=o.useMemo(()=>{if(!D)return[];const h=[];Wt&&h.push({label:"Status",value:Wt.label}),D.scopedTaskCount>0&&h.push({label:"Tasks",value:D.scopedTaskCount}),D.scopedMilestoneCount>0&&h.push({label:"Milestones",value:D.scopedMilestoneCount});const k=D.artifacts??0;k>0&&h.push({label:"Artifacts",value:k});const w=D.decisions??0;w>0&&h.push({label:"Decisions",value:w}),D.blockingDecisions&&D.blockingDecisions>0&&h.push({label:"Blocking",value:D.blockingDecisions,tone:"critical"}),D.stopReason&&h.push({label:"Stop reason",value:xr(D.stopReason)??lt(D.stopReason)});const _=Oc(D.tokensUsed,D.tokenBudget);return _&&h.push({label:"Token usage",value:_}),h},[D,Wt]),Wn=o.useMemo(()=>{const h=new Set;for(const k of ph((R==null?void 0:R.item)??null))h.add(k);for(const k of(ee==null?void 0:ee.decisionIds)??[])h.add(k);for(const k of(ee==null?void 0:ee.blockingDecisionIds)??[])h.add(k);for(const k of(ee==null?void 0:ee.nonBlockingDecisionIds)??[])h.add(k);return Array.from(h)},[ee,R]),Us=o.useMemo(()=>Z?Wn.length>0||(R==null?void 0:R.item.decisionRequired)===!0||((D==null?void 0:D.blockingDecisions)??0)>0?!0:(Wt==null?void 0:Wt.label)==="Needs decision":!1,[Wn,R,D,Wt,Z]),dr=o.useMemo(()=>Gt?Gt.tone==="positive"?M.lime:Gt.tone==="warning"?M.amber:Gt.tone==="critical"?M.red:M.teal:M.teal,[Gt]),ur=(Gt==null?void 0:Gt.terminalStop)===!0,tt=o.useMemo(()=>nh(dt((R==null?void 0:R.item)??null)),[R]),mr=o.useMemo(()=>dt((R==null?void 0:R.item)??null),[R]),m=o.useMemo(()=>lh((R==null?void 0:R.item)??null,ee),[ee,R]),A=o.useMemo(()=>{if(!(m!=null&&m.retryAt))return null;const h=new Date(m.retryAt);if(!Number.isFinite(h.getTime()))return null;const k=h.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),w=$t(m.retryAt);return w?`${k} (${w})`:k},[m]),F=o.useMemo(()=>R?tr(R.item):{agentId:null,agentName:null},[R]),S=o.useMemo(()=>ml(Ps(R==null?void 0:R.item.metadata)??void 0),[R]);o.useMemo(()=>ml(mr),[mr]);const Y=o.useMemo(()=>{const h=dc((R==null?void 0:R.item)??null);return h.length>0?h:fh((R==null?void 0:R.item)??null,t,new Set)},[R,t]),Ae=o.useMemo(()=>Y.filter((h,k,w)=>w.findIndex(_=>_.path===h.path)===k),[Y]),ct=o.useMemo(()=>Ae.slice(0,4),[Ae]),We=o.useMemo(()=>Ae.slice(4),[Ae]),Ze=o.useMemo(()=>{if(Ae.length===0)return null;const h=Ae[0];return h?la(h.path):null},[Ae]),ft=o.useMemo(()=>{var _;const h=nn(we);if(h)return h;const k=pl((R==null?void 0:R.item)??null);if(k)return k;const w=nn(R==null?void 0:R.item.summary)??nn(R==null?void 0:R.item.description);if(w)return w;if(R){const ce=R.item,Ne=dt(ce),Fe=Ce(Ne,["agent_name","agentName"])??ce.agentName??"OrgX",Je=Ce(Ne,["task_title","taskTitle","workstream_title","workstreamTitle"]),It=((_=ce.type)==null?void 0:_.replace(/_/g," "))??"activity";return Je?`${Fe} worked on ${Je}`:`${Fe} recorded a ${It}`}return null},[we,R]),Rt=o.useMemo(()=>R?Er(R.item):!1,[R]),tn=o.useMemo(()=>{if(!ee||!R)return null;const h=ee.initiativeId??R.item.initiativeId??null,k=ee.workstreamId??Zs(R.item);if(!h||!k)return null;const w=In((D==null?void 0:D.parsedStatus)??ee.parsedStatus),_=In((D==null?void 0:D.stopReason)??ee.stopReason),ce=Math.max(0,(D==null?void 0:D.blockingDecisions)??ee.blockingDecisions??(R.item.decisionRequired?1:0)),Ne=Math.max(0,(D==null?void 0:D.nonBlockingDecisions)??ee.nonBlockingDecisions??0),Fe=w==="blocked"||w==="error"||w==="failed"||_==="blocked"||_==="error"||R.item.type==="blocker_created",Je=!Fe&&ce===0&&Ne>0&&(w==="needs_decision"||w==="completed"||_==="completed");return!Fe&&!Je?null:{initiativeId:h,workstreamId:k,runId:R.runId??null,event:ee.event,requestedByAgentId:ee.requesterAgentId??R.item.requesterAgentId??null,requestedByAgentName:ee.requesterAgentName??R.item.requesterAgentName??null,actionLabel:Fe?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Fe?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Fe}},[ee,R,D]),Cn=o.useCallback(()=>{kt(null)},[]),pr=o.useCallback(async(h,k)=>{if(k){qe(null),Ue(h);try{await k()}catch(w){qe(w instanceof Error?w.message:"Action failed")}finally{Ue(w=>w===h?null:w)}}},[]),As=o.useCallback(async()=>{var h;if(!(!tn||Be)){Pe(!0),Ft(null);try{const k=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:tn.initiativeId,workstreamId:tn.workstreamId,runId:tn.runId,event:tn.event,requestedByAgentId:tn.requestedByAgentId,requestedByAgentName:tn.requestedByAgentName,graceMs:1e4})}),w=await k.json().catch(()=>null);if(!k.ok||(w==null?void 0:w.ok)!==!0)throw new Error((w==null?void 0:w.error)||`Request failed (${k.status})`);const _=(h=w==null?void 0:w.scheduled)!=null&&h.dueAt?new Date(w.scheduled.dueAt):null,ce=_&&Number.isFinite(_.getTime())?_.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Ft(ce?`Scheduled. Auto action starts by ${ce} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(k){const w=k instanceof Error?k.message:"Failed to schedule auto-fix";Ft(Ut(w)||w)}finally{Pe(!1)}}},[tn,Be]);o.useEffect(()=>{if(!O)return;const h=window.setTimeout(()=>_e(null),2e3);return()=>window.clearTimeout(h)},[O]),o.useEffect(()=>{qe(null)},[Q,ye,x]),o.useEffect(()=>{if(!U){Ct.current=null;return}const h=U.trim();!h||Ct.current===h||!t.some(w=>w.id===h)||(Ct.current=h,xe("all"),ge(""),nt(1),kt(h),fe==null||fe(h))},[t,fe,U]);const Mn=o.useCallback(async(h,k)=>{if(k)try{await navigator.clipboard.writeText(k),_e(`${h} copied`)}catch{_e("Copy failed")}},[]);o.useEffect(()=>{ze("structured"),Me(!1),Pe(!1),Ft(null)},[vt]),o.useEffect(()=>{X(null),He("feed");const h=Nh((R==null?void 0:R.item)??null);if(!h||Xt())return;const k=new URLSearchParams({turnId:h.turnId});h.sessionKey&&k.set("sessionKey",h.sessionKey),h.runId&&k.set("run",h.runId);const w=new AbortController;return fetch(`/orgx/api/live/activity/detail?${k.toString()}`,{method:"GET",signal:w.signal}).then(async _=>{var Ne;return _.ok?((Ne=(await _.json()).detail)==null?void 0:Ne.summary)??null:(_.status===404&&He("missing"),null)}).then(_=>{typeof _=="string"&&_.trim().length>0?(X(_),He("local")):He("missing")}).catch(_=>{_ instanceof DOMException&&_.name==="AbortError"||He("missing")}),()=>w.abort()},[R]),o.useEffect(()=>{rt(null),_t(null);const h=R==null?void 0:R.item;if(!h||Dt)return;const k=(we??h.summary??h.description??h.title??"").trim();if(!k||Xt())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:k,title:h.title??null,type:h.type})}).then(async _=>_.ok?await _.json():((_.status===404||_.status===405)&&q(!0),null)).then(_=>{const ce=_==null?void 0:_.headline;typeof ce=="string"&&ce.trim().length>0&&(q(!1),rt(ce.trim()),_t((_==null?void 0:_.source)??null))}).catch(_=>{_ instanceof DOMException&&_.name}),()=>w.abort()},[R,we,Dt]);const Ss=o.useCallback(h=>{var _;if(Nt.length===0)return;const w=((Pn>=0?Pn:0)+h+Nt.length)%Nt.length;nt(h),kt(((_=Nt[w])==null?void 0:_.item.id)??null)},[Pn,Nt]);o.useEffect(()=>{vt&&(Pn>=0||kt(null))},[Pn,vt]),o.useEffect(()=>{if(!vt)return;const h=k=>{k.key==="ArrowRight"||k.key.toLowerCase()==="l"?(k.preventDefault(),Ss(1)):(k.key==="ArrowLeft"||k.key.toLowerCase()==="h")&&(k.preventDefault(),Ss(-1))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[vt,Ss]);const ms=it.size===1,ps=ms?[...it][0]:null,fr=ps?s.find(h=>h.runId===ps||h.id===ps)??null:null,Ri=o.useMemo(()=>{if(!ms)return[];const h=[],k=new Set;for(const w of de){if(!w.runId||!it.has(w.runId))continue;const _=da(w.item);if(_){if(k.has(_)||(k.add(_),!je))continue}else if(!je&&Er(w.item))continue;h.push(w.item)}return h},[ms,de,it,je]),qa=!z&&Nt.length<=160,Hs=(h,k,w)=>{const _=h.item,ce=w??_.id,Ne=tr(_),Fe=ll(_),Je=Vf(_,Fe),It=Fe.executor??Fe.requester,Mt=ca(mn((It==null?void 0:It.name)??Fe.primaryLabel??_.agentName??Ne.agentName??null),mn((It==null?void 0:It.id)??_.agentId??Ne.agentId??null),Sn)||"OrgX",Oe=Gf(Je)||Mt,Et=Kf[Je]||oa(h.userState),Yt=Re==="newest"&&k<2,qt=h.runId,Vs=pl(_),{title:_s}=Dr(_),zr=Vs??nn(_.summary),Li=nn(_.description),Wa=hl(_,zr??Li??null),Ua=dt(_),Ha=li([{value:Ce(Ua,["initiative_title","initiativeTitle"]),idHint:_.initiativeId},{value:_.initiativeId?$.get(_.initiativeId)??null:null,idHint:_.initiativeId}]),fs=Zs(_)??(qt?jn.get(qt)??null:null),Va=li([{value:Ce(Ua,["workstream_title","workstreamTitle"]),idHint:fs},{value:fs?le.get(fs)??null:null,idHint:fs},{value:qt?ls.get(qt)??null:null,idHint:fs}]),fc=[Ha,Va].filter(Boolean).join(" > "),hr=fs?W.get(fs):void 0,hc=(T==null?void 0:T.state)==="running"&&fs===(T==null?void 0:T.activeWorkstreamId),gc=hr?` — #${hr.rank} in queue`:"",xc=(fc||Ha||Va||lt(_.type))+(hc?gc:""),yc=aa(h.userState),bc=new Date(_.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),wc=$t(_.timestamp),vc=h.bucket==="artifact"?rh(_):null,Ka=ih(_);return n.jsx(df,{renderKey:ce,displayTitle:_s,headline:Wa,contextLabel:xc,detailText:(zr??Li)!==Wa?zr??Li:null,displayAgentName:Oe,railColor:Et,userStateLabel:yc,userStateWhy:h.userStateWhy,relativeTime:wc,timeLabel:bc,isRecent:Yt,enableMotion:qa,onOpen:()=>{nt(1),kt(_.id)},ariaLabel:`Open activity details for ${_s||Ai(_.type)}`,artifactSnippet:vc,evidenceChips:Ka.length>0?Ka:void 0,actorCategory:Je,queuePosition:hr?{rank:hr.rank,state:hr.state}:null},ce)};return n.jsx(If,{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:[ms&&Ri.length>0?n.jsx(af,{items:Ri,session:fr,agentName:((za=Ri[0])==null?void 0:za.agentName)??null,onBack:N,onOpenItem:h=>{nt(1),kt(h.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:pn}),Xn>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:["+",Xn," hidden"]}),_n>0&&!je&&n.jsxs("button",{type:"button",onClick:()=>ne(!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:[_n," sync hidden"]}),je&&n.jsx("button",{type:"button",onClick:()=>ne(!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:oe("h-1.5 w-1.5 flex-shrink-0 rounded-full",Bt&&"pulse-soft"),style:{backgroundColor:M.lime},"aria-label":"Live",title:Bt?"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:h=>ge(h.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(h=>!h),L(!1)},"aria-haspopup":"menu","aria-expanded":at,className:oe("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",at?"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:js}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:oe("transition-transform duration-200",at&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:at&&n.jsx(ue.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute left-0 z-30 mt-2 w-[min(92vw,380px)] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity time range",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Presets"}),n.jsx("div",{className:"flex flex-wrap gap-1",children:Lr.filter(h=>h.id!=="custom").map(h=>{const k=x===h.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(h.id),Le(!1)},className:oe("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",k?"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:h.label},h.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"}),rs?n.jsx("input",{type:"datetime-local",step:300,value:ra(St),onChange:h=>Ht(il(h.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(Ga,{selected:St,onChange:h=>Ht(h instanceof Date?h:null),selectsStart:!0,startDate:St,endDate:jt,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"}),rs?n.jsx("input",{type:"datetime-local",step:300,min:ra(St),value:ra(jt),onChange:h=>ln(il(h.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(Ga,{selected:jt,onChange:h=>ln(h instanceof Date?h:null),selectsEnd:!0,minDate:St??void 0,startDate:St,endDate:jt,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:kn?`${ii(St)} - ${ii(jt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:Jn,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:zs,disabled:!kn,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:[(Lt||d||p)&&n.jsxs(n.Fragment,{children:[Lt&&n.jsxs("button",{onClick:N,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[rl(Ns.id)?n.jsx(sr,{provider:Ns.id,size:"xs"}):n.jsx(Qt,{name:(ht==null?void 0:ht.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:f,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:[rl(Tt.id)?n.jsx(sr,{provider:Tt.id,size:"xs"}):n.jsx(Qt,{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(h=>{const k=Q===h;return n.jsx("button",{type:"button",onClick:()=>xe(h),"aria-pressed":k,className:oe("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",k?"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[h]},h)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:st,children:[n.jsxs("button",{type:"button",onClick:()=>{L(h=>!h),Le(!1)},"aria-haspopup":"menu","aria-expanded":Te,"aria-label":"Activity filters",title:"Activity filters",className:oe("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Te?"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:oe("transition-transform duration-200",Te&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Te&&n.jsx(ue.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(h=>n.jsx("button",{type:"button",onClick:()=>{Ge(h.id),L(!1)},className:oe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",Re===h.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:h.label},h.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(h=>{const k=Q===h;return n.jsx("button",{type:"button",onClick:()=>{xe(h),L(!1)},className:oe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",k?"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[h]},h)})})]}),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:()=>{ne(h=>!h)},className:oe("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",je?"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:je?"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:Ye,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[Nt.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(Ti,{icon:"activity",headline:te?"Syncing activity feed...":Lt?"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. ${pn>0?`${pn} events in other categories.`:""}`:V&&V.length>0?`Waiting for autopilot to start. Queue has ${V.length} item${V.length===1?"":"s"} ready.`:"No activity yet",description:te?"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.${Is?` Last active: ${Is}.`:""}`:`Try widening the time window (${js}), 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:qs.map(h=>{const k=x===h.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(h.id),className:oe("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",k?"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:h.label},`empty-time-${h.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"}),(Lt||d||Q!=="all")&&n.jsx("button",{type:"button",onClick:()=>{Lt&&N(),d&&(f==null||f()),p&&(C==null||C()),Q!=="all"&&xe("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"}),K&&n.jsx("button",{type:"button",onClick:()=>void pr("play",K),disabled:Ie!==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:Ie==="play"?"Starting...":"Start next session"}),!K&&Se&&n.jsx("button",{type:"button",onClick:Se,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(of,{completedCount:rn.completed,decisionsCount:rn.decisions,blockerCount:rn.blocked,visible:pt,onDismiss:()=>{gt(!1),At.current=Date.now()}}),Nt.length>0&&n.jsxs("div",{className:"space-y-4",children:[on.map(h=>{const k=h.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:h.label}),qa?n.jsx(yt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:k.map((w,_)=>{const ce=E.has(w.key),Ne=w.allItems.slice(1),Fe=Ne.length,Je=Math.min(Fe,G[w.key]??Sr),It=Ne.slice(0,Je);if(w.count===1)return Hs(w.representative,_);if(w.key.startsWith("autopilot::")&&w.count>=3){const Oe=ul(w);return n.jsx(Yo,{workstreamTitle:Oe.workstreamTitle,items:Oe.items,firstTimestamp:w.firstTimestamp,lastTimestamp:w.representative.timestampEpoch,onExpandItem:Et=>{const Yt=w.allItems[Et];Yt&&kt(Yt.item.id)}},w.key)}const Mt=`cluster:${w.key}`;return n.jsxs("div",{children:[Hs(w.representative,_,Mt),n.jsxs("button",{type:"button",onClick:Oe=>{Oe.stopPropagation(),$n(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:ce?"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:oe("transition-transform",ce?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ce&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[It.map((Oe,Et)=>Hs(Oe,_+Et+1)),Je<Fe&&n.jsxs("button",{type:"button",onClick:Oe=>{Oe.stopPropagation(),Qn(w.key,Fe)},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 (",Fe-Je," remaining)"]})]})]},w.key)})})}):n.jsx("div",{className:"space-y-2",children:k.map((w,_)=>{const ce=E.has(w.key),Ne=w.allItems.slice(1),Fe=Ne.length,Je=Math.min(Fe,G[w.key]??Sr),It=Ne.slice(0,Je);if(w.count===1)return Hs(w.representative,_);if(w.key.startsWith("autopilot::")&&w.count>=3){const Oe=ul(w);return n.jsx(Yo,{workstreamTitle:Oe.workstreamTitle,items:Oe.items,firstTimestamp:w.firstTimestamp,lastTimestamp:w.representative.timestampEpoch,onExpandItem:Et=>{const Yt=w.allItems[Et];Yt&&kt(Yt.item.id)}},w.key)}const Mt=`cluster:${w.key}`;return n.jsxs("div",{children:[Hs(w.representative,_,Mt),n.jsxs("button",{type:"button",onClick:Oe=>{Oe.stopPropagation(),$n(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:ce?"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:oe("transition-transform",ce?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ce&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[It.map((Oe,Et)=>Hs(Oe,_+Et+1)),Je<Fe&&n.jsxs("button",{type:"button",onClick:Oe=>{Oe.stopPropagation(),Qn(w.key,Fe)},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 (",Fe-Je," remaining)"]})]})]},w.key)})})]},h.key)}),n.jsx("div",{ref:zt,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:oe("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&&Nt.length>0&&!nl(x)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:Xn>0?`${Nt.length} of ${pn} events`:"Beginning of activity history"})]})]})]}),ke?n.jsx($f,{}):null,n.jsx(uf,{open:R!==null,onClose:Cn,children:R&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:oa(R.userState),boxShadow:`0 0 12px ${oa(R.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[aa(R.userState)," · ",Pn+1,"/",Nt.length," sessions"]}),O&&n.jsx(Tn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:O})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[R.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(R.runId),Cn()},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:()=>Ss(-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:()=>Ss(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:()=>Me(h=>!h),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"})]})}),he&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Me(!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:[R.runId&&n.jsx("button",{type:"button",onClick:()=>{Mn("Run id",R.runId??""),Me(!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"}),F.agentId&&n.jsx("button",{type:"button",onClick:()=>{Mn("Agent id",F.agentId??""),Me(!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:()=>{Mn("Event id",R.item.id),Me(!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:Cn,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(yt,{mode:"wait",custom:Qe,children:n.jsx(ue.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||hl(R.item,we)||lt(R.item.title||Ai(R.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(R.item.timestamp).toLocaleString()," · ",$t(R.item.timestamp),ut==="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 h=dt(R.item),k=(ee==null?void 0:ee.workstreamId)??Zs(R.item)??(R.runId?jn.get(R.runId)??null:null),w=li([{value:(ee==null?void 0:ee.workstreamTitle)??null,idHint:k},{value:Ce(h,["workstream_title","workstreamTitle"]),idHint:k},{value:k?le.get(k)??null:null,idHint:k},{value:R.runId?ls.get(R.runId)??null:null,idHint:k}]),ce=[li([{value:(ee==null?void 0:ee.initiativeTitle)??null,idHint:R.item.initiativeId},{value:Ce(h,["initiative_title","initiativeTitle"]),idHint:R.item.initiativeId},{value:R.item.initiativeId?$.get(R.item.initiativeId)??null:null,idHint:R.item.initiativeId}]),w].filter(Boolean).join(" > ");return ce?n.jsx(Tn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:ce})}):null})(),n.jsx(Tn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:aa(R.userState)}),n.jsxs(Tn,{tone:"muted",children:[n.jsx(Qt,{name:(qn==null?void 0:qn.label)??(et==null?void 0:et.primaryLabel)??"OrgX",hint:qn?cl(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"})]}),Rt&&n.jsx(Tn,{tone:"lime",children:"Sync replay"})]})]}),R&&ia(R.item)&&!Bn&&n.jsxs("button",{type:"button",onClick:()=>{const h=ia(R.item);h&&P(h)},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:M.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:M.cyan},children:"View registered artifact"})]}),n.jsx(ff,{item:R.item}),Bn&&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:Bn.source==="metadata"?"Artifact":lt(Bn.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[ke&&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:()=>ze("structured"),"aria-pressed":J==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${J==="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:()=>ze("json"),"aria-pressed":J==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${J==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Yn&&n.jsx("button",{type:"button",onClick:()=>P(Yn),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:J==="structured"?mc(Bn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(Bn.value,null,2)})})})]}),Wt&&n.jsxs("div",{className:oe("rounded-xl border px-3.5 py-3",Wt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Wt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Wt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Wt.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:Wt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Wt.summary}),Wt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Wt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[R.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(R.runId),Cn()},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"}),Us&&n.jsx("button",{type:"button",onClick:()=>{Z==null||Z(Wn[0]??null),Cn()},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:Wn.length>0?"Resolve decision":"Resolve decisions"}),Yn&&!Bn&&n.jsx("button",{type:"button",onClick:()=>P(Yn),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"}),Ze&&n.jsx("a",{href:Ze,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"}),tn&&n.jsx("button",{type:"button",onClick:()=>void As(),disabled:Be,className:oe("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",tn.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:Be?"Scheduling...":tn.actionLabel})]}),tn&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:mt??tn.helperText})]}),(()=>{const h=dt(R.item),k=h==null?void 0:h.outcomes,w=h==null?void 0:h.task_updates;if(!k&&(!w||w.length===0))return null;const _=k==null?void 0:k.pr_url,ce=k==null?void 0:k.pr_number,Ne=k==null?void 0:k.commit_sha,Fe=k==null?void 0:k.commit_url,Je=k==null?void 0:k.tests;return _||Ne||Je||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"}),_&&n.jsxs("a",{href:_,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:ce?`#${ce}`:"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"})})]}),Ne&&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:Ne.slice(0,7)})]}),Fe&&n.jsx("a",{href:Fe,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary hover:text-primary transition-colors",children:"View"})]}),Je&&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:(Je.failed??0)>0?M.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:(Je.failed??0)>0?M.red:"rgba(103,232,249,0.7)"},children:"Tests"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[Je.passed??0," passed",(Je.failed??0)>0&&n.jsxs("span",{className:"text-red-300",children:[" · ",Je.failed," failed"]}),(Je.skipped??0)>0&&n.jsxs("span",{className:"text-muted",children:[" · ",Je.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((Mt,Oe)=>n.jsxs("li",{className:"text-caption text-secondary",children:[Mt.title?`"${Mt.title}"`:"Task",Mt.status?` → ${lt(Mt.status)}`:""]},Oe))})]})]}):null})(),m&&!ke&&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&&ke&&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(Tn,{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(Tn,{tone:"muted",children:["Domain: ",lt(m.domain)]}),m.modelTier&&n.jsxs(Tn,{tone:"muted",children:["Tier: ",lt(m.modelTier)]}),A&&n.jsxs(Tn,{tone:"muted",children:["Retry: ",A]}),!A&&m.retryInMs!==null&&n.jsxs(Tn,{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:nn(m.blockedReason)??m.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[me&&n.jsx("button",{type:"button",onClick:me,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"}),tn&&n.jsx("button",{type:"button",onClick:()=>void As(),disabled:Be,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:Be?"Scheduling...":"Retry now"})]})]}),cr.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:cr.map(h=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:h.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${h.tone==="critical"?"text-red-300":"text-primary"}`,children:h.value})]},h.label))})]}),et&&!ee&&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(Qt,{name:et.executor.label,hint:cl(et.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:et.executor.label})]}),et.mode==="handoff"&&et.requester&&n.jsxs("span",{className:"text-caption text-muted",children:["requested by ",et.requester.label]})]}),ee&&n.jsxs("div",{className:"space-y-5",children:[(D==null?void 0:D.nextStep)&&((Gt==null?void 0:Gt.tone)==="critical"||(Gt==null?void 0:Gt.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:D.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:xr(ee.event)??lt(ee.event)})]})}),(()=>{const h=dt(R.item),k=Ce(h,["parsed_status","status"]),w=["Queued","Dispatched","Running","Completed"],_={queued:"Queued",dispatched:"Dispatched",running:"Running",completed:"Completed",success:"Completed",blocked:"Running",needs_decision:"Running",needs_attention:"Running",failed:"Running"},ce=_[k??""]??_[ee.event??""]??null;if(!ce)return null;const Ne=w.indexOf(ce),Fe=k==="completed"||k==="success",Je=R.item.timestamp,It=Date.now()-new Date(Je).getTime(),Mt=It<6e4?`${Math.round(It/1e3)}s`:`${Math.floor(It/6e4)}m ${Math.round(It%6e4/1e3)}s`;return n.jsxs("div",{className:"flex items-center gap-1 px-1",children:[w.map((Oe,Et)=>{const Yt=Et<Ne||Et===Ne&&Fe,qt=Et===Ne&&!Fe;return n.jsxs("div",{className:"flex items-center gap-1",children:[Et>0&&n.jsx("div",{className:"h-[1.5px] w-4",style:{backgroundColor:Yt||qt?M.lime:"rgba(255,255,255,0.12)"}}),n.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[n.jsx("span",{className:oe("h-2 w-2 rounded-full",qt&&"animate-pulse"),style:{backgroundColor:Yt||qt?M.lime:"rgba(255,255,255,0.15)"}}),n.jsxs("span",{className:oe("text-[9px] tracking-wider",Yt||qt?"text-primary":"text-muted/50"),children:[Oe,Yt&&Et===w.length-1&&" ✓"]})]})]},Oe)}),n.jsx("span",{className:"ml-2 text-micro text-muted",children:Mt})]})})(),Gt&&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:ur?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:dr},children:ur?(Wt==null?void 0:Wt.label)??"Stopped":`${Gt.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,Gt.pct)}%`,backgroundColor:dr}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:Gt.label})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),us.primary!==zn?n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Qt,{name:us.primary,hint:us.secondary??us.primary,size:"xs"}),n.jsx("span",{children:us.primary}),n.jsx("span",{className:"text-white/[0.2]",children:"→"}),n.jsx(Qt,{name:zn,hint:zn,size:"xs"}),n.jsx("span",{children:zn}),ee.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",lt(ee.domain),")"]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Qt,{name:zn,hint:zn,size:"xs"}),n.jsx("span",{children:zn}),ee.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",lt(ee.domain),")"]})]}),ke&&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:us.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})]}),ee.dispatcherClient&&ee.dispatcherClient!=="unknown"&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:lt(ee.dispatcherClient)})]}),(ee.domain||ee.requiredSkills.length>0)&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Policy"}),n.jsxs("div",{className:"mt-0.5 text-caption text-primary",children:[ee.domain??"",ee.requiredSkills.length>0?`${ee.domain?" · ":""}${ee.requiredSkills.join(", ")}`:""]})]})]})]}),D&&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:D.initiativeTitle??(D.initiativeId?xs(D.initiativeId):"—")})]}),D.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(D.initiativeStatus)})]}),(D.workstreamTitle||D.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:D.workstreamTitle??xs(D.workstreamId)})]}),D.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(D.workstreamStatus)})]})]}),D.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:[D.doneInitiativeWorkstreams??0,"/",D.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,D.initiativeWorkstreamPct)}%`}})})]})]}),((D==null?void 0:D.taskTitle)||(D==null?void 0:D.milestoneTitle)||(D==null?void 0:D.phase)||(D==null?void 0:D.nextStep)||(D==null?void 0:D.parsedStatus)||(D==null?void 0:D.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:[(D==null?void 0:D.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:D.taskTitle})]}),(D==null?void 0:D.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:D.milestoneTitle})]}),(D==null?void 0:D.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:xr(D.phase)??lt(D.phase)})]}),(D==null?void 0:D.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:D.nextStep})]}),(D==null?void 0:D.parsedStatus)&&D.parsedStatus!==(D==null?void 0:D.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:xr(D.parsedStatus)??lt(D.parsedStatus)})]}),(D==null?void 0:D.stopReason)&&D.stopReason!==(D==null?void 0:D.phase)&&D.stopReason!==(D==null?void 0:D.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:xr(D.stopReason)??lt(D.stopReason)})]})]})]}),ee.error&&n.jsx("div",{className:"rounded-lg border border-red-400/20 bg-red-500/10 px-4 py-3 text-body text-red-100/80",children:ee.error})]}),ft&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),$e==="missing"&&!Rt&&ke&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(Tr,{mode:"block",text:ft,className:"text-body leading-relaxed text-primary"})]}),nn(R.item.description)&&nn(R.item.description)!==ft&&(()=>{const h=nn(R.item.description)??"";return h.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(Tr,{mode:"block",text:h,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(Tr,{mode:"block",text:h,className:"text-body leading-relaxed text-secondary"})]})})(),dn&&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:dn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:dn.dispatch})]}),dn.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:dn.highlights.slice(0,3).map((h,k)=>n.jsx("li",{children:h},`${dn.sliceRunId}:highlight:${k}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:dn.outcome.summary})]})]})]}),(()=>{const h=dt(R.item),k=h==null?void 0:h.blocker,w=h==null?void 0:h.decisions_needed,_=k||w&&w.length>0,ce=Ae.length>0;return!_&&!ce?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:[k&&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:k.description??"Blocked"}),k.waiting_on&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Waiting on: ",k.waiting_on]})]})]}),Us&&n.jsx("div",{className:"mt-2 flex gap-2",children:n.jsx("button",{type:"button",onClick:()=>{Z==null||Z(Wn[0]??null),Cn()},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((Ne,Fe)=>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:Ne.title??"Pending decision"})]}),Ne.id&&Z&&n.jsx("button",{type:"button",onClick:()=>{Z(Ne.id),Cn()},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"})]},Ne.id??Fe))}),ce&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary select-none",children:[Ae.length," evidence file",Ae.length===1?"":"s"]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[ct.map((Ne,Fe)=>{const Je=la(Ne.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:lt(Ne.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Ls(Ne.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Je&&n.jsx("a",{href:Je,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 Mn(`${lt(Ne.key)} path`,Ne.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"})]})]},`${Ne.key}:${Ne.path}:${Fe}`)}),We.length>0&&We.map((Ne,Fe)=>{const Je=la(Ne.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:lt(Ne.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Ls(Ne.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Je&&n.jsx("a",{href:Je,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 Mn(`${lt(Ne.key)} path`,Ne.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"})]})]},`${Ne.key}:${Ne.path}:overflow:${Fe}`)})]})]})]})]})})(),ke&&(tt||(ee==null?void 0:ee.logPath)||S)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),ke&&(tt||(ee==null?void 0:ee.logPath)||(ee==null?void 0:ee.outputPath)||(D==null?void 0:D.initiativeId)||(D==null?void 0:D.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:[tt&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[tt.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:lt(tt.domain)})]}),(tt.provider||tt.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:[tt.provider?`${lt(tt.provider)} · `:"",tt.model?Rr(tt.model):"—"]})]}),tt.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:lt(tt.modelTier)})]}),tt.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",tt.pluginVersion]})]})]}),(tt==null?void 0:tt.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:[tt.skillPack.name??"—",tt.skillPack.version?`@${tt.skillPack.version}`:"",tt.skillPack.source?` · ${tt.skillPack.source}`:""]}),tt.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var h;return void Mn("Skill pack checksum",((h=tt.skillPack)==null?void 0:h.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 ",tt.skillPack.checksum.slice(0,12)]})]}),tt&&tt.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"}),tt.requiredSkills.map(h=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:h},h))]}),(tt==null?void 0:tt.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:[tt.kickoffContextSource?`${tt.kickoffContextSource} · `:"",tt.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void Mn("Kickoff context hash",tt.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((ee==null?void 0:ee.logPath)||(ee==null?void 0:ee.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(ee==null?void 0:ee.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",Ls(ee.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void Mn("Log path",(ee==null?void 0:ee.logPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),(ee==null?void 0:ee.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",Ls(ee.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void Mn("Output path",(ee==null?void 0:ee.outputPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]})]}),((D==null?void 0:D.initiativeId)||(D==null?void 0:D.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(D==null?void 0:D.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",xs(D.initiativeId)]}),(D==null?void 0:D.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",xs(D.workstreamId)]})]})]})]}),ke&&S&&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:S})]})]})},R.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"})]})})]})})}),Sh=o.lazy(async()=>({default:(await sn(()=>import("./0uYJrBLl.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),_h=o.lazy(async()=>({default:(await sn(()=>import("./B8NuBCcY.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),Ch=o.lazy(async()=>({default:(await sn(()=>import("./CMir7ekf.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),Mh=o.lazy(()=>sn(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),Th=o.lazy(()=>sn(()=>import("./C-MOJWHs.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),Eh=o.lazy(async()=>({default:(await sn(()=>import("./DBct8HLW.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),Rh=o.lazy(async()=>({default:(await sn(()=>import("./CyUpNSKv.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),Lh=o.lazy(async()=>({default:(await sn(()=>import("./DLNTxNX-.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),$h=o.lazy(async()=>({default:(await sn(()=>import("./05zHA1Am.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),Dh=o.lazy(async()=>({default:(await sn(()=>import("./BDlKSbsp.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),Fh=o.lazy(async()=>({default:(await sn(()=>import("./Crj3jKHE.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Ph=o.lazy(async()=>({default:(await sn(()=>import("./DdYkuATV.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),Oh=o.lazy(async()=>({default:(await sn(()=>import("./8nr6IqT4.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),Bh=o.lazy(async()=>({default:(await sn(()=>import("./CoDun8X6.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),gl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},qh={connected:M.lime,reconnecting:M.amber,disconnected:M.red},ua="orgx.demo_mode",ma="orgx.dev_mode",pa="orgx.show_synthetic_entities",Sa="orgx.selected_workspace_id",xl={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},yl=new Set(["running","active","queued","pending","in_progress","working","planning"]),zh=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function wn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Wh(e){const t=wn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Uh(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 Hh(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=Ut(e);return{title:"Live stream degraded",message:Uh(s),action:"settings"}}function fa(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 Vh(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 bl(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function wl(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 ha(e,t){const s=xl[e.status]??99,r=xl[t.status]??99;return s!==r?s-r:wn(e.updatedAt??e.lastEventAt??e.startedAt)-wn(t.updatedAt??t.lastEventAt??t.startedAt)}function vl(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 Kh(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 Gh(e){if(Bs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Xh(e){if(Bs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Qh(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Jh(e){return zh.test(e)}function ci(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 Yh(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Zh(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function eg(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 tg(e,t){vs(e,t)}function ng(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 sg(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=eg(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Sa);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function rg(){const e=Xd();return e.showGate?n.jsx(Hu,{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(Gm,{children:n.jsx(cg,{onboarding:e})})}function ig(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 ag(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 kl(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 jl(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function og(){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:Ci,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function lg(){const{state:e}=Gl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ph,{})}):null}function cg({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(ua)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(pa)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ma)==="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(()=>sg()),x=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:b=[]}=Os({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),F=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const Y of F){if(!Y||typeof Y!="object"||Array.isArray(Y))continue;const Ae=ci(Y,["id"]);if(!Ae)continue;const ct=ci(Y,["status","priority"]);if(!Yh(ct))continue;const We=ci(Y,["title","name"])??(Ae.length>10?`${Ae.slice(0,8)}…`:Ae),Ze=Y.is_default===!0,ft=Zh({title:We,isDefault:Ze}),Rt=ci(Y,["created_at"]);S.push({id:Ae,title:ft,status:ct,isDefault:Ze,createdAt:Rt})}return S.sort((Y,Ae)=>{if(Y.isDefault!==Ae.isDefault)return Y.isDefault?-1:1;const ct=wn(Y.createdAt)-wn(Ae.createdAt);return ct!==0?ct:Y.title.localeCompare(Ae.title)}),S},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:v,error:N,refetch:f,approveDecision:C,rejectDecision:H,approveAllDecisions:Z,bulkDecisionAction:U,decisionMutation:fe}=jd({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),K=t||r,re=o.useMemo(()=>K?I.sessions.nodes:I.sessions.nodes.filter(m=>!Gh(m)),[I.sessions.nodes,K]),be=o.useMemo(()=>I.activity.filter(m=>!(!K&&Xh(m)||!a&&Qh(m))),[I.activity,K,a]),ve=I.connection==="connected"||I.decisions.length>0,[Se,me]=o.useState(null),[Ke,pe]=o.useState(!1),[ae,te]=o.useState(null),[ie,ke]=o.useState(null),[V,T]=o.useState(null),[z,P]=o.useState(null),[W,Q]=o.useState("24h"),[xe,je]=o.useState({startIso:null,endIso:null}),ne=o.useRef(new Set),[ye,ge]=o.useState(null),[E,B]=o.useState(null),[G,se]=o.useState(null),[Re,Ge]=o.useState(null),Te=o.useRef(null),L=o.useCallback(m=>{Te.current&&clearTimeout(Te.current),Ge(m),Te.current=setTimeout(()=>Ge(null),4e3)},[]),[at,Le]=o.useState(!1),[Xe,bt]=o.useState(!1),[vt,kt]=o.useState([]),O=o.useRef(null),_e=o.useRef(null),[he,Me]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[Qe,nt]=o.useState(!1),[J,ze]=o.useState(null),[we,X]=o.useState("activity"),[$e,He]=o.useState("initiatives"),[De,rt]=o.useState("next_up"),ut=o.useCallback(m=>{if(X(m),m==="initiatives"){He("initiatives"),rt("next_up");return}m==="decisions"&&(He("initiatives"),rt("in_progress"),Dt("needs_attention"))},[]),[_t,Dt]=o.useState("all"),q=o.useMemo(()=>Array.isArray(I.sliceRuns)?I.sliceRuns:[],[I.sliceRuns]),Ue=o.useMemo(()=>Ul({sessions:re,sliceRuns:q}),[q,re]).length,Ve=o.useMemo(()=>Hl(q),[q]),qe=Ve.length+(ve?I.decisions.length:0),[Be,Pe]=o.useState(null),mt=o.useCallback(m=>{const A=q.find(F=>F.initiativeId===m.initiativeId&&F.workstreamId===m.workstreamId)??null;Pe({source:"queue",item:m,linkedSliceRun:A})},[q]),Ft=o.useCallback((m,A)=>{Pe({source:"in_progress",row:m,sliceRun:A})},[]),pt=o.useCallback(m=>{Pe({source:"needs_input",sliceRun:m})},[]),gt=o.useCallback(async(m,A)=>{L("Slice accepted and marked complete."),f()},[f,L]),At=o.useCallback(async(m,A)=>{L("Changes requested — feedback posted.")},[L]),st=hu({projectId:u,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:I.snapshotVersion}),Pt=xu({authToken:null,embedMode:!1}),{model:Ye,actions:zt}=wu({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Ct=o.useMemo(()=>Ye.items.filter(m=>m.kind==="failure_diagnostic"),[Ye.items]),St=o.useMemo(()=>({...Ye,items:Ct,total:Ct.length}),[Ct,Ye]),[Ht,jt]=o.useState(null),[ln,rs]=o.useState(0),is=o.useCallback(m=>{jt(m);const A=Ct.findIndex(F=>F.id===m.id);rs(A>=0?A:0)},[Ct]),ks=o.useCallback(m=>{if(Ct.length===0)return;const A=(ln+m+Ct.length)%Ct.length;rs(A),jt(Ct[A]??null)},[ln,Ct]),Rn=st,Vt=o.useMemo(()=>st.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[st.items]),kn=!!Vt,js=o.useMemo(()=>{var F;if(!Vt)return null;const m=Vt.autoRuntimeState;return{state:m==="running"?"running":m==="stopping"?"stopping":"idle",reason:Vt.blockReason??null,activeRunId:((F=Vt.autoContinue)==null?void 0:F.activeRunId)??null,activeWorkstreamTitle:Vt.workstreamTitle??null}},[Vt]);o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(ua,"1"):window.localStorage.removeItem(ua)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(pa,"1"):window.localStorage.removeItem(pa)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(ma,"1"):window.localStorage.removeItem(ma)}catch{}},[a]),o.useEffect(()=>{a||nt(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(Sa,u):window.localStorage.removeItem(Sa)}catch{}try{const m=new URL(window.location.href);u?tg(m.searchParams,u):ng(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 rn=o.useCallback((m,A)=>{Me(F=>({open:!0,tab:m??F.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),as=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{}},[]),An=o.useCallback(()=>{rn("orgx")},[rn]),Kn=o.useCallback(()=>{sn(()=>import("./0uYJrBLl.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),{data:Ln}=Vl(l==="mission-control",u),{data:Gn}=Km(l==="mission-control",u),{data:os=[]}=Os({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Kt,Sn]=o.useState(null),[jn,ls]=o.useState(""),[$,le]=o.useState(!1),de=o.useCallback((m,A)=>{Sn({type:m,initiativeId:A}),ls(""),le(!1)},[]),Ee=o.useCallback(()=>{Sn(null),ls(""),le(!1)},[]),wt=o.useCallback(()=>{ke(null)},[]),Bt=o.useCallback(()=>{T(null),P(null)},[]),it=o.useCallback(()=>{se(null)},[]);o.useEffect(()=>{var F;const m=((F=re[0])==null?void 0:F.id)??null;if(!m){Se!==null&&me(null);return}if(Se===null){me(m);return}re.some(S=>S.id===Se)||me(m)},[re,Se]),o.useEffect(()=>{if(!ie)return;re.some(A=>A.id===ie)||ke(null)},[ie,re]);const Lt=o.useCallback(m=>{sn(()=>import("./B8NuBCcY.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),me(m),pe(!0),te(null),ke(m),T(null),P(null)},[]),qs=o.useCallback(m=>{sn(()=>import("./B8NuBCcY.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),me(m.id),pe(!0),ke(m.id),T(m.workstreamId??null),P(m.title),te({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),L(`Opened intervention composer for ${m.title}.`)},[]),ht=o.useCallback(m=>{const A=m.trim();if(!A)return;const F=re.find(S=>S.runId===A||S.id===A)??null;F&&(Lt(F.id),L(`Focused session: ${F.title}`))},[re,Lt]),Ns=o.useCallback(m=>{var S;const A=(S=m.id)==null?void 0:S.trim();if(!A)return;const F=fa(m);if(F){const Y=re.find(Ae=>Ae.runId===F||Ae.id===F)??null;Y&&(me(Y.id),ke(Y.id))}x("activity"),X("activity"),pe(!1),ge(A),L("Opened activity detail from session timeline.")},[re,x]),Tt=o.useMemo(()=>re.find(m=>m.id===ie)??null,[ie,re]),Nt=o.useMemo(()=>{var F,S;const m=((F=Tt==null?void 0:Tt.runId)==null?void 0:F.trim())??"",A=((S=Tt==null?void 0:Tt.id)==null?void 0:S.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[Tt==null?void 0:Tt.id,Tt==null?void 0:Tt.runId]),pn=o.useMemo(()=>{const m=new Set;for(const A of Nt){const F=A.trim();F.length>0&&m.add(F)}return m},[Nt]),Xn=o.useMemo(()=>{const m=new Map;for(const A of re){const F=A.workstreamId??null;A.runId&&m.set(A.runId,F),A.id&&m.set(A.id,F)}return m},[re]),_n=o.useMemo(()=>{const m=Nt.length>0?Nt.join("|"):"*",A=(V==null?void 0:V.trim())||"*",F=(G==null?void 0:G.trim())||"*";return`${m}::${A}::${F}`},[V,G,Nt]),Is=o.useCallback(m=>{ne.current.add(_n),Q(m)},[_n]);o.useEffect(()=>{if(ne.current.has(_n)||v)return;const m=Date.now(),A=be.filter(Y=>{const Ae=fa(Y);if(pn.size>0&&(!Ae||!pn.has(Ae)))return!1;if(V){const ct=bl(Y);if((wl(ct,["workstreamId","workstream_id"])??(Ae?Xn.get(Ae)??null:null))!==V)return!1}if(G){const ct=bl(Y);if((wl(ct,["agentName","agent_name"])??Y.agentName)!==G)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(Y=>{const Ae=Fr(Y,m);return A.some(ct=>{const We=wn(ct.timestamp);return We?Ae===null||We>=Ae:!1})})??"all";ne.current.add(_n),S!==W&&Q(S)},[V,be,_n,W,Xn,G,v,pn]);const fn=Ld({seed:be,timeFilterId:W,customSinceIso:W==="custom"?xe.startIso:null,customUntilIso:W==="custom"?xe.endIso:null,runId:(Tt==null?void 0:Tt.runId)??null,projectId:u,pageSize:50,demoMode:t}),on=o.useMemo(()=>re.find(m=>m.id===Se)??null,[re,Se]),$n=o.useMemo(()=>re.filter(m=>yl.has(m.status)).length,[re]),Qn=o.useMemo(()=>q.length>0?Ve.length:re.filter(m=>{const A=en(m.status),F=en(m.phase??""),S=en(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||F==="blocked"||S==="error"?!0:yl.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[q.length,Ve.length,re]);o.useMemo(()=>re.filter(m=>m.status==="failed").length,[re]);const zs=o.useMemo(()=>re.filter(m=>m.status==="completed").length,[re]);o.useMemo(()=>{const m=(ve?I.decisions.length:0)+Qn;return[{id:"active",label:"Running",value:$n,color:$n>0?M.lime:M.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?M.amber:M.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:zs,color:M.teal,icon:"session"}]},[$n,Qn,zs,I.decisions.length,re,ve]),o.useMemo(()=>I.decisions.length>0?Math.max(0,...I.decisions.map(m=>m.waitingMinutes)):0,[I.decisions]);const Jn=o.useMemo(()=>N?Hh(N):null,[N]),Dn=o.useMemo(()=>{const m=[];if(Jn){const A=Jn.action==="refresh"&&typeof f=="function";m.push({id:`stream-error:${N}`,kind:"error",icon:"notification",title:Jn.title,message:Jn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void f():()=>rn("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:An}),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,An,f,rn,Re]);o.useEffect(()=>{const m=new Set(Dn.map(A=>A.id));kt(A=>A.filter(F=>m.has(F)))},[Dn]);const Fn=o.useMemo(()=>Dn.filter(m=>!vt.includes(m.id)),[vt,Dn]),ar=ve?I.decisions.length:0,Or=$n+Qn+ar,Ws=o.useCallback(m=>{kt(A=>A.includes(m)?A:A.concat(m))},[]),Ei=o.useCallback(()=>{kt(Dn.map(m=>m.id))},[Dn]);o.useEffect(()=>{if(!Xe)return;const m=F=>{var Y,Ae;const S=F.target;S&&((Y=_e.current)!=null&&Y.contains(S)||(Ae=O.current)!=null&&Ae.contains(S)||bt(!1))},A=F=>{F.key==="Escape"&&bt(!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 an=o.useMemo(()=>{var F;const m=new Map;for(const S of re){const Y=S.initiativeId??S.groupId??"unscoped",Ae=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",ct=ig(Ae),We=m.get(Y)??{id:Y,name:Ae,category:ct,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(S.progress!==null&&(We.progressTotal+=S.progress,We.progressCount+=1),We.statusCounts[S.status]=(We.statusCounts[S.status]??0)+1,S.agentName&&(We.allAgents.add(S.agentName),["running","queued","pending","blocked"].includes(S.status)&&We.activeAgents.add(S.agentName)),S.workstreamId){const Ze=I.sessions.groups.find(Rt=>Rt.id===S.workstreamId),ft=((F=Ze==null?void 0:Ze.label)==null?void 0:F.trim())||S.workstreamId;We.workstreams.set(S.workstreamId,ft)}We.latestEpoch=Math.max(We.latestEpoch,wn(S.updatedAt??S.lastEventAt??S.startedAt)),m.set(Y,We)}const A=[];for(const S of m.values()){const Y=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,Ae=S.category,ct=ag(Ae),We=Math.round(Math.max(0,Math.min(100,Y))/100*(ct.length-1)),Ze=(S.statusCounts.blocked??0)>0,ft=(S.statusCounts.completed??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0&&(S.statusCounts.blocked??0)===0&&(S.statusCounts.paused??0)===0,Rt=!ft&&!Ze&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,tn=(S.statusCounts.running??0)+(S.statusCounts.active??0)+(S.statusCounts.in_progress??0),Cn=(S.statusCounts.queued??0)+(S.statusCounts.pending??0),pr=S.workstreams.size,As=`${pr} workstream${pr===1?"":"s"}`,Mn=pr===0?"No workstreams linked yet.":ft?`${As} completed.`:Ze?`${As} linked · resolve blockers to continue.`:Rt?`${As} linked · initiative is paused.`:tn>0?`${tn} workstream${tn===1?"":"s"} active right now.`:Cn>0?`${Cn} workstream${Cn===1?"":"s"} queued to start.`:`${As} linked · ready to run.`,Ss=ct.map((ms,ps)=>{let fr="upcoming";return(ft||ps<We)&&(fr="completed"),ps===We&&!ft&&(fr=Ze?"warning":"current"),{name:ms,status:fr}});A.push({id:S.id,name:S.name,status:ft?"completed":Ze?"blocked":Rt?"paused":"active",rawStatus:ft?"completed":Ze?"blocked":Rt?"paused":"active",category:Ae,health:Math.max(0,Math.min(100,Y)),phases:Ss,currentPhase:ft?ct.length-1:We,daysRemaining:0,targetDate:null,createdAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,updatedAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,activeAgents:S.activeAgents.size,totalAgents:S.allAgents.size,avatars:Array.from(S.activeAgents).slice(0,3),description:Mn,workstreams:Array.from(S.workstreams.entries()).map(([ms,ps])=>({id:ms,name:ps,status:"active"}))})}return A.sort((S,Y)=>{const Ae=S.status==="blocked"?0:S.status==="active"?1:2,ct=Y.status==="blocked"?0:Y.status==="active"?1:2;return Ae!==ct?Ae-ct:Y.health-S.health})},[re,I.sessions.groups]),cs=o.useMemo(()=>{const m=(S,Y)=>{var We,Ze;const Ae=typeof Y.description=="string"&&Y.description.trim().length>0?Y.description:null,ct=typeof S.description=="string"&&S.description.trim().length>0?S.description:null;return{...S,...Y,health:Y.health>0?Y.health:S.health,activeAgents:Math.max(S.activeAgents,Y.activeAgents),totalAgents:Math.max(S.totalAgents,Y.totalAgents),avatars:(We=S.avatars)!=null&&We.length?S.avatars:Y.avatars,workstreams:(Ze=S.workstreams)!=null&&Ze.length?S.workstreams:Y.workstreams,description:Ae??ct??void 0,rawStatus:Y.rawStatus??S.rawStatus??null,targetDate:Y.targetDate??S.targetDate??null,createdAt:Y.createdAt??S.createdAt??null,updatedAt:Y.updatedAt??S.updatedAt??null}},A=new Map;for(const S of an)A.set(S.id,S);for(const S of[...Gn??[],...Ln??[]]){if(!K&&Bs(S.id)){A.delete(S.id);continue}const Y=S.rawStatus??S.status;if(!jl(Y)){A.delete(S.id);continue}const Ae=A.get(S.id);A.set(S.id,Ae?m(Ae,S):S)}const F=new Set(os);return Array.from(A.values()).filter(S=>!F.has(S.id)).filter(S=>jl(S.rawStatus??S.status)).sort((S,Y)=>{const Ae=Rt=>Rt==="blocked"?0:Rt==="active"?1:Rt==="paused"?2:3,ct=Ae(S.status)-Ae(Y.status);if(ct!==0)return ct;const We=kl(S.priority)-kl(Y.priority);if(We!==0)return We;const Ze=wn(Y.updatedAt)-wn(S.updatedAt);if(Ze!==0)return Ze;const ft=Y.health-S.health;return ft!==0?ft:S.name.localeCompare(Y.name)})},[an,Ln,K,Gn,os]),Br=o.useMemo(()=>{const m={};for(const A of cs)A.id&&A.name&&(m[A.id]=A.name);return m},[cs]),or=o.useMemo(()=>{if(!Tt)return null;const m=Tt.agentName,A=Tt.title;if(m){const F=be.find(S=>{var Y;return S.runId===Tt.runId&&((Y=S.summary)==null?void 0:Y.trim())});if(F!=null&&F.summary){const S=F.summary.trim().length>40?F.summary.trim().slice(0,40)+"…":F.summary.trim();return`${m}: ${S}`}return m}if(A){const F=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(F.length>0)return F}return A??null},[be,Tt]),Pn=o.useMemo(()=>{const m=new Map;for(const A of re){const F=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const Y=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),Ae=wn(Y),ct=Ae?Math.max(0,Math.floor((Date.now()-Ae)/6e4)):0,We=m.get(F),Ze={id:F,name:S,role:"Agent",status:Kh(A.status),task:A.title??null,progress:A.progress??null,lastActive:Y,lastActiveMinutes:ct};(!We||wn(Ze.lastActive)>wn(We.lastActive))&&m.set(F,Ze)}return Array.from(m.values())},[re]),R=o.useCallback(async()=>{if(re.length===0){L("No sessions available to continue.");return}const m=[...re].sort(ha)[0];if(me(m.id),ke(m.id),T(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{}L(`Focused highest priority session: ${m.title}`),await f()},[re,f]),On=o.useCallback(async(m,A)=>{const F=await m.json().catch(()=>null),S=typeof(F==null?void 0:F.error)=="string"&&F.error.trim()||typeof(F==null?void 0:F.message)=="string"&&F.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:Ut(S)},[]),dn=o.useCallback((m,A)=>!m||m.trim().length===0?A:Ut(m.trim())||A,[]),Bn=o.useCallback(async()=>{const m=vl(st.items);if(!m){L("No startable Next Up workstream is available."),x("mission-control");return}await st.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),ke(null),T(m.workstreamId),P(m.workstreamTitle),se(null),L(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([st.refetch(),f()])},[f,st,x]),Yn=o.useCallback(async()=>{const m=vl(st.items);if(!m){L("No startable initiative is ready for Autopilot yet."),x("mission-control");return}await Pt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await st.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),ke(null),T(null),P(null),se(null),L(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([st.refetch(),f()])},[f,Pt,st,x]),lr=o.useCallback(async()=>{Le(!0);try{if(!Vt){await Yn();return}await st.stopInitiativeAutoContinue({initiativeId:Vt.initiativeId}),L(`Autopilot stopped for ${Vt.initiativeTitle}.`),await Promise.all([st.refetch(),f()])}finally{Le(!1)}},[Vt,f,st,Yn]),ds=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),F=(m.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await On(S,"Failed to dispatch workstream from In Progress"));ke(null),T(F),P(m.title),L(`Dispatched ${m.title}.`),await Promise.all([st.refetch(),f()])},[On,f,st]),et=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),F=(m.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,placement:"bottom",resetToTodo:!1})});if(!S.ok){const Y=await On(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(Y))throw new Error(Y);const Ae=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!Ae.ok)throw new Error(await On(Ae,"Failed to pause workstream using legacy fallback"))}L(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([st.refetch(),f()])},[On,f,st]),qn=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 F=m.text.trim();if(Jh(F)){rn("agents",{focusAgentDomain:"engineering"}),L("Opened agent settings for engineering runtime configuration.");return}const S=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(A)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:F,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!S.ok)throw new Error(await On(S,"Failed to submit intervention"));L(`Intervention sent for ${m.session.title}.`),await f()},[rn,On,f]),ee=o.useCallback(async m=>{if(me(m.id),ke(m.id),T(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{}L(`Dispatch requested: ${m.title}`),await f()},[f]),un=o.useCallback(async(m,A,F={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!S.ok){const Y=await S.json().catch(()=>null);throw new Error((Y==null?void 0:Y.error)??`${A} failed (${S.status})`)}},[]),us=o.useCallback(async m=>{var Y;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 Ae=await A.json().catch(()=>null);throw new Error((Ae==null?void 0:Ae.error)??`Checkpoint creation failed (${A.status})`)}const F=await A.json().catch(()=>null),S=F&&"data"in F&&((Y=F.data)==null?void 0:Y.id)||F&&"id"in F&&F.id||null;L(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await f()},[f]),zn=o.useCallback(async m=>{await un(m,"pause",{reason:"pause_from_dashboard"}),L(`Pause requested: ${m.title}`),await f()},[f,un]),qr=o.useCallback(async m=>{await un(m,"resume",{reason:"resume_from_dashboard"}),L(`Resume requested: ${m.title}`),await f()},[f,un]),Gt=o.useCallback(async m=>{await un(m,"cancel",{reason:"restart_from_in_progress"}),await ds(m),L(`Restarted ${m.title}.`),await f()},[ds,f,un]),D=o.useCallback(async m=>{await un(m,"cancel",{reason:"cancel_from_dashboard"}),L(`Cancel requested: ${m.title}`),await f()},[f,un]),Wt=o.useCallback(async m=>{var ct;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const We=await A.json().catch(()=>null);throw new Error((We==null?void 0:We.error)??`Checkpoint list failed (${A.status})`)}const F=await A.json().catch(()=>null),Ae=(ct=(Array.isArray(F)?F:Array.isArray(F==null?void 0:F.data)?F.data:[]).map(We=>({id:typeof We.id=="string"?We.id:"",createdAt:typeof We.createdAt=="string"?We.createdAt:typeof We.created_at=="string"?We.created_at:""})).filter(We=>We.id.length>0).sort((We,Ze)=>Date.parse(Ze.createdAt)-Date.parse(We.createdAt))[0])==null?void 0:ct.id;if(!Ae)throw new Error("No checkpoint available for rollback.");await un(m,"rollback",{checkpointId:Ae,reason:"rollback_from_dashboard"}),L(`Rollback requested for ${m.title}.`),await f()},[f,un]),cr=o.useCallback(async()=>{var F;if(!Kt||jn.trim().length===0||$)return;le(!0);const m=Kt.type,A=jn.trim();try{const S={type:m,title:A,status:"active"};if(m==="workstream"){const Ae=Kt.initiativeId??(on==null?void 0:on.initiativeId)??((F=an[0])==null?void 0:F.id)??null;if(!Ae){L("Select an initiative first to start a workstream."),le(!1);return}S.initiative_id=Ae,S.parentId=Ae}const Y=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!Y.ok){const Ae=await Y.json().catch(()=>null);throw new Error((Ae==null?void 0:Ae.error)??`Failed to create ${m}.`)}L(`Created ${m}: ${A}`),Ee(),await f()}catch(S){L(dn(S instanceof Error?S.message:"",`Failed to create ${m}.`)),le(!1)}},[Ee,$,Kt,jn,an,f,on==null?void 0:on.initiativeId]),Wn=o.useCallback(()=>{de("initiative")},[de]),Us=o.useCallback(m=>{de("workstream",m)},[de]);o.useCallback(()=>{var m;return Us((on==null?void 0:on.initiativeId)??((m=an[0])==null?void 0:m.id)??null)},[an,on==null?void 0:on.initiativeId,Us]);const dr=o.useCallback(m=>{const A=[...re].filter(F=>(F.initiativeId??F.groupId)===m.id).sort(ha)[0];A&&(me(A.id),ke(A.id),T(null),P(null),L(`Focused initiative: ${m.name}`))},[re]),ur=o.useCallback(m=>{const A=an.find(F=>F.id===m)??cs.find(F=>F.id===m)??null;A&&dr(A)},[dr,an,cs]),tt=o.useCallback(m=>{const A=(m??"").trim();x("activity"),He("initiatives"),X("initiatives"),rt("in_progress"),Dt("needs_attention"),B(A.length>0?A:null),L(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[x]),mr=o.useCallback(m=>{const A=new Set,F=(m.runId??"").trim();F.length>0&&A.add(F),A.add(m.sliceRunId);const S=new Map;for(const Ze of be){const ft=fa(Ze),Rt=Vh(Ze);(ft&&A.has(ft)||Rt&&Rt===m.sliceRunId)&&S.set(Ze.id,Ze)}const Y=Array.from(S.values()),Ae=Ze=>{const ft=Ze.type.trim().toLowerCase();let Rt=0;return(ft==="decision_requested"||ft==="blocker_created")&&(Rt+=80),(ft==="run_failed"||ft==="autopilot_stopped")&&(Rt+=70),(ft.includes("slice_completed")||ft.includes("completed"))&&(Rt+=60),ft.includes("artifact")&&(Rt+=55),(ft.includes("progress")||ft.includes("update"))&&(Rt+=35),Rt+=Math.floor(wn(Ze.timestamp)/1e3),Rt};Y.sort((Ze,ft)=>Ae(ft)-Ae(Ze));const ct=Y[0]??null;x("activity"),X("activity"),He("initiatives");const We=(F?re.find(Ze=>Ze.runId===F||Ze.id===F)??null:null)??(m.initiativeId&&m.workstreamId?re.find(Ze=>Ze.initiativeId===m.initiativeId&&Ze.workstreamId===m.workstreamId)??null:null);if(We?(me(We.id),ke(We.id),T(null),P(null)):m.workstreamId&&(ke(null),T(m.workstreamId),P(m.workstreamTitle??"Work slice")),ct!=null&&ct.id){ge(ct.id),L(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){tt();return}if(F.length>0){ht(F),L("Opened the related work session. Timeline details were unavailable.");return}L("No activity details were found for this slice yet.")},[be,ht,tt,re,x]);return o.useCallback(m=>{const A=new Set(m),F=[...re].filter(S=>A.has(S.status)).sort(ha)[0];if(!F){L("No matching sessions for that metric right now.");return}Lt(F.id),X("activity")},[re,Lt]),o.useCallback(m=>{l==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&ze(m)},[l]),v?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:M.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:M.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(og,{}),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(Vu,{color:qh[I.connection],pulse:I.connection==="connected",title:[`Status: ${gl[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: ${Wh(I.lastSnapshotAt)}`,Jn?`Details: ${Jn.message}`:null].filter(Boolean).join(`
212
+ `),children:gl[I.connection]??"Unknown"}),($n>0||Qn>0)&&n.jsx(Fo,{className:"hidden md:flex",running:$n,blocked:Qn,decisionsCount:ve?I.decisions.length:0,completedToday:zs,onDecisionsClick:()=>{x("activity"),He("initiatives"),X("initiatives"),rt("in_progress"),Dt("needs_attention")},onBlockedClick:()=>{q.length>0?(x("mission-control"),rt("in_progress"),Dt("needs_attention")):ze("blocked")},onNewInitiative:Wn})]}),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:()=>{as(!1),An()},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:()=>bt(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"})]}),Fn.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:Fn.length})]}),a?n.jsx("button",{type:"button",onClick:()=>nt(!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:()=>rn("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:f,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:[Fn.length>0&&n.jsx("button",{type:"button",onClick:Ei,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>bt(!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(Fo,{className:"max-w-full overflow-hidden",running:$n,blocked:Qn,decisionsCount:ar,completedToday:zs,onDecisionsClick:()=>{x("activity"),X("initiatives"),He("initiatives"),rt("in_progress"),Dt("needs_attention"),bt(!1)},onBlockedClick:()=>{q.length>0?(x("mission-control"),rt("in_progress"),Dt("needs_attention")):ze("blocked"),bt(!1)}})}),Fn.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:Or>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:Fn.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(vn,{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),bt(!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:()=>Ws(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(Sh,{initiatives:cs,activities:be,agents:Pn,runtimeInstances:I.runtimeInstances??[],workspaceInitiativeId:u,isLoading:v,authToken:null,embedMode:!1,connection:I.connection,lastSnapshotAt:I.lastSnapshotAt,error:N,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>rn("orgx"),onRefresh:f,onCreateInitiative:Wn,onPlayNextUp:Bn,onStartAutopilot:Yn,nextUpQueueModel:st,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($p,{sessions:I.sessions,activity:be,runtimeInstances:I.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:Se,onSelectSession:Lt,onAgentFilter:se,agentFilter:G,timeFilterId:W,onReconnect:An,onLaunched:f,connectionStatus:I.connection,autopilotState:js})}),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(Ah,{activity:fn.items,sessions:re,sliceRuns:q,initiatives:an,timelineNarrative:I.timelineNarrative??[],workspaceId:u,chatSnapshot:I.chat,devMode:a,selectedRunIds:Nt,selectedSessionLabel:or,selectedWorkstreamId:V,selectedWorkstreamLabel:z,agentFilter:G,timeFilterId:W,onTimeFilterChange:Is,customTimeRange:xe,onCustomTimeRangeChange:je,hasMore:fn.hasMore,isLoadingMore:fn.isLoadingMore,onLoadMore:fn.loadMore,onClearSelection:wt,onClearWorkstreamFilter:Bt,onClearAgentFilter:it,onFocusRunId:ht,onOpenDecision:tt,requestedActivityItemId:ye,onActivityItemRequestHandled:()=>ge(null),onPlayNextUp:Bn,onStartAutopilot:Yn,onPauseWorkstream:et,onCreateInitiative:Wn,onOpenMissionControl:()=>x("mission-control"),onOpenNextUp:()=>x("mission-control"),onOpenSettings:()=>rn("orgx"),onRefreshData:f,isLoading:v})}),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(nr,{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(),rt("in_progress")},className:oe("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:oe("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(),rt("next_up")},className:oe("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:Rn.total}),n.jsx("span",{className:oe("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:()=>{lr().catch(m=>{L(dn(m instanceof Error?m.message:"","Autopilot action failed."))})},disabled:at,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":kn?"active":"idle",title:kn?"Stop autopilot":"Start autopilot","aria-label":kn?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:oe("h-3.5 w-3.5",kn?"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:oe("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",kn?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:kn?"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:oe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",_t==="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:oe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",_t==="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:qe})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:De==="in_progress"?_t==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[St.items.length>0&&n.jsx("div",{className:"min-h-[180px] max-h-[34%]",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading triage…"}),children:n.jsx(Mh,{model:St,actions:zt,onOpenDetail:is})})}),ve?n.jsxs("section",{className:oe("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(Ch,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:I.decisions,focusDecisionId:E,onFocusDecisionHandled:()=>B(null),onApproveDecision:C,onRejectDecision:H,onApproveAll:Z,onBulkDecisionAction:U,mutationState:fe,initiativeNames:Br})})})]}):n.jsx(nr,{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:oe("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(Dm,{className:oe("h-full min-h-0"),title:ve?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:q,initiatives:an,onOpenDecisions:()=>tt(),onFocusRunId:ht,onReviewActivity:mr,onOpenSliceDetail:pt})})]})]}):n.jsx(Im,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:re,sliceRuns:q,initiatives:an,needsAttentionCount:qe,onSwitchToNeedsAttention:()=>Dt("needs_attention"),onOpenSession:Lt,onFocusRunId:ht,onPlayWorkstream:ds,onPauseWorkstream:et,onResumeWorkstream:ds,onRestartSession:Gt,onIntervene:qs,onOpenSliceDetail:Ft}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Eh,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:st,queueActions:Pt,snapshotVersion:I.snapshotVersion,excludeRunning:!0,onOpenInitiative:ur,onOpenSliceDetail:mt})})},`${De}:${_t}`)]}):n.jsx(nr,{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(yt,{children:Ke&&on&&n.jsxs(n.Fragment,{children:[n.jsx(ue.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] hidden bg-black/40 backdrop-blur-sm lg:block",onClick:()=>pe(!1)},"session-drawer-backdrop"),n.jsx(ue.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"glass-panel soft-shadow fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:M.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(_h,{session:on,activity:be,initiatives:an,sliceRuns:q,initialInterventionDraft:ae,onSubmitIntervention:qn,onOpenActivityItem:Ns,onContinueHighestPriority:R,onDispatchSession:ee,onPauseSession:zn,onResumeSession:qr,onCancelSession:D,onCreateCheckpoint:us,onRollbackSession:Wt,onStartInitiative:Wn,onStartWorkstream:Us,onClose:()=>pe(!1)})})})},"session-drawer-panel")]})}),l==="activity"?n.jsx(Gu,{activeTab:we,onTabChange:ut,pendingDecisionCount:ve?I.decisions.length:0}):null,n.jsx(Mi,{open:Kt!==null,onClose:Ee,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:(Kt==null?void 0:Kt.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Kt==null?void 0:Kt.type)==="workstream"?"Create a new workstream under the selected initiative.":"Create a new initiative to organize your work."})]}),n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("label",{className:"mb-1.5 block text-caption uppercase tracking-[0.1em] text-secondary",children:"Name"}),n.jsx("input",{value:jn,onChange:m=>ls(m.target.value),onKeyDown:m=>{m.key==="Enter"&&cr()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Kt==null?void 0:Kt.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:Ee,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:cr,disabled:jn.trim().length===0||$,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:$?"Creating…":"Create"})]})]})}),he.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Rh,{open:he.open,onClose:()=>Me(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:he.tab,onChangeTab:m=>Me(A=>({...A,tab:m})),agentBehaviorInitialDomain:he.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{as(m),m||An()},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(Bh,{open:Qe,selectedWorkspaceId:u,onClose:()=>nt(!1)})}),(J==="sessions"||J==="active"||J==="blocked"||J==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Lh,{open:J==="sessions"||J==="active"||J==="blocked"||J==="failed",onClose:()=>ze(null),mode:J==="active"||J==="blocked"||J==="failed"?J:"sessions",sessions:re,onOpenSession:m=>{Lt(m.id),ze(null)},onRunAction:async(m,A)=>{await un(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>f(),onSetNotice:m=>L(m)})}),J==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx($h,{open:J==="decisions",onClose:()=>ze(null),decisions:ve?I.decisions:[],onApproveDecision:C,onRejectDecision:H,onApproveAll:Z,onBulkDecisionAction:U})}),J==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Dh,{open:J==="outbox",onClose:()=>ze(null),outbox:I.outbox,onOpenSettings:()=>{ze(null),rn("orgx")},onRefresh:()=>{f()}})}),J==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Fh,{open:J==="handoffs",onClose:()=>ze(null),handoffs:I.handoffs})}),n.jsx(lg,{}),Ht&&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(Th,{item:Ht,actions:zt,onClose:()=>jt(null),onNavigate:ks,currentIndex:ln,totalCount:Ct.length,decisions:ve?I.decisions:void 0,onApproveDecision:C,onRejectDecision:H})})})}),Be&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Oh,{target:Be,initiatives:an,onClose:()=>Pe(null),onPlayWorkstream:async(m,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,agentId:F??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const Y=await S.json().catch(()=>null);L(dn((Y==null?void 0:Y.error)??(Y==null?void 0:Y.message)??null,`Failed to dispatch workstream (${S.status})`));return}L("Dispatched workstream."),f()},onStartAutoContinue:async(m,A,F)=>{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 S=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,agentId:F??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const Y=await S.json().catch(()=>null);L(dn((Y==null?void 0:Y.error)??(Y==null?void 0:Y.message)??null,`Failed to start auto-continue (${S.status})`));return}L("Auto-continue started."),f()},onMoveWorkstream:async(m,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:F})});if(!S.ok){const Y=await S.json().catch(()=>null);L(dn((Y==null?void 0:Y.error)??(Y==null?void 0:Y.message)??null,`Move failed (${S.status})`));return}L(`Moved workstream to ${F}.`),f()},onRemoveFromQueue:async(m,A)=>{const F=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!F.ok){const S=await F.json().catch(()=>null);L(dn((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${F.status})`));return}L("Removed workstream from queue."),f()},onOpenSession:Lt,onFocusRunId:ht,onOpenInitiative:ur,onReviewActivity:mr,onOpenDecisions:()=>tt(),onAcceptSlice:gt,onRejectSlice:At})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Wd();const dg=new Sc({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Ic.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(_c,{client:dg,children:n.jsx(rg,{})})}));export{Wc as $,Qt as A,oe as B,Zt as C,Vn as D,vn as E,xs as F,hu as G,vg as H,Sg as I,kg as J,Ng as K,hs as L,Tr as M,bs as N,Vp as O,nr as P,bg as Q,Ls as R,Tn as S,Ti as T,Qd as U,Eu as V,Fl as W,Ru as X,Pu as Y,qu as Z,Ig as _,Jd as a,wg as a0,mm as a1,Ag as a2,Xr as a3,tm as a4,up as a5,yg as a6,xr as a7,yi as a8,Ot as b,Om as c,Cd as d,M as e,Eg as f,ap as g,Ut as h,Xt as i,Es as j,_g as k,Gl as l,Jt as m,en as n,Mg as o,Vi as p,ys as q,Tg as r,Rg as s,Bm as t,xu as u,$t as v,Cg as w,jg as x,Mi as y,vs as z};