@useorgx/openclaw-plugin 0.7.3 → 0.7.5

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 (123) hide show
  1. package/dashboard/dist/assets/{CZaT3ob_.js → 77gGFBt6.js} +1 -1
  2. package/dashboard/dist/assets/77gGFBt6.js.br +0 -0
  3. package/dashboard/dist/assets/77gGFBt6.js.gz +0 -0
  4. package/dashboard/dist/assets/BBpTN_SR.js +1 -0
  5. package/dashboard/dist/assets/BBpTN_SR.js.br +0 -0
  6. package/dashboard/dist/assets/BBpTN_SR.js.gz +0 -0
  7. package/dashboard/dist/assets/BTAEErUY.js +1 -0
  8. package/dashboard/dist/assets/BTAEErUY.js.br +0 -0
  9. package/dashboard/dist/assets/BTAEErUY.js.gz +0 -0
  10. package/dashboard/dist/assets/BVShoyjA.js +1 -0
  11. package/dashboard/dist/assets/BVShoyjA.js.br +0 -0
  12. package/dashboard/dist/assets/BVShoyjA.js.gz +0 -0
  13. package/dashboard/dist/assets/{CC63EwFD.js → BgcAY5rE.js} +1 -1
  14. package/dashboard/dist/assets/BgcAY5rE.js.br +0 -0
  15. package/dashboard/dist/assets/BgcAY5rE.js.gz +0 -0
  16. package/dashboard/dist/assets/{rttbDbEx.js → C-PAoJF-.js} +1 -1
  17. package/dashboard/dist/assets/C-PAoJF-.js.br +0 -0
  18. package/dashboard/dist/assets/C-PAoJF-.js.gz +0 -0
  19. package/dashboard/dist/assets/C0nA-iUG.js +1 -0
  20. package/dashboard/dist/assets/C0nA-iUG.js.br +0 -0
  21. package/dashboard/dist/assets/C0nA-iUG.js.gz +0 -0
  22. package/dashboard/dist/assets/C6GO-FKy.js +1 -0
  23. package/dashboard/dist/assets/C6GO-FKy.js.br +0 -0
  24. package/dashboard/dist/assets/C6GO-FKy.js.gz +0 -0
  25. package/dashboard/dist/assets/CFwPph5U.js +1 -0
  26. package/dashboard/dist/assets/CFwPph5U.js.br +0 -0
  27. package/dashboard/dist/assets/CFwPph5U.js.gz +0 -0
  28. package/dashboard/dist/assets/CPjsbbgZ.js +212 -0
  29. package/dashboard/dist/assets/CPjsbbgZ.js.br +0 -0
  30. package/dashboard/dist/assets/CPjsbbgZ.js.gz +0 -0
  31. package/dashboard/dist/assets/{IUexzymk.js → CSr2ZnTV.js} +1 -1
  32. package/dashboard/dist/assets/CSr2ZnTV.js.br +0 -0
  33. package/dashboard/dist/assets/CSr2ZnTV.js.gz +0 -0
  34. package/dashboard/dist/assets/CgQDT6yL.js +1 -0
  35. package/dashboard/dist/assets/CgQDT6yL.js.br +0 -0
  36. package/dashboard/dist/assets/CgQDT6yL.js.gz +0 -0
  37. package/dashboard/dist/assets/{B6wPWJ35.js → CnitK1MX.js} +1 -1
  38. package/dashboard/dist/assets/CnitK1MX.js.br +0 -0
  39. package/dashboard/dist/assets/CnitK1MX.js.gz +0 -0
  40. package/dashboard/dist/assets/{CgaottFX.js → D7DHFX0D.js} +1 -1
  41. package/dashboard/dist/assets/D7DHFX0D.js.br +0 -0
  42. package/dashboard/dist/assets/D7DHFX0D.js.gz +0 -0
  43. package/dashboard/dist/assets/DEip7uko.js +1 -0
  44. package/dashboard/dist/assets/DEip7uko.js.br +0 -0
  45. package/dashboard/dist/assets/DEip7uko.js.gz +0 -0
  46. package/dashboard/dist/assets/DHUSLc01.css +1 -0
  47. package/dashboard/dist/assets/DHUSLc01.css.br +0 -0
  48. package/dashboard/dist/assets/DHUSLc01.css.gz +0 -0
  49. package/dashboard/dist/assets/{B5zYRHc3.js → DOFL9l8s.js} +1 -1
  50. package/dashboard/dist/assets/DOFL9l8s.js.br +0 -0
  51. package/dashboard/dist/assets/DOFL9l8s.js.gz +0 -0
  52. package/dashboard/dist/assets/{8dksYiq4.js → DpuQm1oF.js} +1 -1
  53. package/dashboard/dist/assets/DpuQm1oF.js.br +0 -0
  54. package/dashboard/dist/assets/DpuQm1oF.js.gz +0 -0
  55. package/dashboard/dist/assets/{D8JNX8kq.js → DxKG5zy8.js} +2 -2
  56. package/dashboard/dist/assets/DxKG5zy8.js.br +0 -0
  57. package/dashboard/dist/assets/DxKG5zy8.js.gz +0 -0
  58. package/dashboard/dist/assets/tcEHYcbW.js +1 -0
  59. package/dashboard/dist/assets/tcEHYcbW.js.br +0 -0
  60. package/dashboard/dist/assets/tcEHYcbW.js.gz +0 -0
  61. package/dashboard/dist/index.html +2 -2
  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.js +29 -11
  65. package/dist/http/helpers/autopilot-slice-utils.js +7 -10
  66. package/dist/http/helpers/openclaw-cli.js +2 -2
  67. package/dist/http/index.js +161 -4
  68. package/dist/http/routes/live-legacy.d.ts +2 -0
  69. package/dist/http/routes/live-legacy.js +186 -3
  70. package/dist/http/routes/live-misc.d.ts +1 -0
  71. package/dist/http/routes/live-misc.js +76 -0
  72. package/dist/http/routes/mission-control-read.d.ts +4 -0
  73. package/dist/http/routes/mission-control-read.js +114 -63
  74. package/dist/http/routes/usage.js +15 -3
  75. package/dist/json-utils.js +5 -1
  76. package/dist/openclaw-settings.js +3 -2
  77. package/dist/sync/outbox-replay.js +17 -8
  78. package/package.json +6 -1
  79. package/dashboard/dist/assets/6mILZQ2a.js +0 -1
  80. package/dashboard/dist/assets/6mILZQ2a.js.br +0 -0
  81. package/dashboard/dist/assets/6mILZQ2a.js.gz +0 -0
  82. package/dashboard/dist/assets/8dksYiq4.js.br +0 -0
  83. package/dashboard/dist/assets/8dksYiq4.js.gz +0 -0
  84. package/dashboard/dist/assets/B5zYRHc3.js.br +0 -0
  85. package/dashboard/dist/assets/B5zYRHc3.js.gz +0 -0
  86. package/dashboard/dist/assets/B6wPWJ35.js.br +0 -0
  87. package/dashboard/dist/assets/B6wPWJ35.js.gz +0 -0
  88. package/dashboard/dist/assets/BWEwjt1W.js +0 -1
  89. package/dashboard/dist/assets/BWEwjt1W.js.br +0 -0
  90. package/dashboard/dist/assets/BWEwjt1W.js.gz +0 -0
  91. package/dashboard/dist/assets/BzRbDCAD.css +0 -1
  92. package/dashboard/dist/assets/BzRbDCAD.css.br +0 -0
  93. package/dashboard/dist/assets/BzRbDCAD.css.gz +0 -0
  94. package/dashboard/dist/assets/C8uM3AX8.js +0 -1
  95. package/dashboard/dist/assets/C8uM3AX8.js.br +0 -0
  96. package/dashboard/dist/assets/C8uM3AX8.js.gz +0 -0
  97. package/dashboard/dist/assets/C9jy61eu.js +0 -212
  98. package/dashboard/dist/assets/C9jy61eu.js.br +0 -0
  99. package/dashboard/dist/assets/C9jy61eu.js.gz +0 -0
  100. package/dashboard/dist/assets/CC63EwFD.js.br +0 -0
  101. package/dashboard/dist/assets/CC63EwFD.js.gz +0 -0
  102. package/dashboard/dist/assets/CZaT3ob_.js.br +0 -0
  103. package/dashboard/dist/assets/CZaT3ob_.js.gz +0 -0
  104. package/dashboard/dist/assets/CgaottFX.js.br +0 -0
  105. package/dashboard/dist/assets/CgaottFX.js.gz +0 -0
  106. package/dashboard/dist/assets/CzCxAZlW.js +0 -1
  107. package/dashboard/dist/assets/CzCxAZlW.js.br +0 -0
  108. package/dashboard/dist/assets/CzCxAZlW.js.gz +0 -0
  109. package/dashboard/dist/assets/D3iMTYEj.js +0 -1
  110. package/dashboard/dist/assets/D3iMTYEj.js.br +0 -0
  111. package/dashboard/dist/assets/D3iMTYEj.js.gz +0 -0
  112. package/dashboard/dist/assets/D8JNX8kq.js.br +0 -0
  113. package/dashboard/dist/assets/D8JNX8kq.js.gz +0 -0
  114. package/dashboard/dist/assets/DnA8dpj6.js +0 -1
  115. package/dashboard/dist/assets/DnA8dpj6.js.br +0 -0
  116. package/dashboard/dist/assets/DnA8dpj6.js.gz +0 -0
  117. package/dashboard/dist/assets/IUexzymk.js.br +0 -0
  118. package/dashboard/dist/assets/IUexzymk.js.gz +0 -0
  119. package/dashboard/dist/assets/ic2FaMnh.js +0 -1
  120. package/dashboard/dist/assets/ic2FaMnh.js.br +0 -0
  121. package/dashboard/dist/assets/ic2FaMnh.js.gz +0 -0
  122. package/dashboard/dist/assets/rttbDbEx.js.br +0 -0
  123. package/dashboard/dist/assets/rttbDbEx.js.gz +0 -0
@@ -1,212 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BWEwjt1W.js","assets/cNrhgGc1.js","assets/C-KIc3Wc.js","assets/BJgZIVUQ.js","assets/qm8xLgv-.css","assets/6mILZQ2a.js","assets/CZaT3ob_.js","assets/CxQ08qFN.js","assets/C8uM3AX8.js","assets/IUexzymk.js","assets/B6wPWJ35.js","assets/rttbDbEx.js","assets/CL_wXqR7.js","assets/ic2FaMnh.js","assets/D3iMTYEj.js","assets/D8JNX8kq.js","assets/B5zYRHc3.js","assets/CgaottFX.js","assets/8dksYiq4.js","assets/CzCxAZlW.js","assets/DnA8dpj6.js","assets/CC63EwFD.js"])))=>i.map(i=>d[i]);
2
- var gl=Object.defineProperty;var xl=(e,t,s)=>t in e?gl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Vs=(e,t,s)=>xl(e,typeof t!="symbol"?t+"":t,s);import{r as o,u as Ki,a as ns,b as xn,j as n,c as yl,d as bl,D as oa,e as wl,Q as vl}from"./cNrhgGc1.js";import{b as kl}from"./C-KIc3Wc.js";import{m as ye,A as pt,u as zn}from"./CxQ08qFN.js";import{F as jl,T as Nl}from"./BJgZIVUQ.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 Il="modulepreload",Al=function(e){return"/orgx/live/"+e},la={},Pt=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};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=Al(u),u in la)return;la[u]=!0;const h=u.endsWith(".css"),y=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${y}`))return;const b=document.createElement("link");if(b.rel=h?"stylesheet":Il,h||(b.as="script"),b.crossOrigin="",b.href=u,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((f,k)=>{b.addEventListener("load",f),b.addEventListener("error",()=>k(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)})},ca=()=>{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()}}},si="all";function On(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Sl(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return On(e.get("workspace_id"))??On(e.get("workspaceId"))??On(e.get("command_center_id"))??On(e.get("commandCenterId"))??On(e.get("center"))??On(e.get("project_id"))??On(e.get("projectId"))}catch{return null}}function ss(e,t,s){const r=On(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",si),e.set("command_center_id",si),e.set("center",si));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function _l(e){const t=On(e);return t?{"x-orgx-workspace-id":t}:{}}function kt(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??Sl();return Object.assign(t,_l(s)),t}const Cl=[[/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 or(e){if(!e)return"";for(const[s,r]of Cl)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,So=/^[0-9a-f]{20,}$/i;function Yn(e){return Ao.test(e)?`#${e.slice(0,4)}`:So.test(e)?`#${e.slice(0,4)}`:e}function qn(e){return Ao.test(e)||So.test(e)}function Fs(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 ot(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=>or(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Fs(s)),t}function $t(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=>Fs(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 rr(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 Cn(e){return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(e)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(e)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(e)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(e)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(e)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(e)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(e)?"This session is no longer available.":/500|internal server error/i.test(e)?"Something went wrong on the server. Retrying automatically.":/ECONNREFUSED|network error|fetch failed/i.test(e)?"Connection issue. Retrying automatically.":/40[13]/.test(e)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(e)?"This item was paused without a specific reason.":$t(ot(e))}function Ml(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 El(e){const t=e.metadata??{},s=Ms(t,"task_title")??Ms(t,"workstream_title"),r=s?$t(String(s)):e.title?$t(e.title):null,i=Ms(t,"user_summary")??Ms(t,"summary"),a=i?$t(String(i)):e.summary?$t(e.summary):e.description?$t(e.description):null,c=Ms(t,"next_step")??Ms(t,"nextStep"),l=c?$t(String(c)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:l&&(l===r||l===a)?null:l}}function Ms(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const Tl={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 Ks(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Tl[t]??e.replace(/_/g," ")}const Rl={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function Vf(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Rl[t]??e.replace(/_/g," ")}function Kf(e,t){return e.toLowerCase().includes("path")?Fs(t):qn(t)?Yn(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return qn(i)?Yn(i):i}).join(", "):$t(t)}function Dl(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 Gf(e){const t=Dl(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function qr(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function St(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 Ll=8e3,Fl=320,$l=300,Pl=80,Ol=80,Bl=120,da=6e4,ql=3500,zl=180,Gi={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},gr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},vs={threads:[],total:0,updatedAt:null},ua={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},_o=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),xr=10*6e4;function Wl(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 Ul(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=>Cn(a)).filter(a=>a.length>0).join(" ")}function Hl(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 Cn(s.length>0?s:e.trim())}function Vl(e){const t=e.map(s=>Hl(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function mt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function zr(e,t){const s=ua[e.status]??99,r=ua[t.status]??99;if(s!==r)return s-r;const i=mt(e.updatedAt??e.lastEventAt??e.startedAt),a=mt(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function Kl(e){return(e??"").trim().toLowerCase()}function ma(e){return _o.has(Kl(e.status))}function ri(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function pa(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const f=Date.now(),k=e.nodes.filter(_=>{const v=mt(_.updatedAt??_.lastEventAt??_.startedAt);if(ma(_))return!0;const C=["completed","archived","failed"].includes((_.status??"").toLowerCase())?xr/3:xr;return f-v<=C});if(!k.length)return t;const w=new Set(k.map(_=>_.id)),x=new Set(k.map(_=>_.groupId));return{nodes:k.sort(zr),edges:e.edges.filter(_=>w.has(_.parentId)&&w.has(_.childId)),groups:e.groups.filter(_=>x.has(_.id))}}const s=new Set,r=[...t.nodes];for(const f of t.nodes)for(const k of ri(f))s.add(k);const i=Date.now(),a=[];for(const f of e.nodes){if(ri(f).some(g=>s.has(g)))continue;const w=mt(f.updatedAt??f.lastEventAt??f.startedAt),_=["completed","archived","failed"].includes((f.status??"").toLowerCase())?xr/3:xr,v=i-w<=_;if(ma(f)||v){a.push(f),r.push(f);for(const g of ri(f))s.add(g)}}if(!a.length)return t;const c=new Set(r.map(f=>f.id)),l=new Map(e.groups.map(f=>[f.id,f])),d=new Map(t.groups.map(f=>[f.id,f])),u=[...t.groups];for(const f of a){if(d.has(f.groupId))continue;const k=l.get(f.groupId)??{id:f.groupId,label:f.groupLabel||f.agentName||"Ungrouped",status:null};d.set(f.groupId,k),u.push(k)}const h=f=>`${f.parentId}->${f.childId}`,y=new Set,b=[];for(const f of t.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=h(f);y.has(k)||(y.add(k),b.push(f))}for(const f of e.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=h(f);y.has(k)||(y.add(k),b.push(f))}return{nodes:r.sort(zr),edges:b,groups:u}}function Gs(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(zr).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 fa(e,t){return e.length<=t?e:[...e].sort((s,r)=>mt(r.updatedAt)-mt(s.updatedAt)).slice(0,t)}function Gl(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()-mt(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 Co(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 ha(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 ga(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 xa(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 Mo(e){if(!e||typeof e!="object")return Gi;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 Xl(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 Ql(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function hs(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}const Jl=new Set(["autopilot_slice_result","auto_continue_started","auto_continue_stopped","next_up_manual_dispatch_started","autopilot_slice_mcp_handshake_failed","autopilot_slice_timeout","autopilot_slice_log_stall","auto_continue_spawn_guard_blocked","auto_continue_spawn_guard_rate_limited","autopilot_autofix_scheduled","autopilot_autofix_executed","autopilot_autofix_skipped"]);function Yl(e){const t=Ql(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"";if(!r||!Jl.has(r))return null;const i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??hs(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=hs(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??hs(t,["initiative_id","initiativeId"]),l=hs(t,["workstream_id","workstreamId"]),d=hs(t,["task_id","taskId"]),u=hs(t,["stop_reason","stopReason"]),h=hs(t,["parsed_status","parsedStatus"]),y=(e.title??"").trim().toLowerCase();return!i&&!a&&!l&&!d?null:[r,c??"",l??"",d??"",i??"",a??"",u??"",h??"",y].join("|")}function Eo(e,t){const s=new Set,r=new Set,i=[];for(const a of e){if(s.has(a.id))continue;s.add(a.id);const c=Yl(a);if(!(c&&r.has(c))&&(c&&r.add(c),i.push(a),i.length>=t))break}return i}function Zl(e,t,s){if(t.length===0)return e;const r=new Map;for(const l of e)r.set(l.id,l);let i=!1;for(const l of t){const d=r.get(l.id);if(!d){r.set(l.id,l),i=!0;continue}(d.timestamp!==l.timestamp||d.type!==l.type||d.title!==l.title||d.description!==l.description||d.summary!==l.summary||d.kind!==l.kind||d.agentId!==l.agentId||d.agentName!==l.agentName||d.requesterAgentId!==l.requesterAgentId||d.requesterAgentName!==l.requesterAgentName||d.executorAgentId!==l.executorAgentId||d.executorAgentName!==l.executorAgentName||d.runId!==l.runId||d.initiativeId!==l.initiativeId||d.decisionRequired!==l.decisionRequired||JSON.stringify(d.metadata??null)!==JSON.stringify(l.metadata??null))&&(r.set(l.id,l),i=!0)}if(!i)return e;const a=Array.from(r.values()).sort((l,d)=>{const u=mt(d.timestamp)-mt(l.timestamp);return u!==0?u:d.id.localeCompare(l.id)}),c=Eo(a,s);return Co(e,c)?e:c}function ii(e,t){const s=[...e].sort((r,i)=>{const a=mt(i.timestamp)-mt(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Eo(s,t)}function ya(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(Gl).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:mt(c.requestedAt??c.updatedAt)-mt(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 ba(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 ec(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 tc(e,t){return!!(_o.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function yr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function ai(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 nc(e,t,s){const r=new Map,i=[...e].sort((l,d)=>mt(d.timestamp)-mt(l.timestamp));for(const l of i){if(!l.runId)continue;const d=l.runId,u=r.get(d),h=l.timestamp;if(!u){const y=l.initiativeId??null;r.set(d,{id:d,parentId:null,runId:d,title:l.title,agentId:l.agentId??null,agentName:l.agentName??null,status:ba(l.type),progress:null,initiativeId:y,workstreamId:null,groupId:y??"unscoped",groupLabel:yr(y),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:l.title,blockers:l.type==="blocker_created"&&l.description?[l.description]:[]});continue}(!u.startedAt||mt(h)<mt(u.startedAt))&&(u.startedAt=h),mt(h)>=mt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=h,u.lastEventAt=h,u.lastEventSummary=l.title,u.status=ba(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=yr(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),h=ec(l.status),y=new Date().toISOString(),b=tc(l,h),f=l.startedAt??(b?y:null),k=l.initiativeId??null,w=l.currentTask&&l.currentTask.trim().length>0?l.currentTask.trim():`${l.name??l.id} ${h==="archived"?"idle":h}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:w,agentId:l.id,agentName:l.name??l.id,status:h,progress:null,initiativeId:k,workstreamId:null,groupId:k??"unscoped",groupLabel:yr(k),startedAt:f,updatedAt:f,lastEventAt:f,lastEventSummary:l.currentTask,blockers:ai(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=w),b&&(u.updatedAt=f??u.updatedAt??y,u.lastEventAt=f??u.lastEventAt??y),u.status==="archived"&&h!=="archived"&&(u.status=h),ai(l.blockers).length>0&&(u.blockers=ai(l.blockers)),k&&!u.initiativeId&&(u.initiativeId=k,u.groupId=k,u.groupLabel=yr(k))}const a=Array.from(r.values()).sort(zr).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 sc(e,t,s){var h;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 y=()=>i.abort();a.addEventListener("abort",y,{once:!0}),u=()=>a.removeEventListener("abort",y)}d=setTimeout(()=>i.abort(),r)}try{const y=await fetch(e,l),f=(((h=y.headers.get("content-type"))==null?void 0:h.toLowerCase())??"").includes("application/json");if(!y.ok){let k=`${y.status} ${y.statusText}`;if(f){const w=await y.json().catch(()=>null);w!=null&&w.error&&(k=`${y.status} ${w.error}`)}else{const w=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);w.length>0&&(k=`${y.status} ${w}`)}return{ok:!1,status:y.status,data:null,error:k}}if(!f){const k=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:y.status,data:null,error:`Unexpected content type for ${e}${k?`: ${k}`:""}`}}return{ok:!0,status:y.status,data:await y.json(),error:null}}catch(y){const b=y instanceof Error?y.message:"Network error",f=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return y instanceof DOMException&&y.name==="AbortError"||Wl(b)?{ok:!1,status:0,data:null,error:f&&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 rc(e,t,s,r,i=[],a=Gi,c=null,l=1,d=[],u=vs,h){var k,w,x;const y=((k=t[0])==null?void 0:k.timestamp)??null,b=((w=r[0])==null?void 0:w.requestedAt)??((x=r[0])==null?void 0:x.updatedAt)??null,f=mt(y)>=mt(b)?y:b;return{connection:"connected",lastActivity:f?St(f):null,lastSnapshotAt:c,snapshotVersion:l,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:Mo(a),chat:Rr(u),runtimeInstances:d,workSliceProjections:(h==null?void 0:h.workSliceProjections)??[],timelineNarrative:(h==null?void 0:h.timelineNarrative)??[],nextUpByInitiative:(h==null?void 0:h.nextUpByInitiative)??[],runningWorkSlices:(h==null?void 0:h.runningWorkSlices)??0,needsInputTotal:(h==null?void 0:h.needsInputTotal)??0,failedActionableTotal:(h==null?void 0:h.failedActionableTotal)??0,completedTodayTotal:(h==null?void 0:h.completedTodayTotal)??0,consistencyFlags:(h==null?void 0:h.consistencyFlags)??[],dataHealth:h==null?void 0:h.dataHealth}}function wa(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)=>mt(r.lastEventAt??r.lastHeartbeatAt)-mt(s.lastEventAt??s.lastHeartbeatAt))}function va(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 ic(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)=>mt(r.lastActivityAt??r.updatedAt)-mt(s.lastActivityAt??s.updatedAt))}function Rr(e){if(!e||typeof e!="object")return vs;const t=ic(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 ac(e,t){const s=e??vs,r=t??vs;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 Dr(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,h=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:h,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)=>mt(i.updatedAt??i.lastEventAt)-mt(r.updatedAt??r.lastEventAt))}function br(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)=>mt(r.updatedAt??r.completedAt??r.failedAt)-mt(s.updatedAt??s.completedAt??s.failedAt))}function oi(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)=>mt(r.occurredAt)-mt(s.occurredAt))}function li(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 ka(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(h=>({id:h.artifactId,type:h.type,title:h.title,url:h.url,createdAt:h.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 Dr(t)}function oc(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 lc(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 cc(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 dc(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 uc(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 mc(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 pc(e={}){const{enabled:t=!0,pollInterval:s=Ll,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=Fl,maxActivityItems:d=$l,maxHandoffs:u=Pl,maxDecisions:h=Ol,batchWindowMs:y=Bl}=e,b=typeof a=="string"&&a.trim().length>0?a.trim():null,f=typeof c=="string"&&c.trim().length>0?c.trim():null,[k,w]=o.useState(ca()),[x,_]=o.useState(gr),[v,g]=o.useState(!r),[C,U]=o.useState(null),de=o.useRef(),ee=o.useRef(null),pe=o.useRef(null),[ie,se]=o.useState(!1),oe=o.useRef(0),we=o.useRef(!1),Ne=o.useRef(`${b??"__all__"}::${f??"__all__"}`),Q=o.useRef(!1),je=o.useRef(null),Me=o.useCallback((V,G)=>{je.current&&(clearTimeout(je.current),je.current=null),_(V),G!=null&&G.autoResetMs&&G.autoResetMs>0&&(je.current=setTimeout(()=>{je.current=null,_(gr)},G.autoResetMs))},[]);o.useEffect(()=>()=>{je.current&&(clearTimeout(je.current),je.current=null)},[]),o.useEffect(()=>{const V=`${b??"__all__"}::${f??"__all__"}`;Ne.current!==V&&(Ne.current=V,Q.current=!0,Me(gr),w(G=>({...G,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:vs,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(G.snapshotVersion??0)+1})),g(!0),U(null))},[b,f,Me]);const B=o.useCallback((V,G,le,ae=null,ve=null,re=null,Pe=null,Se=null,E=null,P=null)=>{oe.current=Date.now(),we.current=!1,w(K=>{const te=Q.current;te&&(Q.current=!1);const Re=G===null?te?[]:K.activity:ii(G,d),qe=le===null?te?[]:K.handoffs:fa(le,u),Ee=Gs(V===null?te?{nodes:[],edges:[],groups:[]}:K.sessions:te?Gs(V,l):pa(K.sessions,Gs(V,l)),l),M=ae===null?te?[]:K.decisions:ya(ae,h),q=ve===null?te?[]:K.sliceRuns:Dr(ve),ne=re===null?te?Gi:K.outbox:Mo(re),me=Se===null?te?[]:K.runtimeInstances??[]:wa(Se),Te=E===null?te?vs:K.chat??vs:Rr(E),et=(P==null?void 0:P.workSliceProjections)==null?te?[]:K.workSliceProjections??[]:br(P.workSliceProjections),tt=(P==null?void 0:P.timelineNarrative)==null?te?[]:K.timelineNarrative??[]:oi(P.timelineNarrative),Ce=(P==null?void 0:P.nextUpByInitiative)==null?te?[]:K.nextUpByInitiative??[]:li(P.nextUpByInitiative),Ye=typeof(P==null?void 0:P.runningWorkSlices)=="number"&&Number.isFinite(P.runningWorkSlices)?Math.max(0,Math.floor(P.runningWorkSlices)):K.runningWorkSlices??0,ze=typeof(P==null?void 0:P.needsInputTotal)=="number"&&Number.isFinite(P.needsInputTotal)?Math.max(0,Math.floor(P.needsInputTotal)):K.needsInputTotal??0,dt=typeof(P==null?void 0:P.failedActionableTotal)=="number"&&Number.isFinite(P.failedActionableTotal)?Math.max(0,Math.floor(P.failedActionableTotal)):K.failedActionableTotal??0,at=typeof(P==null?void 0:P.completedTodayTotal)=="number"&&Number.isFinite(P.completedTodayTotal)?Math.max(0,Math.floor(P.completedTodayTotal)):K.completedTodayTotal??0,nt=(P==null?void 0:P.consistencyFlags)==null?K.consistencyFlags??[]:P.consistencyFlags.filter(ke=>typeof ke=="string"),xe=(P==null?void 0:P.dataHealth)===void 0||(P==null?void 0:P.dataHealth)===null?K.dataHealth:P.dataHealth,Xe=(K.snapshotVersion??0)+1;return ha(K.sessions,Ee)&&Co(K.activity,Re)&&ga(K.handoffs,qe)&&xa(K.decisions,M)&&oc(K.sliceRuns,q)&&Xl(K.outbox,ne)&&ac(K.chat,Te)&&va(K.runtimeInstances,me)&&lc(K.workSliceProjections??[],et)&&cc(K.timelineNarrative??[],tt)&&dc(K.nextUpByInitiative??[],Ce)&&(K.runningWorkSlices??0)===Ye&&(K.needsInputTotal??0)===ze&&(K.failedActionableTotal??0)===dt&&(K.completedTodayTotal??0)===at&&uc(K.consistencyFlags??[],nt)&&mc(K.dataHealth,xe)&&K.lastSnapshotAt===Pe&&K.connection==="connected"?K:rc(Ee,Re,qe,M,q,ne,Pe,Xe,me,Te,{workSliceProjections:et,timelineNarrative:tt,nextUpByInitiative:Ce,runningWorkSlices:Ye,needsInputTotal:ze,failedActionableTotal:dt,completedTodayTotal:at,consistencyFlags:nt,dataHealth:xe})}),g(!1)},[d,h,u,l]),I=o.useCallback(async()=>{if(!t){w(le=>le.connection==="disconnected"?le:{...le,connection:"disconnected"}),g(!1),U(null);return}const V=`${b??"__all__"}::${f??"__all__"}`;if(ee.current&&pe.current===V)return ee.current;if(r){w(ca()),g(!1);return}const G=(async()=>{try{const le=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(h),include_idle:"true"});f&&ss(le,f),b&&le.set("initiative",b);const ae=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${le.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${le.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${le.toString()}`}],ve=[];let re=null,Pe=!1;for(let Y=0;Y<ae.length;Y+=1){const Ae=ae[Y];Y>0&&await new Promise(Le=>{setTimeout(Le,zl)});const De=await sc(Ae.url,{headers:kt({workspaceId:f})},{timeoutMs:ql});if(De.ok&&De.data){re=De.data;break}(De.status===401||De.status===403)&&(Pe=!0),ve.push(`${Ae.label}: ${De.error??"unavailable"}`)}if(!re){if(Pe){const Y=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw Y.code="ORGX_AUTH",Y}throw new Error(Ul(ve))}if(Ne.current!==V)return;const Se=Array.isArray(re.degraded)?re.degraded.filter(Y=>typeof Y=="string"):[],E=Se.map(Y=>Y.toLowerCase()),P=(...Y)=>E.some(Ae=>Y.some(De=>Ae.includes(De))),K=Array.isArray(re.activity)?re.activity:[],te=Array.isArray(re.handoffs)?re.handoffs:[],Re=Array.isArray(re.decisions)?re.decisions:[],qe=K.length===0&&P("activity unavailable","activity local fallback failed"),Ee=P("sessions unavailable","sessions local fallback failed"),M=te.length===0&&P("handoffs unavailable"),q=Re.length===0&&P("decisions unavailable"),ne=br(Array.isArray(re.projections)?re.projections:[]),me=Rr(re.chat??null),Te=oi(Array.isArray(re.timelineNarrative)?re.timelineNarrative:[]),et=li(Array.isArray(re.nextUpByInitiative)?re.nextUpByInitiative:[]),tt=ne.length>0?ka(ne):Dr(Array.isArray(re.sliceRuns)?re.sliceRuns:[]),Ce=re.sessions&&Array.isArray(re.sessions.nodes)&&Array.isArray(re.sessions.edges)&&Array.isArray(re.sessions.groups)?re.sessions:nc(K,re.agents,l),Ye=tt.length===0&&ne.length===0&&P("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),ze=et.length===0&&P("next-up unavailable","next-up queue"),dt=qe?null:K,at=M?null:te,nt=q?null:Re,xe=Ee&&Ce.nodes.length===0?null:Ce,Xe=Ye?null:ne,ke=Ye?null:Te,W=Ye?null:tt,$e=ze?null:et;B(xe,dt,at,nt,W,re.outbox??null,re.generatedAt??null,re.runtimeInstances??null,me,{workSliceProjections:Xe,timelineNarrative:ke,nextUpByInitiative:$e,runningWorkSlices:Ye?null:re.runningWorkSlices??null,needsInputTotal:Ye?null:re.needsInput??null,failedActionableTotal:Ye?null:re.failedActionable??null,completedTodayTotal:Ye?null:re.completedToday??null,consistencyFlags:Array.isArray(re.consistencyFlags)?re.consistencyFlags:null,dataHealth:re.dataHealth??null});const z=Se.length>0?Vl(Se):[];z.length>0?(U(`Partial live data: ${z.join("; ")}`),w(Y=>Y.connection==="connected"?Y:{...Y,connection:"connected"}),se(!1)):(U(null),w(Y=>Y.connection==="connected"?Y:{...Y,connection:"connected"}))}catch(le){if(Ne.current!==V)return;const ae=le instanceof Error?le.message:"Unknown error",ve=!!(le&&typeof le=="object"&&"code"in le&&le.code==="ORGX_AUTH");ve&&(we.current=!0);const re=oe.current>0&&Date.now()-oe.current>da;U(ae),w(Pe=>{const Se=ve||re?"disconnected":"reconnecting";return Pe.connection===Se?Pe:{...Pe,connection:Se}}),se(!ve),g(!1)}finally{pe.current===V&&(ee.current=null,pe.current=null)}})();return ee.current=G,pe.current=V,G},[B,t,i,d,h,u,l,f,b,r]),T=o.useCallback(async(V,G,le)=>{var E,P,K;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const ae=Array.from(new Set(V.filter(Boolean)));if(ae.length===0)return{updated:0,failed:0};const ve=((E=le==null?void 0:le.note)==null?void 0:E.trim())||void 0,re=((P=le==null?void 0:le.optionId)==null?void 0:P.trim())||void 0;if(r){const te=new Set(ae);return w(Re=>{const qe=Re.decisions.filter(ne=>te.has(ne.id));if(qe.length===0)return Re;const Ee=new Date().toISOString(),M=qe.map(ne=>({id:`decision:${G}:${ne.id}:${Date.now()}`,type:"decision_resolved",title:G==="approve"?`Approved: ${ne.title}`:`Rejected: ${ne.title}`,description:ne.context,agentId:null,agentName:ne.agentName,requesterAgentId:null,requesterAgentName:ne.agentName??null,executorAgentId:null,executorAgentName:ne.agentName??null,runId:null,initiativeId:null,timestamp:Ee,metadata:{decisionId:ne.id,action:G}})),q=ii(M.concat(Re.activity),d);return{...Re,decisions:Re.decisions.filter(ne=>!te.has(ne.id)),activity:q,lastActivity:St(Ee)}}),{updated:te.size,failed:0,firstError:void 0}}const Pe=new Date().toISOString(),Se=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:kt({contentTypeJson:!0,workspaceId:f}),body:JSON.stringify({ids:ae,action:G,...ve?{note:ve}:{},...re?{option_id:re}:{}})});try{const te=await Se.json().catch(()=>null),Re=Array.isArray(te==null?void 0:te.results)?te.results:[],qe=new Set(Re.filter(me=>me.ok).map(me=>me.id)),M=((K=Re.filter(me=>!me.ok).find(me=>typeof me.error=="string"&&me.error.trim().length>0))==null?void 0:K.error)??(typeof(te==null?void 0:te.error)=="string"&&te.error.trim().length>0?te.error:void 0);if(!Se.ok&&Se.status!==207){const me=M??`Decision action failed (${Se.status})`;throw new Error(me)}if(qe.size===0&&Se.ok&&((te==null?void 0:te.failed)??0)===0)for(const me of ae)qe.add(me);qe.size>0?w(me=>{const Te=me.decisions.filter(ze=>qe.has(ze.id));if(Te.length===0)return me;const et=new Date().toISOString(),tt=Te.map(ze=>({id:`decision:${G}:${ze.id}:${Date.now()}`,type:"decision_resolved",title:G==="approve"?`Approved: ${ze.title}`:`Rejected: ${ze.title}`,description:ze.context,agentId:null,agentName:ze.agentName,requesterAgentId:null,requesterAgentName:ze.agentName??null,executorAgentId:null,executorAgentName:ze.agentName??null,runId:null,initiativeId:null,timestamp:et,metadata:{decisionId:ze.id,action:G}})),Ce=ii(tt.concat(me.activity),d);return{...me,decisions:me.decisions.filter(ze=>!qe.has(ze.id)),activity:Ce,lastActivity:St(et)}}):Se.ok&&ae.length>0&&w(me=>({...me,decisions:me.decisions.filter(Te=>!ae.includes(Te.id))})),I();const q=(te==null?void 0:te.updated)??qe.size,ne=(te==null?void 0:te.failed)??Math.max(0,ae.length-qe.size);return Me({phase:ne>0?"error":"success",action:G,targetCount:ae.length,message:ne>0?`${G==="approve"?"Approve":"Reject"} completed with ${ne} failure${ne===1?"":"s"}.`:G==="approve"?`Approved ${q} decision${q===1?"":"s"}.`:`Rejected ${q} decision${q===1?"":"s"}.`,startedAt:Pe,completedAt:new Date().toISOString()},{autoResetMs:ne>0?8e3:4e3}),{updated:q,failed:ne,firstError:M}}catch(te){throw Me({phase:"error",action:G,targetCount:ae.length,message:te instanceof Error?te.message:"Decision update failed.",startedAt:Pe,completedAt:new Date().toISOString()}),te}},[i,I,d,f,Me,r]),ce=o.useCallback(async(V,G)=>T([V],"approve",G),[T]),ge=o.useCallback(async(V,G)=>T([V],"reject",G),[T]),J=o.useCallback(async()=>{let V=[];return w(G=>(V=G.decisions.map(le=>le.id),G)),V.length===0?{updated:0,failed:0}:T(V,"approve")},[T]),he=o.useCallback(async(V,G,le)=>T(V,G,le?{note:le}:void 0),[T]);return o.useEffect(()=>{i||Me(gr)},[i,Me]),o.useEffect(()=>{if(!t){se(!1),g(!1),U(null);return}if(r){I();return}if(I(),f){se(!0);return}const V=new URLSearchParams;f&&ss(V,f),b&&V.set("initiative",b);const G=V.toString()?`/orgx/api/live/stream?${V.toString()}`:"/orgx/api/live/stream",le=new EventSource(G),ae=new EventSource("/orgx/api/hooks/runtime/stream");let ve=null,re=null,Pe=null,Se=null,E=[],P=null,K;const te=()=>{if(K=void 0,ve){oe.current=Date.now(),we.current=!1;const Ee=ve;ve=null,Pe=null,Se=null,E=[],P=null,re=null,B(Ee.sessions,Ee.activity,Ee.handoffs,Ee.decisions,Ee.sliceRuns,Ee.outbox,Ee.generatedAt,Ee.runtimeInstances,Ee.chat,Ee.v2);return}!Pe&&!Se&&!P&&!re&&E.length===0||(oe.current=Date.now(),we.current=!1,w(Ee=>{var q;let M=Ee;if(Pe){const ne=Gs(Pe,l),me=Gs(pa(M.sessions,ne),l);Pe=null,ha(M.sessions,me)||(M={...M,sessions:me})}if(Se){const ne=fa(Se,u);Se=null,ga(M.handoffs,ne)||(M={...M,handoffs:ne})}if(P){const ne=ya(P,h);P=null,xa(M.decisions,ne)||(M={...M,decisions:ne})}if(re){const ne=wa(re);re=null,va(M.runtimeInstances,ne)||(M={...M,runtimeInstances:ne})}if(E.length>0){const ne=Zl(M.activity,E,d);E=[],ne!==M.activity&&(M={...M,activity:ne,lastActivity:(q=ne[0])!=null&&q.timestamp?St(ne[0].timestamp):M.lastActivity})}return M===Ee?Ee:M.connection==="connected"?M:{...M,connection:"connected"}}),U(null),g(!1))},Re=()=>{K||(K=setTimeout(te,y))};le.onopen=()=>{oe.current=Date.now(),we.current=!1,se(!1),w(Ee=>Ee.connection==="connected"?Ee:{...Ee,connection:"connected"}),U(null)},le.onerror=()=>{if(we.current){w(M=>M.connection==="disconnected"?M:{...M,connection:"disconnected"}),se(!1);return}const Ee=oe.current>0&&Date.now()-oe.current>da;w(M=>M.connection===(Ee?"disconnected":"reconnecting")?M:{...M,connection:Ee?"disconnected":"reconnecting"}),se(!0)},le.addEventListener("snapshot",Ee=>{try{const M=JSON.parse(Ee.data),q=typeof M.generatedAt=="string"&&M.generatedAt.length>0?M.generatedAt:new Date().toISOString();ve={sessions:M.sessions,activity:M.activity??[],handoffs:M.handoffs??[],decisions:M.decisions??null,sliceRuns:Array.isArray(M.sliceRuns)?Dr(M.sliceRuns):Array.isArray(M.projections)?ka(br(M.projections)):null,outbox:M.outbox??null,generatedAt:q,runtimeInstances:Array.isArray(M.runtimeInstances)?M.runtimeInstances:null,chat:Rr(M.chat??null),v2:{workSliceProjections:Array.isArray(M.projections)?br(M.projections):null,timelineNarrative:Array.isArray(M.timelineNarrative)?oi(M.timelineNarrative):null,nextUpByInitiative:Array.isArray(M.nextUpByInitiative)?li(M.nextUpByInitiative):null,runningWorkSlices:typeof M.runningWorkSlices=="number"?M.runningWorkSlices:null,needsInputTotal:typeof M.needsInput=="number"?M.needsInput:null,failedActionableTotal:typeof M.failedActionable=="number"?M.failedActionable:null,completedTodayTotal:typeof M.completedToday=="number"?M.completedToday:null,consistencyFlags:Array.isArray(M.consistencyFlags)?M.consistencyFlags:null,dataHealth:M.dataHealth??null}},Re()}catch(M){U(M instanceof Error?M.message:"Invalid snapshot")}}),le.addEventListener("activity.appended",Ee=>{try{const M=JSON.parse(Ee.data);if(M.length===0)return;E=E.concat(M),Re()}catch{}}),le.addEventListener("session.updated",Ee=>{try{Pe=JSON.parse(Ee.data),Re()}catch{}});const qe=Ee=>{try{const M=JSON.parse(Ee.data);re=Array.isArray(M)?M:[M],Re()}catch{}};return le.addEventListener("runtime.updated",qe),ae.addEventListener("runtime.updated",qe),le.addEventListener("handoff.updated",Ee=>{try{Se=JSON.parse(Ee.data),Re()}catch{}}),le.addEventListener("decision.updated",Ee=>{try{P=JSON.parse(Ee.data),Re()}catch{}}),()=>{K&&clearTimeout(K),le.close(),ae.close()}},[B,y,t,i,I,d,h,u,l,b,f,r]),o.useEffect(()=>{if(!(!t||r||(de.current&&clearInterval(de.current),!ie&&!!!f)))return de.current=setInterval(I,s),()=>{de.current&&clearInterval(de.current)}},[t,I,f,s,ie,r]),{data:k,isLoading:v,error:C,refetch:I,approveDecision:ce,rejectDecision:ge,approveAllDecisions:J,bulkDecisionAction:he,decisionMutation:x}}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 To(e){return lr.find(t=>t.id===e)??lr[0]}function cr(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 fc(e,t=Date.now()){const s=cr(e,t);return s?new Date(s).toISOString():null}const hc=new Set(["ungrouped","unscoped","unknown"]),gc="orgx.demo_mode",xc="orgx.show_synthetic_entities";function js(e){const t=(e??"").trim().toLowerCase();return!!(!t||hc.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Mt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(gc)==="1"}catch{return!1}}function yc(){if(typeof window>"u")return!1;if(Mt())return!0;try{return window.localStorage.getItem(xc)==="1"}catch{return!1}}function bc(e){return Mt()?!0:!js(e)}function Fi(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ro(e,t){const s=Fi(t.timestamp)-Fi(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function wc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function vc(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 Do(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=wc(e.metadata);return vc(s,["initiative_id","initiativeId"])}function ci(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function $i(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(!$i(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]||!$i(s[l],r[l]))return!1}return!0}const kc=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function Ds(e,...t){}function jc(e,t,s,r){const i=new Map,a=t.sinceEpoch,c=t.untilEpoch;let l=0,d=0,u=0;for(const h of e??[]){if(!h||typeof h.id!="string")continue;if(s&&h.runId!==s){l++;continue}if(r&&Do(h)!==r){d++;continue}const y=Fi(h.timestamp);if(y){if(a!==null&&y<a){u++;continue}if(c!==null&&y>c){u++;continue}i.set(h.id,h)}}return Ds("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(Ro)}function ja(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||!$i(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return Ds("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Ro):e}function Nc(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=Mt()}=e,h=o.useMemo(()=>ci(a),[a]),y=o.useMemo(()=>ci(c),[c]),b=o.useMemo(()=>ci(l),[l]),f=o.useMemo(()=>cr(s),[s]),k=o.useMemo(()=>fc(s),[s]),w=o.useMemo(()=>{if(s==="custom"){const J=(r==null?void 0:r.trim())??"";return J.length>0?J:null}return k},[r,k,s]),x=o.useMemo(()=>{if(s!=="custom")return null;const J=(i==null?void 0:i.trim())??"";return J.length>0?J:null},[i,s]),_=o.useMemo(()=>{if(w){const J=Date.parse(w);if(Number.isFinite(J))return J}return f},[f,w]),v=o.useMemo(()=>{if(!x)return null;const J=Date.parse(x);return Number.isFinite(J)?J:null},[x]),g=o.useMemo(()=>jc(t,{sinceEpoch:_,untilEpoch:v},h,y),[t,_,v,h,y]),C=u?null:"",[U,de]=o.useState(g),[ee,pe]=o.useState(()=>C),[ie,se]=o.useState(!1),[oe,we]=o.useState(null),[Ne,Q]=o.useState(null),je=o.useRef(null),Me=o.useRef(!1),B=o.useRef(g);B.current=g;const I=o.useMemo(()=>`${h??""}|${y??""}|${s}|${w??""}|${x??""}|${b??""}|${u?"demo":"live"}`,[h,y,s,w,x,b,u]),T=o.useRef(I);o.useEffect(()=>{T.current!==I&&(T.current=I,Ds("RESET",{reason:"filter/run change",runId:h,initiativeId:y,projectId:b,timeFilterId:s,sinceIso:w,untilIso:x,seedCount:B.current.length}),de(B.current),pe(C),we(null),Q(null),Me.current=!1)},[I,C,h,y,b,s,w,x]),o.useEffect(()=>{de(J=>{const he=ja(J,g);return he!==J&&Ds("SSE_MERGE",{prevCount:J.length,seedCount:g.length,nextCount:he.length,delta:he.length-J.length}),he})},[g]);const ce=o.useCallback(async()=>{if(u){pe(null),we(null);return}if(ee===null)return;if(je.current)return je.current;se(!0);const J=(async()=>{try{const he=new URLSearchParams;he.set("limit",String(Math.max(1,Math.min(500,d)))),ee.trim().length>0&&he.set("cursor",ee),w&&he.set("since",w),x&&he.set("until",x),h&&he.set("run",h),y&&he.set("initiative",y),b&&ss(he,b);const V=await fetch(`/orgx/api/live/activity/page?${he.toString()}`,{headers:kt({workspaceId:b})}),G=await V.json().catch(()=>null);if(!V.ok||!G){const ve=typeof(G==null?void 0:G.error)=="string"&&G.error.trim()||typeof(G==null?void 0:G.message)=="string"&&G.message.trim()||`Activity paging failed (${V.status})`;throw new Error(ve)}const le=Array.isArray(G.activities)?G.activities:[],ae=le.filter(ve=>!y||Do(ve)===y);Ds("PAGE_FETCH",{cursor:ee,rawCount:le.length,afterFilter:ae.length,filteredOut:le.length-ae.length,initiativeId:y,runId:h,nextCursor:G.nextCursor??null}),de(ve=>{const re=ja(ve,ae);return Ds("PAGE_MERGE",{prevCount:ve.length,pageCount:ae.length,nextCount:re.length,added:re.length-ve.length}),re}),pe(G.nextCursor??null),Q(G.storeUpdatedAt??null),we(null)}catch(he){const V=he instanceof Error?he.message:"";we(V?Cn(V):"Activity paging failed"),pe(G=>G===""?null:G)}finally{se(!1),je.current=null}})();return je.current=J,J},[ee,u,y,d,b,h,w,x]);return o.useEffect(()=>{ee===""&&(Me.current||(Me.current=!0,ce()))},[ee,ce]),{items:U,hasMore:ee!==null,isLoadingMore:ie,error:oe,storeUpdatedAt:Ne,loadMore:ce,cutoffEpoch:_,sinceIso:w,untilIso:x}}const Ic="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Ac="".trim().toLowerCase()==="true"||"".trim()==="1",Sc="".trim().toLowerCase()==="true"||"".trim()==="1",_c={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let di=null,Na=!1,Ia=!1,Xi=!1;function Cc(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Yr(){return Xi||!Ac?!1:Sc?!0:!Cc()}function Mc(){return Yr()?(di||(di=Pt(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(Xi=!0,null))),di):Promise.resolve(null)}function Ec(e){if(Na)return!0;try{return e.init(Ic,_c),Na=!0,!0}catch{return Xi=!0,!1}}async function Qi(){const e=await Mc();return!e||!Ec(e)?null:e}function Tc(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 Rc(){!Yr()||typeof window>"u"||Ia||(Ia=!0,Tc(()=>{Qi()}))}function Dc(e){if(!Yr())return;const t=e.trim();t&&Qi().then(s=>{if(s)try{s.identify(t)}catch{}})}function Qn(e,t){Yr()&&e.trim()&&Qi().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const Lc="https://orgx.mintlify.site/guides/openclaw-plugin-setup",Fc=1500,ui="orgx.onboarding.skip",$c=680,Pc=`<!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>`,Lr={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Lc,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Es(){return{...Lr,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function Oc(e){if(typeof e=="string")return e;if(e&&typeof e=="object")return JSON.stringify(e)}async function Xs(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:Oc(s==null?void 0:s.error)??`Request failed (${t.status})`}}function wr(e){if(e)try{Dc(e)}catch{}}function Bc(){const[e,t]=o.useState(()=>Mt()?Es():Lr),[s,r]=o.useState(()=>!Mt()),[i,a]=o.useState(!1),[c,l]=o.useState(!1),d=o.useRef(null),[u,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(ui)==="1"),y=o.useCallback(async()=>{if(Mt()){const g=Es();return t(g),g}const v=await Xs(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!v.ok||!v.data){const g=v.error??"Failed to load onboarding state",C={...Lr,status:"error",lastError:g,nextAction:"retry"};return t(C),C}return wr(v.data.installationId??null),t(v.data),v.data},[]);o.useEffect(()=>{if(Mt()){t(Es()),r(!1);return}let v=!1;return(async()=>{r(!0);const g=await y();v||(t(g),r(!1))})(),()=>{v=!0}},[y]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const g=Math.max(900,e.pollIntervalMs??Fc),C=window.setInterval(async()=>{const U=await Xs(fetch("/orgx/api/onboarding/status",{method:"GET"}));U.ok&&U.data&&(wr(U.data.installationId??null),t(U.data))},g);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 v=window.open("","_blank");return v?(v.opener=null,v.document.title="Connecting to OrgX…",v.document.open(),v.document.write(Pc),v.document.close(),v):null}catch{return null}},[]),f=o.useCallback(async()=>{if(Mt()){const g=Es();t(g);return}const v=b();d.current=v,a(!0);try{const g=await Xs(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),C=g.data;if(!g.ok||!(C!=null&&C.state)){v&&!v.closed&&v.close();const de=g.error??"Could not start pairing";t(ee=>({...ee,status:"error",lastError:de,nextAction:"enter_manual_key"}));return}t(C.state);const U=C.connectUrl;if(U){const de=d.current;let ee=!1;if(de&&!de.closed)try{window.setTimeout(()=>{if(!de.closed)try{de.location.href=U}catch{}},$c),ee=!0}catch{ee=!1}ee||(ee=!!window.open(U,"_blank","noopener,noreferrer")),ee||t(pe=>({...pe,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[b]),k=o.useCallback(async v=>{if(Mt()){const g=Es();return t(g),g}l(!0);try{const g=v.trim(),C=g.replace(/^[a-z]+_/i,""),U=Array.from(new Set([g,C?`oxk_${C}`:"",C?`orgx_${C}`:""].map(ee=>ee.trim()).filter(ee=>ee.length>0)));let de="Manual key validation failed";for(const ee of U){const pe={"Content-Type":"application/json","X-OrgX-Api-Key":ee,Authorization:`Bearer ${ee}`},ie=await Xs(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:pe,body:JSON.stringify({apiKey:ee})}));if(ie.ok&&ie.data)return wr(ie.data.installationId??null),t(ie.data),ie.data;de=ie.error??de}throw t(ee=>({...ee,status:"manual_key",lastError:de,nextAction:"enter_manual_key"})),new Error(de)}finally{l(!1)}},[]),w=o.useCallback(async()=>{if(Mt()){const C=Es();return t(C),C}const v=await Xs(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(v.ok&&v.data)return wr(v.data.installationId??null),t(v.data),v.data;const g={...Lr,status:"idle"};return t(g),g},[]),x=o.useCallback(()=>{t(v=>({...v,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),_=o.useMemo(()=>Mt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:_,isLoading:s,isStarting:i,isSubmittingManual:c,refreshStatus:y,startPairing:f,submitManualKey:k,disconnect:w,skipGate:()=>h(!0),resumeGate:()=>h(!1),backToPairing:x,setManualMode:()=>t(v=>({...v,status:"manual_key",nextAction:"enter_manual_key"}))}}const Bn={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 qc extends Error{constructor(s,r){super(s);Vs(this,"code","upgrade_required");Vs(this,"currentPlan");Vs(this,"requiredPlan");Vs(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 zc(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 qc(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 Xf(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"}const Wc=750;async function Qs(e){return await e.json().catch(()=>null)}function Uc(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 vr(e,t,s){if(Uc(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 Cn(r)}function Hc(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?Cn(s):t}function Vc(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 Fr({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 Kc(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 Gc(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;if(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")return!1;if(e.queueState==="running"||e.queueState==="blocked")return!0;const s=!!(e.autoContinue.activeRunId||e.autoContinue.activeTaskId),r=!!(Array.isArray(e.autoContinue.activeRunIds)&&e.autoContinue.activeRunIds.length>0);if(s||r)return!0;const i=Date.parse(e.autoContinue.updatedAt??"");return Number.isFinite(i)?Date.now()-i<=45e3:!1}function Ji(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 Yi(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 Lo(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=Ji(typeof c.id=="string"?c.id:null),d=Yi(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 Xc(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Qc(e){const t=Ji(e.runnerAgentId),s=Yi(e.runnerAgentName,t),r=Lo(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=Xc(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(h=>typeof h=="string"&&h.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:Gc(e),autoRuntimeState:Kc(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 Fr(e){const t=e.items.map(u=>Qc(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 Jc(e){const t=(e.queueState??"").trim().toLowerCase();if(t==="queued"||t==="running"||t==="blocked"||t==="idle")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"?"idle":"queued"}function Yc(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 Zc(e){var y,b,f,k,w,x,_,v,g,C,U,de,ee,pe,ie,se;const t=((b=(y=e.lineage)==null?void 0:y.initiativeIds)==null?void 0:b.filter(oe=>typeof oe=="string"&&oe.trim().length>0))??[],s=((k=(f=e.lineage)==null?void 0:f.workstreamIds)==null?void 0:k.filter(oe=>typeof oe=="string"&&oe.trim().length>0))??[],r=((w=e.initiativeId)==null?void 0:w.trim())||t[0]||null,i=((x=e.workstreamId)==null?void 0:x.trim())||((v=(_=e.sourceWorkstreamIds)==null?void 0:_.find(oe=>typeof oe=="string"&&oe.trim().length>0))==null?void 0:v.trim())||s[0]||null;if(!r||!i)return null;const a=((C=(g=e.lineage)==null?void 0:g.taskIds)==null?void 0:C.filter(oe=>typeof oe=="string"&&oe.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,l=Ji(e.runnerAgentId??null),d=Yi(e.runnerAgentName??null,l),u=Lo(e.runnerAgents??null,l,d),h=u[0]??null;return{initiativeId:r,initiativeTitle:((U=e.initiativeTitle)==null?void 0:U.trim())||t[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:i,workstreamTitle:((de=e.workstreamTitle)==null?void 0:de.trim())||((ee=e.title)==null?void 0:ee.trim())||((pe=e.milestoneTitle)==null?void 0:pe.trim())||((ie=e.taskTitle)==null?void 0:ie.trim())||Yc(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((se=e.taskTitle)==null?void 0:se.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(h==null?void 0:h.id)??l,runnerAgentName:(h==null?void 0:h.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(h?"inferred":"fallback"),queueState:Jc(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 ed({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=100,authToken:i=null,embedMode:a=!1,enabled:c=!0,snapshotVersion:l=null}){var ee,pe,ie,se,oe,we,Ne,Q,je,Me;const d=Ki(),u=Mt(),h=Math.max(0,s),y=Math.max(1,Math.min(300,r)),b=o.useRef(null);o.useEffect(()=>()=>{b.current&&(clearTimeout(b.current),b.current=null)},[]);const f=o.useMemo(()=>Bn.nextUpQueue({initiativeId:e,projectId:t,offset:h,limit:y,authToken:i,embedMode:a}),[e,t,h,y,i,a]),k=o.useRef(l);o.useEffect(()=>{l!==null&&k.current!==null&&l!==k.current&&d.invalidateQueries({queryKey:f}),k.current=l},[l,d,f]);const w=()=>{b.current&&(clearTimeout(b.current),b.current=null),b.current=setTimeout(()=>{b.current=null,d.invalidateQueries({queryKey:Bn.liveData({authToken:i,embedMode:a,projectId:t})})},Wc)},x=async()=>{await Promise.all([d.invalidateQueries({queryKey:f}),d.invalidateQueries({queryKey:Bn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})}),d.invalidateQueries({queryKey:Bn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})]),w()},_=async(B,I)=>{if(u)return Vc(e);const T=new URLSearchParams;e&&T.set("initiative_id",e),ss(T,t,{allTokenWhenMissing:!0}),T.set("offset",String(B)),T.set("limit",String(I));let ce;try{ce=await fetch(`/orgx/api/mission-control/next-up?${T.toString()}`,{headers:kt({authToken:i,embedMode:a})})}catch(le){throw new Error(Hc(le,"Failed to load next up queue"))}const ge=await Qs(ce);if(!ce.ok){const le=vr(ce,ge,"Failed to load next up queue");throw new Error(le)}const J=ge??null;if(!J||J.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:B,limit:I,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(yc())return Fr(J);const he=J.items.filter(le=>!js(le.initiativeId));let V=Fr({...J,items:he});if(V.items.length>0)return V;const G=new URLSearchParams;e&&G.set("initiative_id",e),ss(G,t,{allTokenWhenMissing:!0}),G.set("level","workstream"),G.set("include_completed","0"),G.set("offset",String(B)),G.set("limit",String(Math.max(I,24)));try{const le=await fetch(`/orgx/api/mission-control/slices?${G.toString()}`,{headers:kt({authToken:i,embedMode:a})}),ae=await Qs(le);if(le.ok&&(ae!=null&&ae.ok)&&Array.isArray(ae.items)){const ve=ae.items.map(re=>Zc(re)).filter(re=>!!re).filter(re=>!js(re.initiativeId));ve.length>0&&(V=Fr({ok:!0,generatedAt:new Date().toISOString(),total:typeof ae.total=="number"&&Number.isFinite(ae.total)?Math.max(ae.total,ve.length):ve.length,items:ve,pagination:ae.pagination&&typeof ae.pagination=="object"?{offset:typeof ae.pagination.offset=="number"?Math.max(0,Math.floor(ae.pagination.offset)):B,limit:typeof ae.pagination.limit=="number"?Math.max(1,Math.floor(ae.pagination.limit)):Math.max(I,24),total:typeof ae.pagination.total=="number"?Math.max(0,Math.floor(ae.pagination.total)):ve.length,nextCursor:typeof ae.pagination.nextCursor=="string"?ae.pagination.nextCursor:null,hasMore:typeof ae.pagination.hasMore=="boolean"?ae.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...J.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return V},v=ns({queryKey:f,enabled:c,queryFn:async()=>_(h,y),refetchInterval:B=>{const I=B.state.data;return!I||!Array.isArray(I.items)||I.items.length===0?1e4:I.items.some(ce=>ce.queueState==="running")?2500:8e3}}),g=o.useRef(null);o.useEffect(()=>{var T;const B=(T=v.data)==null?void 0:T.pagination;if(!c||!(B!=null&&B.hasMore)||!B.nextCursor||g.current===B.nextCursor)return;const I=Number.parseInt(B.nextCursor,10);Number.isFinite(I)&&(g.current=B.nextCursor,d.prefetchQuery({queryKey:Bn.nextUpQueue({initiativeId:e,projectId:t,offset:I,limit:y,authToken:i,embedMode:a}),queryFn:()=>_(I,y),staleTime:15e3}))},[c,(pe=(ee=v.data)==null?void 0:ee.pagination)==null?void 0:pe.hasMore,(se=(ie=v.data)==null?void 0:ie.pagination)==null?void 0:se.nextCursor,e,t,y,i,a,d]);const C=xn({mutationFn:async B=>{if(u)return{ok:!0,initiativeId:B.initiativeId,workstreamId:B.workstreamId,dispatchMode:"slice",sessionId:null};const I=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:kt({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:B.initiativeId,workstreamId:B.workstreamId,agentId:B.agentId??void 0,scope:B.scope??void 0,maxParallelSlices:typeof B.maxParallelSlices=="number"&&Number.isFinite(B.maxParallelSlices)?Math.max(1,Math.floor(B.maxParallelSlices)):void 0,parallelMode:B.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),T=await Qs(I);if(!I.ok)throw new Error(vr(I,T,"Failed to dispatch queued workstream"));return T},onMutate:async B=>{await d.cancelQueries({queryKey:f});const I=d.getQueryData(f);return I?(d.setQueryData(f,{...I,items:I.items.map(T=>T.initiativeId===B.initiativeId&&T.workstreamId===B.workstreamId?{...T,queueState:"running",playbackState:"running"}:T.queueState==="running"?{...T,queueState:"idle",playbackState:"idle"}:T)}),{previous:I}):{previous:I}},onError:(B,I,T)=>{T!=null&&T.previous&&d.setQueryData(f,T.previous)},onSuccess:()=>{x()}}),U=xn({mutationFn:async B=>{if(u)return;const I={initiativeId:B.initiativeId,agentId:B.agentId??void 0,tokenBudgetTokens:B.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};B.scope==="workstream"&&B.workstreamId&&(I.workstreamIds=[B.workstreamId]),typeof B.maxParallelSlices=="number"&&Number.isFinite(B.maxParallelSlices)&&(I.maxParallelSlices=B.maxParallelSlices),B.parallelMode==="iwmt"&&(I.parallelMode=B.parallelMode);const T=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:kt({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(I)}),ce=await Qs(T);if(!T.ok){const ge=zc(ce);throw ge||new Error(vr(T,ce,"Failed to start auto-continue"))}},onSuccess:()=>{x()}}),de=xn({mutationFn:async B=>{if(u)return;const I=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:kt({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:B.initiativeId})}),T=await Qs(I);if(!I.ok)throw new Error(vr(I,T,"Failed to stop auto-continue"))},onSuccess:()=>{x()}});return{items:((oe=v.data)==null?void 0:oe.items)??[],total:((we=v.data)==null?void 0:we.total)??0,pagination:((Ne=v.data)==null?void 0:Ne.pagination)??null,generatedAt:((Q=v.data)==null?void 0:Q.generatedAt)??null,degraded:((je=v.data)==null?void 0:je.degraded)??[],isLoading:v.isLoading,isFetching:v.isFetching,error:((Me=v.error)==null?void 0:Me.message)??null,refetch:v.refetch,playWorkstream:C.mutateAsync,startWorkstreamAutoContinue:U.mutateAsync,stopInitiativeAutoContinue:de.mutateAsync,isPlaying:C.isPending,isStartingAutoContinue:U.isPending,isStoppingAutoContinue:de.isPending}}const td=750;async function en(e){return await e.json().catch(()=>null)}function Rs(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 tn(e,t,s){if(Rs(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 Cn(r)}function nd(e){const t=e.authToken??null,s=e.embedMode??!1,r=Mt(),i=Ki(),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"]})},td)},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 v=>{if(r)return{ok:!0,demo:!0,initiativeId:v.initiativeId,workstreamId:v.workstreamId,placement:v.placement??"top"};const g=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(g.ok)return C;if(!Rs(g,C))throw new Error(tn(g,C,"Failed to move Next Up item"));const U=await fetch("/orgx/api/mission-control/next-up",{headers:kt({authToken:t,embedMode:s})}),de=await en(U);if(!U.ok)throw new Error(tn(U,de,"Failed to read queue for move fallback"));const pe=(Array.isArray(de==null?void 0:de.items)?de.items:[]).map(Ne=>{const Q=typeof(Ne==null?void 0:Ne.initiativeId)=="string"?Ne.initiativeId:null,je=typeof(Ne==null?void 0:Ne.workstreamId)=="string"?Ne.workstreamId:null;return!Q||!je?null:{initiativeId:Q,workstreamId:je}}).filter(Ne=>!!Ne);if(pe.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const ie=pe.findIndex(Ne=>Ne.initiativeId===v.initiativeId&&Ne.workstreamId===v.workstreamId);if(ie===-1)return{ok:!0,fallback:"reorder-move-skip"};const[se]=pe.splice(ie,1);(v.placement??"top")==="bottom"?pe.push(se):pe.unshift(se);const oe=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:pe})}),we=await en(oe);if(!oe.ok)throw new Error(tn(oe,we,"Failed to move Next Up item with reorder fallback"));return we??{ok:!0,fallback:"reorder-move"}},u=async v=>{if(r)return{ok:!0,demo:!0,initiativeId:v.initiativeId,workstreamId:v.workstreamId};const g=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(g.ok)return C;if(Rs(g,C)){const U=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),de=await en(U);if(!U.ok)throw new Error(tn(U,de,"Failed to remove item from queue with legacy fallback"));return de??{ok:!0,fallback:"next-up-unpin"}}throw new Error(tn(g,C,"Failed to remove item from queue"))},h=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0};const g=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok)throw new Error(tn(g,C,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),y=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0};const g=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok)throw new Error(tn(g,C,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),b=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0,updated:v.order.length};const g=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok)throw new Error(tn(g,C,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),f=xn({mutationFn:d,onSuccess:()=>{l()}}),k=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0,initiativeId:v.initiativeId,workstreamId:v.workstreamId};const g=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok){if(Rs(g,C)){const U=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:v.initiativeId})}),de=await en(U);if(!U.ok)throw new Error(tn(U,de,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(tn(g,C,"Failed to stop triage"))}return C},onSuccess:()=>{l()}}),w=xn({mutationFn:u,onSuccess:()=>{l()}}),x=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0,cleared:!0};const g=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok){if(Rs(g,C)&&v.initiativeId){const U=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:v.initiativeId})}),de=await en(U);if(!U.ok)throw new Error(tn(U,de,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(tn(g,C,"Failed to clear Next Up lifecycle state"))}return C},onSuccess:()=>{l()}}),_=xn({mutationFn:async v=>{if(r)return{ok:!0,demo:!0,updated:v.items.length,failed:0,errors:[],fallback:"demo"};const g=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:kt({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(v)}),C=await en(g);if(!g.ok){if(!Rs(g,C))throw new Error(tn(g,C,"Failed to apply bulk queue action"));const U=await Promise.all(v.items.map(async ie=>{try{return v.action==="remove"?await u(ie):await d({initiativeId:ie.initiativeId,workstreamId:ie.workstreamId,placement:v.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(se){return{ok:!1,error:se instanceof Error?se.message:"Queue action failed"}}})),de=U.filter(ie=>ie.ok).length,ee=U.length-de,pe=U.filter(ie=>!ie.ok&&ie.error).map(ie=>ie.error);return{ok:ee===0,updated:de,failed:ee,errors:pe,fallback:"sequential"}}return C},onSuccess:()=>{l()}});return{pin:h.mutateAsync,unpin:y.mutateAsync,reorder:b.mutateAsync,move:f.mutateAsync,remove:w.mutateAsync,stopTriage:k.mutateAsync,clear:x.mutateAsync,bulk:_.mutateAsync,isPinning:h.isPending,isUnpinning:y.isPending,isReordering:b.isPending,isMoving:f.isPending,isRemoving:w.isPending,isStoppingTriage:k.isPending,isClearing:x.isPending,isBulking:_.isPending}}function Fo(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function sd(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:Fo(s,r)});if(!c.ok)throw new Error(`Triage fetch failed: ${c.status}`);return c.json()}async function rd(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:Fo(s,r),body:JSON.stringify(t)});if(!c.ok){const l=await c.json().catch(()=>({}));throw new Error(l.error??`Action failed: ${c.status}`)}return c.json()}function id(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,c=Ki(),l=Bn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=ns({queryKey:l,queryFn:()=>sd(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=xn({mutationFn:async({itemId:f,payload:k})=>rd(f,k,i,a),onSuccess:()=>{c.invalidateQueries({queryKey:l})}}),h=o.useCallback(async(f,k,w)=>u.mutateAsync({itemId:f,payload:{action:k,note:w==null?void 0:w.note,optionId:w==null?void 0:w.optionId,snoozeDurationMinutes:w==null?void 0:w.snoozeDurationMinutes}}),[u]),y=o.useMemo(()=>{var f,k,w;return{items:((f=d.data)==null?void 0:f.items)??[],total:((k=d.data)==null?void 0:k.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((w=d.data)==null?void 0:w.degraded)??[],refetch:d.refetch}},[d]),b=o.useMemo(()=>({performAction:h,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[h,u.isPending,u.error]);return{model:y,actions:b}}function ue(...e){return e.filter(Boolean).join(" ")}const L={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"},ad={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},od={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function ld(e){return ad[e]??"rgba(255, 255, 255, 0.4)"}function $o(e){return od[e]??null}function cd(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function Dt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Yt={durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},Qf={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},Zr="/orgx/live/assets/Fm0FhtnV.png";function Po({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 Sn({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??L.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??L.lime;return n.jsx(Po,{size:s,className:t,stroke:c,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${c}1A`})}if(e==="milestone"){const c=r??L.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??L.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??L.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??L.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??L.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??L.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??L.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??L.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??L.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 dd=[{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"}],$r=[{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."}],ud=[{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."}],Aa="openclaw plugins install @useorgx/openclaw-plugin",Sa="orgx.demo_mode",md=6500;function pd(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 fd={hidden:{},visible:{transition:{staggerChildren:.07}}},Jn={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},hd={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 mi(e){const t=$r.length;return(e+t)%t}function gd({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,[c,l]=o.useState("idle"),[d,u]=o.useState("idle"),[h,y]=o.useState(0),[b,f]=o.useState(!1),k=e.hasApiKey&&e.keySource&&e.keySource!=="none",w=$r[h];o.useEffect(()=>{if(c==="idle")return;const v=window.setTimeout(()=>l("idle"),2e3);return()=>window.clearTimeout(v)},[c]),o.useEffect(()=>{if(d==="idle")return;const v=window.setTimeout(()=>u("idle"),2e3);return()=>window.clearTimeout(v)},[d]),o.useEffect(()=>{if(b)return;const v=window.setInterval(()=>{y(g=>mi(g+1))},md);return()=>window.clearInterval(v)},[b]);const x=async()=>{try{await navigator.clipboard.writeText(Aa),l("ok")}catch{l("error")}},_=async()=>{try{const v={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(v,null,2)),u("ok")}catch{u("error")}};return n.jsxs(ye.section,{variants:fd,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(ye.div,{variants:Jn,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Zr,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(ye.h2,{variants:Jn,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(Sn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ye.p,{variants:Jn,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(ye.div,{variants:Jn,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:()=>f(!0),onMouseLeave:()=>f(!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(Sn,{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:[h+1,"/",$r.length]})]}),n.jsx(pt,{initial:!1,mode:"wait",children:n.jsxs(ye.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:w.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:w.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:w.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:w.highlights.map(v=>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(Sn,{type:v.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:v.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:v.detail})]},`${w.id}-${v.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:w.footnote})]},w.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:$r.map((v,g)=>{const C=g===h;return n.jsx("button",{type:"button",onClick:()=>y(g),"aria-label":`View slide ${g+1}`,className:`h-1.5 rounded-full transition-all ${C?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},v.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(v=>mi(v-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>y(v=>mi(v+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:dd.map(v=>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 ${hd[v.iconType]}`,children:n.jsx(Sn,{type:v.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:v.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:v.desc})]},v.label))}),n.jsxs(ye.div,{variants:Jn,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(ye.div,{variants:Jn,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(Sn,{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(Sn,{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:Aa}),n.jsx("button",{type:"button",onClick:()=>{x()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:c==="ok"?"Copied":c==="error"?"Copy failed":"Copy command"})]}),k&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",pd(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:ud.map(v=>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(Sn,{type:v.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:v.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:v.detail})]},v.label))})]})]})]}),n.jsx(ye.div,{variants:Jn,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:e.lastError})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void _(),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:d==="ok"?"Copied":d==="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(ye.div,{variants:Jn,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(Sa,"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(Sa)}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 xd={hidden:{},visible:{transition:{staggerChildren:.06}}},gs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function yd({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 h=r.trim();if(!h){c("API key is required.");return}const y=/^[a-z]+_/i.test(h)?h:`oxk_${h}`;try{await t(y),i("")}catch(b){c(b instanceof Error?b.message:"Failed to validate API key.")}},u=a!==null;return n.jsxs(ye.section,{variants:xd,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(ye.div,{variants:gs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Zr,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(ye.h3,{variants:gs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ye.p,{variants:gs,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(ye.p,{variants:gs,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(ye.div,{variants:gs,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(ye.div,{variants:gs,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:h=>{i(h.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(ye.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(ye.div,{variants:gs,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 _a="orgx.user.display-name",Ca="orgx.user.avatar-seed-suffix";function Ma(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Ea(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function bd(){const[e,t]=o.useState(()=>Ma(_a)),[s,r]=o.useState(()=>Ma(Ca)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();Ea(_a,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());Ea(Ca,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function wd(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function vd(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 Ta=[L.lime,L.teal,L.iris,L.cyan];function kd(e,t,s,r,i,a){const c=C=>C*Math.PI/180,l=Math.cos,d=Math.sin,u=c(i),h=c(a),y=a-i>180?1:0,b=e+r*l(u),f=t+r*d(u),k=e+r*l(h),w=t+r*d(h),x=e+s*l(h),_=t+s*d(h),v=e+s*l(u),g=t+s*d(u);return[`M ${b} ${f}`,`A ${r} ${r} 0 ${y} 1 ${k} ${w}`,`L ${x} ${_}`,`A ${s} ${s} 0 ${y} 0 ${v} ${g}`,"Z"].join(" ")}function jd(e){const t=vd(wd(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),h=360/u,y=1.5+t()*2;for(let b=0;b<u;b++){if(t()<.15)continue;const f=b*h+y/2,k=(b+1)*h-y/2,w=Ta[Math.floor(t()*Ta.length)],x=.25+t()*.55;r.push({d:kd(i,a,l,d,f,k),fill:w,opacity:x})}}return r}function Nd({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>jd(e),[e]);return n.jsxs(ye.svg,{viewBox:"0 0 100 100",width:t,height:t,className:ue("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Yt.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:L.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:L.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:L.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(ye.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:Yt.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 Id({onComplete:e}){const{displayName:t,updateName:s}=bd(),[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(ye.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:Yt.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(Nd,{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 Ad=[{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 Sd({className:e,compact:t=!1}){return n.jsxs("div",{className:ue("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"]}),Ad.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 Ra="orgx.user.name-asked";function _d(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 Cd(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 Md(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Da={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},pi="orgx.onboarding.mc_hint.dismissed",fi={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 Ed({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:c,onBackToPairing:l,onUseManualKey:d,onSkip:u}){const[h,y]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(pi)==="1"),[b,f]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ra)!=="1"),k=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Ra,"1"),f(!1)},[]);o.useEffect(()=>{typeof window>"u"||(h?window.localStorage.setItem(pi,"1"):window.localStorage.removeItem(pi))},[h]);const w=e.status==="manual_key",x=e.status==="awaiting_browser_auth"||e.status==="pairing",_=Md(e.status),v=_==="active"&&e.status!=="connected",g=e.status==="connected"&&!h;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(ye.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${w?"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(pt,{mode:"wait",children:e.status==="connected"&&b?n.jsx(ye.div,{...fi,children:n.jsx(Id,{onComplete:k})},"welcome-name"):w?n.jsx(ye.div,{...fi,children:n.jsx(yd,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(ye.div,{...fi,children:n.jsx(gd,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(x||e.status==="connected")&&n.jsxs(ye.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:[v&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Da[_]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Da[_]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:_d(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Cd(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&&x&&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"})]})]}),g&&n.jsxs(ye.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:()=>y(!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(Sd,{compact:!0})})]})})}function Td({children:e,color:t,pulse:s,title:r}){const i=t??L.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title:r,style:{backgroundColor:`${i}22`,border:`1px solid ${i}5a`,color:i},children:[n.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s&&n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",style:{backgroundColor:i}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:i}})]}),e]})}function ei({open:e,onClose:t,children:s,maxWidth:r="max-w-2xl",fitContent:i=!1,closeOnBackdropClick:a=!0,closeOnEscape:c=!0,closeOnEscapeWhenTyping:l=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const k=d.current;if(!k)return;const w=k.querySelector('[data-modal-autofocus="true"]');if(w){w.focus();return}const x=k.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');x.length>0?x[0].focus():k.focus()})();const b=k=>{if(k.key==="Escape"){if(!c)return;if(!l){const C=k.target;if(C&&(C.tagName==="INPUT"||C.tagName==="TEXTAREA"||C.tagName==="SELECT"||C.isContentEditable))return}k.preventDefault(),t();return}if(k.key!=="Tab")return;const w=d.current;if(!w)return;const x=w.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(x.length===0){k.preventDefault(),w.focus();return}const _=x[0],v=x[x.length-1],g=document.activeElement;!k.shiftKey&&g===v?(k.preventDefault(),_.focus()):k.shiftKey&&g===_&&(k.preventDefault(),v.focus())},f=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",b),()=>{var k;document.body.style.overflow=f,document.removeEventListener("keydown",b),(k=u.current)==null||k.focus()}},[e,t,c,l]);const h=n.jsx(pt,{children:e&&n.jsxs(ye.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(ye.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:L.cardBgElevated,borderColor:L.cardBorderStrong},onClick:y=>y.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"?h:yl.createPortal(h,document.body)}const Rd=[{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 Dd({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:Rd.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:ue("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(ye.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(ye.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:L.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:ue("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:L.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:ue("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function $s({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:ue("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Ld={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"},Fd="/orgx/live/",nn=e=>`${Fd.replace(/\/+$/,"/")}${e}`,$d={pace:nn("brand/product-orchestrator.png"),eli:nn("brand/engineering-autopilot.png"),mark:nn("brand/launch-captain.png"),sage:nn("brand/pipeline-intelligence.png"),orion:nn("brand/control-tower.png"),dana:nn("brand/design-codex.png"),xandy:nn("brand/xandy-orchestrator.png"),nova:nn("brand/xandy-orchestrator.png"),openclaw:nn("brand/openclaw-mark.svg"),codex:nn("brand/openai-mark.svg"),openai:nn("brand/openai-mark.svg"),anthropic:nn("brand/anthropic-mark.svg"),orgx:nn("brand/orgx-logo.png")},Pd=[{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 Od(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of Pd)if(s.test.test(t))return $d[s.key];return null}function Rt({name:e,size:t="xs",hint:s,src:r}){const i=ld(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:Od(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Ld[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"}):cd(e)})}Rt.displayName="AgentAvatar";const Bd={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 In({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:ue("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",Bd[t],s),...r,children:e})}function qd(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||ws(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=Oo(e.status),c={id:e.workstreamId,label:e.workstreamTitle||ws(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||ws(l.id,"Milestone"),type:"milestone",status:d,progress:{done:l.done,total:l.total}};l.total>0&&(u.children=Array.from({length:l.total},(h,y)=>({id:`${l.id}-task-${y}`,label:`Task ${y+1}`,type:"task",status:y<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:ws(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function Jf(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||ws(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||ws(e.workstreamId,"Workstream"),type:"workstream",status:Oo(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||ws(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 ws(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function Oo(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 Bo(e){switch(e){case"done":return L.lime;case"active":return L.teal;case"blocked":return L.amber;case"failed":return L.red;default:return"rgba(255,255,255,0.15)"}}function zd(e){const t=Bo(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Wd=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(ye.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Ud=16,Hd=14,La=8,Vd=8,Kd=28,Gd=24,Xd=24,Qd=20,hi="rgba(255,255,255,0.07)";function Jd(e){const t=e?Hd:Ud,s=t+Vd+4;return{iconSz:t,colW:s,rowH:e?Xd:Kd,rowHTask:e?Qd:Gd}}function qo({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,h=e.progress&&e.progress.total>0,y=e.type==="task",{iconSz:b,colW:f,rowH:k,rowHTask:w}=Jd(i),x=y?w:k,_=e.children??[],v=_.filter(ie=>ie.type==="task"),g=_.filter(ie=>ie.type!=="task"),C=v.length>c&&!l,U=C?v.slice(0,c):v,de=v.length-U.length,ee=[...g,...U],pe=ee.length>0||C;return n.jsxs("div",{className:"relative",style:{minHeight:x},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:hi,left:(t-1)*f+f/2,top:0,bottom:s?void 0:0,height:s?x/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:hi,left:(t-1)*f+f/2,top:x/2,width:f}})]}),n.jsxs(ye.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:x,paddingLeft:t*f},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:f,height:x},children:y?n.jsx("span",{className:"inline-block rounded-full",style:{...zd(e.status),width:La,height:La}}):n.jsx(Sn,{type:e.type,size:b,accent:u?L.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 ${y?`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}),h&&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})]}),h&&!y&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Wd,{done:e.progress.done,total:e.progress.total,color:Bo(e.status)})})]})]}),pe&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:hi,left:t*f+f/2,top:x/2,height:x/2}}),pe&&n.jsxs("div",{children:[ee.map((ie,se)=>n.jsx(qo,{node:ie,depth:t+1,isLast:se===ee.length-1&&!C,activeId:r,compact:i,index:a+se+1,taskLimit:c,expanded:l,onToggleExpand:d},ie.id)),C&&n.jsxs(ye.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+ee.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:w,paddingLeft:(t+1)*f+f},children:["+",de," more · see all"]}),n.jsx(pt,{children:l&&v.length>c&&n.jsx(ye.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:w},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)*f+f},children:"show less"})})]})]})}const Yd=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(qo,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:c,onToggleExpand:()=>l(h=>!h)},d.id))})}),Pi={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"}},Zd=Object.keys(Pi);function Fa(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of Zd)if(t.includes(s))return s;return"engineering"}function $a(e){return Pi[e]??Pi.engineering}const eu={Eli:"#BFFF00",Pace:"#7C7CFF",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},tu={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Sales",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},nu={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","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","sales-bot":"Sage","operations-bot":"Orion","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"},su={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova",strategy:"Sage"};function Pa(e){const t=tu[e]??"";return{name:e,domain:t,color:eu[e]??"rgba(255,255,255,0.4)",displayLabel:t?`${e} (${t})`:e}}function Oa(e){const t=e==null?void 0:e.trim().toLowerCase();if(!t)return null;const s=nu[t];if(s)return s;for(const[r,i]of Object.entries(su))if(t.includes(r))return i;return null}function zo(e,t){const s=Oa(e);if(s)return Pa(s);const r=Oa(t);if(r)return Pa(r);const i=(t==null?void 0:t.trim())||"OrgX";return{name:i,domain:"",color:"rgba(255,255,255,0.4)",displayLabel:i}}function Yf({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(Rt,{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 ru=new Set(["running","active","in_progress","working","planning","dispatching"]),iu=new Set(["running","dispatching"]),au=3*6e4;function ou(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=au:!1}function lu(e){const t=Dt(e.status??""),s=Dt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:ru.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?ou(e.lastHeartbeatAt):!1}function Wo(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function cu(e){const t=Dt(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 du(e){const t=Dt(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 Uo(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function kr(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function xs(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 Wr(e,t){if(!e)return t;const s=e.trim();return s?qn(s)?`${t} ${Yn(s)}`:s:t}const uu=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),mu=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function pu(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?uu.has(t)||t.startsWith("telegram:"):!1}function fu(e){if(!e)return!1;const t=e.trim();return t?mu.some(s=>s.test(t)):!1}function Ho({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var y,b,f,k,w;const r=new Map;for(const x of s)x.id&&r.set(x.id,x.name??x.id);const i=new Map;for(const x of e){const _=(y=x.runId)==null?void 0:y.trim();!_||i.has(_)||i.set(_,x)}const a=new Map;for(const x of e){const _=((b=x.initiativeId)==null?void 0:b.trim())??"",v=((f=x.workstreamId)==null?void 0:f.trim())??"";if(!_||!v)continue;const g=`${_}:${v}`;a.has(g)||a.set(g,x)}const c=new Set;for(const x of e){const _=(k=x.runId)==null?void 0:k.trim();_&&c.add(_)}const l=[];for(const x of t){if(!iu.has(x.status))continue;const _=(x.runId??x.sliceRunId??"").trim();if(!_)continue;const v=xs(x.initiativeIds,x.initiativeId),g=xs(x.workstreamIds,x.workstreamId),C=v[0]??null,U=g[0]??null,de=[];for(const oe of v)for(const we of g)!oe||!we||de.push(`${oe}:${we}`);if(!(c.has(_)||de.some(oe=>a.has(oe))))continue;const pe=i.get(_)??(de.length>0?de.map(oe=>a.get(oe)??null).find(oe=>!!oe)??null:null),ie=C?r.get(C)??C:null,se=x.scopeProgress&&typeof x.scopeProgress.totalTasks=="number"&&x.scopeProgress.totalTasks>0?Math.round(x.scopeProgress.completedTasks/x.scopeProgress.totalTasks*100):null;l.push({key:`slice:${x.sliceRunId}`,source:"slice",session:pe??null,runId:_,status:Dt(x.status),title:x.workstreamTitle??(pe==null?void 0:pe.title)??`Work slice ${x.sliceRunId.slice(0,8)}`,subtitle:x.statusExplainer??x.lastEventSummary??(pe==null?void 0:pe.lastEventSummary)??null,progress:se??(pe==null?void 0:pe.progress)??null,initiativeId:C,initiativeIds:v,initiativeTitle:ie,workstreamId:U,workstreamIds:g,iwmtId:x.iwmtId??null,iwmtIds:xs(x.iwmtIds,x.iwmtId),workstreamTitle:x.workstreamTitle??(pe==null?void 0:pe.title)??null,taskIds:Array.isArray(x.taskIds)?x.taskIds:[],milestoneIds:Array.isArray(x.milestoneIds)?x.milestoneIds:[],artifactCount:x.artifactCount??0,decisionCount:x.blockingDecisionCount??x.decisionCount??0,updatedAt:x.updatedAt??x.lastEventAt??(pe==null?void 0:pe.updatedAt)??null,scope:x.scope,milestoneProgress:(w=x.scopeProgress)==null?void 0:w.milestones})}if(l.sort((x,_)=>kr(_.updatedAt)-kr(x.updatedAt)),l.length>0)return l;const d=e.filter(lu);d.sort((x,_)=>{const v=kr(x.updatedAt??x.lastEventAt??x.startedAt);return kr(_.updatedAt??_.lastEventAt??_.startedAt)-v});const u=[],h=new Set;for(const x of d){const _=x.workstreamId&&x.workstreamId.trim().length>0?`${x.initiativeId??"none"}:${x.workstreamId}`:x.runId;h.has(_)||(h.add(_),u.push(x))}return u.map(x=>{var _;return{key:`session:${x.id}`,source:"session",session:x,runId:x.runId,status:Dt(x.status??""),title:x.title,subtitle:(_=x.lastEventSummary)!=null&&_.trim()?x.lastEventSummary.trim():null,progress:x.progress,initiativeId:x.initiativeId,initiativeIds:xs(void 0,x.initiativeId),initiativeTitle:x.initiativeId?r.get(x.initiativeId)??x.groupLabel??null:x.groupLabel??null,workstreamId:x.workstreamId,workstreamIds:xs(void 0,x.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:x.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:x.updatedAt??x.lastEventAt??x.startedAt??null}})}const hu=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:h,onFocusRunId:y,onPlayWorkstream:b,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:w,onIntervene:x,onOpenSliceDetail:_}){const[v,g]=o.useState(null),[C,U]=o.useState(null),[de,ee]=o.useState(null),[pe,ie]=o.useState(null),se=o.useMemo(()=>{const I=new Map;if(!Array.isArray(s))return I;for(const T of s){const ce=xs(T.initiativeIds,T.initiativeId),ge=xs(T.workstreamIds,T.workstreamId);for(const he of ce)for(const V of ge){if(!he||!V)continue;const G=`${he}:${V}`;I.has(G)||I.set(G,T)}const J=(T.runId??T.sliceRunId??"").trim();J&&!I.has(`run:${J}`)&&I.set(`run:${J}`,T)}return I},[s]),oe=o.useMemo(()=>Ho({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),we=o.useMemo(()=>{const I=new Map;for(const T of oe){const ce=Dt(T.status);I.set(ce,(I.get(ce)??0)+1)}return Array.from(I.entries()).sort((T,ce)=>ce[1]-T[1]).map(([T,ce])=>({status:T,count:ce}))},[oe]),Ne=o.useMemo(()=>v?oe.filter(I=>Dt(I.status)===v):oe,[v,oe]),Q=o.useMemo(()=>{var ge,J;const I=new Map,T=[];for(const he of Ne){const V=(((ge=he.initiativeIds)==null?void 0:ge[0])??he.initiativeId??"").trim(),G=(((J=he.workstreamIds)==null?void 0:J[0])??he.workstreamId??"").trim();if(!V){T.push(he);continue}let le=I.get(V);le||(le={title:he.initiativeTitle??V,wsMap:new Map},I.set(V,le));const ae=G||"__none__";let ve=le.wsMap.get(ae);ve||(ve={title:he.workstreamTitle??(G||"Unassigned"),rows:[],completedCount:0,lastActivity:null},le.wsMap.set(ae,ve));const re=Dt(he.status);if(re==="completed"||re==="done"?ve.completedCount+=1:ve.rows.push(he),he.updatedAt){const Pe=Date.parse(he.updatedAt),Se=ve.lastActivity?Date.parse(ve.lastActivity):0;Number.isFinite(Pe)&&Pe>Se&&(ve.lastActivity=he.updatedAt)}}const ce=[];for(const[he,V]of I){const G=[];for(const[le,ae]of V.wsMap)G.push({workstreamId:le,workstreamTitle:ae.title,rows:ae.rows,completedCount:ae.completedCount,lastActivityAt:ae.lastActivity});G.sort((le,ae)=>{const ve=le.lastActivityAt?Date.parse(le.lastActivityAt):0;return(ae.lastActivityAt?Date.parse(ae.lastActivityAt):0)-ve}),ce.push({initiativeId:he,initiativeTitle:V.title,workstreams:G})}return ce.sort((he,V)=>{const G=Math.max(0,...he.workstreams.map(ae=>ae.lastActivityAt?Date.parse(ae.lastActivityAt):0));return Math.max(0,...V.workstreams.map(ae=>ae.lastActivityAt?Date.parse(ae.lastActivityAt):0))-G}),{groups:ce,ungrouped:T}},[Ne]),[je,Me]=o.useState(new Set),B=async(I,T,ce)=>{if(I.session){ie(null),U(I.session.id);try{await T(I.session),ie(ce)}catch(ge){const J=ge instanceof Error?ge.message:"";ie(J?Cn(J):"Workstream action failed")}finally{U(null)}}};return n.jsxs($s,{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:oe.length})]})}):null,we.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:()=>g(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${v===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:oe.length})]}),we.map(({status:I,count:T})=>n.jsxs("button",{type:"button",onClick:()=>g(ce=>ce===I?null:I),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${v===I?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[Wo(I),n.jsx("span",{className:"tabular-nums opacity-70",children:T})]},I))]}),pe&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:pe}),Ne.length===0?oe.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:oe.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(ye.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[Q.groups.map(I=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:$t(I.initiativeTitle&&!qn(I.initiativeTitle)?I.initiativeTitle:Wr(I.initiativeId,"Initiative"))}),I.workstreams.map(T=>{var re,Pe;const ce=`${I.initiativeId}:${T.workstreamId}`,ge=je.has(ce),J=T.rows[0]??null,he=J?zo((re=J.session)==null?void 0:re.agentId,(Pe=J.session)==null?void 0:Pe.agentName):null,V=J!=null&&J.milestoneProgress?J.milestoneProgress.reduce((Se,E)=>Se+E.total,0):null,G=J!=null&&J.milestoneProgress?J.milestoneProgress.reduce((Se,E)=>Se+E.done,0):null,le=V&&V>0?`Task ${(G??0)+1} of ${V}`:null,ae=V&&V>0?Math.round((G??0)/V*100):(J==null?void 0:J.progress)!=null?Uo(J.progress):null,ve=$t(J!=null&&J.workstreamTitle&&!qn(J.workstreamTitle)?J.workstreamTitle:Wr(T.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:[he&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${he.color}20`,color:he.color},children:he.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:ve,children:ve}),he?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:he.color},title:he.displayLabel,children:he.displayLabel}):null]})]}),le&&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:le}),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,ae??0)}%`,backgroundColor:(he==null?void 0:he.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:T.rows.map((Se,E)=>n.jsx(Ba,{row:Se,index:E,sliceRunByScope:se,busySessionId:C,expandedRowKey:de,setExpandedRowKey:ee,onOpenSession:h,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:w,onPlayWorkstream:b,onIntervene:x,onOpenSliceDetail:_,runWorkstreamAction:B,showInitiativeLabel:!1},Se.key))}),T.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>Me(Se=>{const E=new Set(Se);return E.has(ce)?E.delete(ce):E.add(ce),E}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:ge?`Hide ${T.completedCount} completed`:`${T.completedCount} completed`})})]},T.workstreamId)})]},I.initiativeId)),Q.ungrouped.length>0&&n.jsxs("div",{children:[Q.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:Q.ungrouped.map((I,T)=>n.jsx(Ba,{row:I,index:T,sliceRunByScope:se,busySessionId:C,expandedRowKey:de,setExpandedRowKey:ee,onOpenSession:h,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:w,onPlayWorkstream:b,onIntervene:x,onOpenSliceDetail:_,runWorkstreamAction:B,showInitiativeLabel:!0},I.key))})]})]})})]})});function Ba({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:c,onFocusRunId:l,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:h,onPlayWorkstream:y,onIntervene:b,onOpenSliceDetail:f,runWorkstreamAction:k,showInitiativeLabel:w=!0}){var T,ce,ge,J,he,V,G,le,ae,ve;const x=Dt(e.status??""),_=e.updatedAt,v=e.subtitle?e.subtitle:_?`Updated ${St(_)}`:null,g=w&&(e.initiativeTitle||e.initiativeId)?$t(e.initiativeTitle&&!qn(e.initiativeTitle)?e.initiativeTitle:Wr(e.initiativeId,"Initiative")):null,C=(T=e.title)!=null&&T.trim()?e.title:"",U=pu(C)&&((ce=e.workstreamTitle)!=null&&ce.trim())?e.workstreamTitle:C||e.workstreamTitle||"",de=Wr(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),ee=$t(U&&!qn(U)?U:de),pe=v&&!fu(v)?$t(v):null,ie=Uo(e.progress),se=["running","active","in_progress","working","planning","dispatching"].includes(x),oe=["paused","blocked","queued","pending"].includes(x),we=h??y,Ne=ie===null&&["running","active","in_progress","working","planning","dispatching"].includes(x),Q=e.session?r===e.session.id:!1,je=i===e.key,Me=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),B=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),I=zo((ge=e.session)==null?void 0:ge.agentId,(J=e.session)==null?void 0:J.agentName);return n.jsxs(ye.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:()=>f==null?void 0:f(e,B),role:"button",tabIndex:0,onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),f==null||f(e,B))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${du(x)}`,"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":I.color}:void 0,children:n.jsx(Rt,{name:((he=e.session)==null?void 0:he.agentName)??"OrgX",hint:((V=e.session)==null?void 0:V.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[g?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:g}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(Sn,{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:ee,children:ee})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(In,{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] ${cu(x)}`,children:Wo(x)}),_&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:jl(new Date(_),{addSuffix:!0})})]}),pe?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:pe,children:pe}):null,null,(ie!==null||Ne)&&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:ie===null?"Live":`${ie}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${ie===100?" shimmer-on-complete":""}`,children:ie===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,ie)}%`,background:`linear-gradient(90deg, ${$a(Fa((G=e.session)==null?void 0:G.agentId)).gradient[0]}, ${$a(Fa((le=e.session)==null?void 0:le.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(Yd,{nodes:qd({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((re,Pe)=>re+Pe.total,0),completedTasks:e.milestoneProgress.reduce((re,Pe)=>re+Pe.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ae=e.session)==null?void 0:ae.agentName)??null,agentId:((ve=e.session)==null?void 0:ve.agentId)??null}),activeId:e.workstreamId,compact:!0})}),Me?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:re=>{re.stopPropagation(),a(Pe=>Pe===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-md px-1 text-micro font-semibold text-secondary transition-colors hover:text-white",children:je?"Hide details":"Slice details"}),je?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:re=>re.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&&se&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Q,onClick:()=>void k(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&&oe&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Q,onClick:()=>void k(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&&we&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Q,onClick:()=>void k(e,we,`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:Q,onClick:()=>void k(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 gu=new Set(["awaiting_input","needs_review","failed"]);function qa(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function xu(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 Vo(e){const t=e.filter(r=>gu.has(r.status)).sort((r,i)=>qa(i.updatedAt??i.lastEventAt??"")-qa(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=xu(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function yu(e){return e==="failed"?"#FF6B88":e==="needs_review"?"#F5B700":"#BFFF00"}function bu(e){return e==="awaiting_input"?"Input":e==="needs_review"?"Review":e==="failed"?"Failed":e.replace(/_/g," ")}function wu(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} pending`}return e.status==="failed"?"Execution stopped":e.status==="needs_review"?"Output ready for review":"Needs your attention"}function Oi(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return qn(s)?`${t} ${Yn(s)}`:s}function vu(e){if(!e)return null;const t=$t(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function ku(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!qn(r)){const a=$t(r);if(a!=="Untitled session")return a}const i=vu(e.statusExplainer);return i||(s?Oi(s,"Workstream"):Oi(e.sliceRunId,"Slice"))}const ju=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:h,onAcceptSlice:y}){const b=o.useMemo(()=>Vo(t),[t]),[f,k]=o.useState(new Set),[w,x]=o.useState(new Set),[_,v]=o.useState(new Set),[g,C]=o.useState(null),U=o.useMemo(()=>b.filter(I=>!f.has(I.item.sliceRunId)),[b,f]),de=o.useMemo(()=>{const I=new Map;for(const T of s)T.id&&I.set(T.id,T.name??T.id);return I},[s]),ee=o.useMemo(()=>{const I=new Map;for(const T of s)for(const ce of T.workstreams??[])ce.id&&(I.has(ce.id)||I.set(ce.id,ce.name??ce.id));return I},[s]),pe=o.useCallback(I=>{x(T=>{const ce=new Set(T);return ce.has(I)?ce.delete(I):ce.add(I),ce})},[]),ie=o.useMemo(()=>U.length>0&&U.every(I=>w.has(I.item.sliceRunId)),[U,w]),se=o.useCallback(()=>{x(I=>ie?new Set:new Set(U.map(T=>T.item.sliceRunId)))},[ie,U]),oe=w.size,we=o.useCallback(async(I,T)=>{const ce=I.sliceRunId??I.id??"";try{C(`Accepting ${ce.slice(0,8)}…`),v(ge=>new Set(ge).add(ce));try{await(y==null?void 0:y(I,T))}catch{}k(ge=>new Set(ge).add(ce)),C(`Accepted ${ce.slice(0,8)}`)}catch(ge){C(`Failed: ${ge instanceof Error?ge.message:"network error"}`)}finally{v(ge=>{const J=new Set(ge);return J.delete(ce),J})}},[y]),Ne=o.useCallback(()=>{const I=U.filter(T=>w.has(T.item.sliceRunId)&&T.item.status==="needs_review");if(I.length!==0){C(`Accepting ${I.length} items…`);for(const T of I)we(T.item);x(new Set)}},[U,w,we]),Q=o.useCallback(I=>{var T;if(I.primaryAction==="resolve_decision"){l==null||l();return}if(I.primaryAction==="review_output"||I.primaryAction==="retry_slice"){u==null||u(I);return}if(I.primaryAction==="open_artifact"){const ce=(T=I.artifacts.find(ge=>ge.url))==null?void 0:T.url;if(ce&&typeof window<"u"){window.open(ce,"_blank","noopener,noreferrer");return}u==null||u(I);return}if(I.runId){d==null||d(I.runId);return}I.sliceRunId&&(d==null||d(I.sliceRunId))},[l,u,d]),je=o.useMemo(()=>U.filter(I=>I.item.status==="needs_review"),[U]),Me=o.useMemo(()=>je.filter(I=>w.has(I.item.sliceRunId)).length,[je,w]),B=c==="card"?$s:"div";return n.jsxs(B,{className:`flex h-full min-h-0 flex-col overflow-hidden ${i??""}`,children:[a?n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2.5",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-body font-semibold text-white/90",children:r}),n.jsx("span",{className:"rounded-full bg-white/[0.06] px-1.5 py-px text-[10px] font-medium tabular-nums text-white/40",children:U.length})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[U.length>1&&n.jsx("button",{type:"button",onClick:se,className:"rounded-md px-2 py-1 text-[11px] font-medium text-white/40 transition-colors hover:bg-white/[0.04] hover:text-white/60",children:ie?"Clear":"Select all"}),oe>0&&Me>0&&y&&n.jsx("button",{type:"button",disabled:_.size>0,onClick:Ne,className:"rounded-md bg-[#BFFF00]/10 px-2.5 py-1 text-[11px] font-semibold text-[#BFFF00] transition-colors hover:bg-[#BFFF00]/18 disabled:opacity-40 disabled:pointer-events-none",children:_.size>0?"Accepting...":`Accept ${Me}`})]})]}):null,g&&n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-white/[0.04] px-4 py-1 text-[10px] text-[#0AD4C4]/70 animate-pulse",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#0AD4C4]"}),g]}),U.length===0?n.jsx("div",{className:"px-4 py-6 text-center text-caption text-white/30",children:"Nothing needs attention right now."}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:n.jsx(pt,{mode:"popLayout",children:U.map(({item:I,duplicateCount:T},ce)=>{const ge=(Array.isArray(I.initiativeIds)&&I.initiativeIds.length>0?I.initiativeIds[0]:I.initiativeId)??null,J=(Array.isArray(I.workstreamIds)&&I.workstreamIds.length>0?I.workstreamIds[0]:I.workstreamId)??null,he=(ge?de.get(ge):null)??Oi(ge,"Initiative"),V=I.workstreamTitle??(J?ee.get(J)??null:null),G=ku(I,V,J),le=$t(wu(I)),ae=$t(he),ve=I.updatedAt??I.lastEventAt??null,re=yu(I.status),Pe=w.has(I.sliceRunId),Se=_.has(I.sliceRunId),E=I.status==="needs_review";return n.jsx(ye.article,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,x:120,scale:.97},transition:{duration:.2,delay:Math.min(ce,5)*.015,ease:[.22,1,.36,1]},className:"group relative cursor-pointer border-b border-subtle transition-colors hover:bg-white/[0.02]",style:{backgroundColor:Pe?"rgba(191,255,0,0.03)":void 0,opacity:Se?.5:void 0},role:"button",tabIndex:0,onClick:P=>{P.target.closest("button, input, [data-stop-row]")||(C("Opening detail…"),h==null||h(I))},onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),h==null||h(I))},children:n.jsxs("div",{className:"flex items-start gap-2 py-2.5 pl-2.5 pr-2.5 sm:gap-2.5 sm:pl-3 sm:pr-3",children:[n.jsx("div",{className:"flex-shrink-0 pt-0.5",children:n.jsx("input",{type:"checkbox",checked:Pe,onChange:()=>pe(I.sliceRunId),className:"h-4 w-4 rounded-sm border-white/15 bg-transparent text-[#BFFF00] focus:ring-0 focus:ring-offset-0 cursor-pointer"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:re}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium leading-tight text-white/90",children:G}),n.jsx("span",{className:"hidden sm:inline flex-shrink-0 text-[10px] tabular-nums text-white/25",children:ve?St(ve):bu(I.status)})]}),n.jsxs("div",{className:"mt-0.5 flex items-baseline gap-1 sm:gap-1.5 pl-3 sm:pl-[14px] overflow-hidden",children:[n.jsx("span",{className:"min-w-0 truncate text-[11px] leading-relaxed text-white/35",children:le}),T>1&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] text-white/20",children:["+",T-1]})]}),n.jsxs("div",{className:"mt-px flex items-center gap-1 pl-3 sm:pl-[14px] text-[10px] text-white/20 overflow-hidden",children:[n.jsx(Sn,{type:"initiative",size:8,className:"opacity-50"}),n.jsx("span",{className:"truncate",children:ae})]})]}),n.jsx("div",{className:"flex flex-shrink-0 items-center gap-1 self-center",children:E&&y?n.jsxs("button",{type:"button",disabled:Se,onClick:()=>we(I),className:"flex h-6 items-center gap-0.5 sm:gap-1 rounded-md bg-[#BFFF00]/8 px-1.5 sm:px-2 text-[11px] font-medium text-[#BFFF00]/70 transition-all hover:bg-[#BFFF00]/15 hover:text-[#BFFF00] disabled:opacity-40",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:"20 6 9 17 4 12"})}),Se?"Accepting...":"Accept"]}):n.jsx("button",{type:"button",onClick:()=>Q(I),className:"flex h-6 items-center rounded-md px-2 text-[11px] font-medium text-white/45 opacity-100 transition-all md:opacity-0 md:group-hover:opacity-100 hover:bg-white/[0.04] hover:text-white/70",children:I.status==="failed"?"Retry":"View"})})]})},I.sliceRunId)})})})]})});function Nu(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Iu(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 Au(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Su(e){return{id:e.id,name:e.title,status:Nu(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Iu(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 za=150,_u=12;function Wa(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Cu(){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 Ko(e,t=null){return ns({queryKey:Bn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if(Mt())return Cu();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<_u;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(za),offset:String(i)});r&&ss(u,r);const h=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:kt({workspaceId:r})});if(!h.ok)break;const y=await h.json(),b=y.data??[];if(s.push(...b),!!!((l=y.pagination)!=null&&l.has_more)||b.length===0)break;i+=za}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}Wa(d.updated_at??d.created_at)>Wa(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=>Au(d.status)).sort((d,u)=>{const h=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-h}).map(Su)},enabled:e,staleTime:6e4})}const jr=50,Ua=8;function Mu(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Eu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Tu(e){return{id:e.id,name:e.title,status:Mu(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,activeAgents:0,totalAgents:0,description:void 0}}function Ru(e,t=null){return ns({queryKey:Bn.liveInitiatives({limit:jr*Ua,projectId:t}),queryFn:async()=>{var c;if(Mt())return[];const s=[];let r=0;for(let l=0;l<Ua;l+=1){const d=new URLSearchParams({limit:String(jr),offset:String(r)});t&&t.trim().length>0&&ss(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:kt({workspaceId:t})});if(!u.ok)break;const h=await u.json(),y=h.initiatives??[];s.push(...y);const b=typeof h.total=="number"?h.total:null,f=(c=h.pagination)==null?void 0:c.has_more;if(!(typeof f=="boolean"?f:b!==null?r+y.length<b:y.length===jr)||y.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=>Eu(l.status)).map(Tu)},enabled:e,staleTime:3e4})}const Go=o.createContext(null);function Du({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(Go.Provider,{value:{state:t,open:r,close:i},children:e})}function Xo(){const e=o.useContext(Go);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Lu(e){const{running:t,blocked:s,decisionsCount:r,completedToday:i,onDecisionsClick:a,onBlockedClick:c,onNewInitiative:l}=e,d=r+s;return t===0&&d===0&&i===0?{key:"idle-empty",segments:[{text:"All caught up. "},l?{text:"Start something new?",color:L.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]}:t===0&&d===0?{key:"idle-done",segments:[{text:`${i} done today`,color:L.teal},{text:" · all caught up"}]}:s>0&&r>0?{key:`blocked-decisions-${s}-${r}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:`${s} blocked`,color:L.red,clickable:!0,onClick:c},{text:" · "},{text:`${r} need your input`,color:L.amber,clickable:!0,onClick:a}]}:s>0?{key:`blocked-${s}-${t}`,segments:[{text:`${s} blocked`,color:L.red,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}:r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:L.lime},{text:" · "}]:[],{text:`${r} need your input`,color:L.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:L.lime},{text:" · all systems go"}]}}function Ha(e){const{className:t}=e,{key:s,segments:r}=Lu(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(pt,{mode:"wait",children:n.jsx(ye.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 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 Zf={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"},Fu={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"},eh=e=>Fu[Dt(e)]??"text-white/60 bg-white/5 border-white/10",th=e=>{const t=Dt(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"},nh=e=>{const t=Dt(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"},sh=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),rh=e=>{const t=Dt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},ys=e=>{const t=Dt(e);return t==="blocked"||t==="failed"||t==="cancelled"?L.red:t==="active"||t==="in_progress"||t==="running"?L.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?L.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?L.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Ur={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:L.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:L.teal,tint:"rgba(20, 184, 166, 0.18)"}},$u=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Pr(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)Pr(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"?($u.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&Pr(a,t,s+1,r):typeof a=="object"&&a!==null&&Pr(a,t,s+1,r)}}}}function Pu(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 Zn(...e){const t=[],s=new Set;for(const r of e)Pr(r,t,0,s);for(const r of t){const i=Pu(r);if(i)return Ur[i]}return Ur.unknown}function Ou(e){return Ur[e]??Ur.unknown}const Bu={xs:18,sm:24,md:30};function qu({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:Zr,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 Ps({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=Ou(e),a=Bu[t];return n.jsx("span",{className:ue("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(qu,{provider:e})})})}function zu({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=zn(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const f=[];return e>0&&f.push({color:L.lime,fraction:e/c}),t>0&&f.push({color:L.red,fraction:t/c}),s>0&&f.push({color:L.amber,fraction:s/c}),f},[e,t,s,c]),d=2.5,u=(r-d)/2,h=2*Math.PI*u,y=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:y,cy:y,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:y,cy:y,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),l.map((f,k)=>{const w=f.fraction*h,x=-b;return b+=w,n.jsx(ye.circle,{cx:y,cy:y,r:u,fill:"none",stroke:f.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${w} ${h-w}`,strokeDashoffset:x,initial:a?!1:{strokeDasharray:`0 ${h}`},animate:{strokeDasharray:`${w} ${h-w}`},transition:{duration:.5,delay:k*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},k)})]}),n.jsx("div",{className:"relative z-10",children:i})]})}const Nr={initiativeId:"",workstreams:[],milestones:[],tasks:[]},Wu=(e,t)=>({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}),Uu=(e,t)=>({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}),Hu=(e,t)=>({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});function Vu(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 Ku({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var l;const i=bc(e),a=o.useMemo(()=>Bn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=ns({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Nr;if(Mt())return Vu(e);if(!i)return{...Nr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,h=async _=>{try{const v=new URLSearchParams({type:_,initiative_id:e,limit:"100"}),g=await fetch(`/orgx/api/entities?${v.toString()}`,{headers:u});return g.ok?await g.json():{data:[]}}catch{return{data:[]}}},[y,b,f]=await Promise.all([h("workstream"),h("milestone"),h("task")]),k=Array.isArray(y.data)?y.data.map(_=>Wu(_,e)):[],w=Array.isArray(b.data)?b.data.map(_=>Uu(_,e)):[],x=Array.isArray(f.data)?f.data.map(_=>Hu(_,e)):[];return{initiativeId:e,workstreams:k,milestones:w,tasks:x}}});return{details:(i?c.data:null)??(e?{...Nr,initiativeId:e}:Nr),isLoading:i?c.isLoading:!1,error:i?((l=c.error)==null?void 0:l.message)??null:null,refetch:c.refetch}}function Gu(){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 Zi({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return ns({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Mt())return Gu();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 Js(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:L.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:L.iris,bg:"rgba(124,124,255,0.10)"}}function Xu(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function Qu(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function Ju({open:e,onClose:t,onLaunched:s}){var le,ae,ve,re,Pe,Se;const r=Zi({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=Ko(e),[a,c]=o.useState(""),[l,d]=o.useState(""),[u,h]=o.useState(""),[y,b]=o.useState(""),[f,k]=o.useState("auto"),[w,x]=o.useState(""),[_,v]=o.useState(null),[g,C]=o.useState(null),[U,de]=o.useState("starter"),[ee,pe]=o.useState(!1),[ie,se]=o.useState(1),oe=Mt(),we=o.useMemo(()=>{const E=l.trim();return E?(i==null?void 0:i.find(P=>P.id===E))??null:null},[i,l]),{details:Ne}=Ku({initiativeId:we?we.id:null,enabled:e&&!!we}),Q=o.useMemo(()=>Xu(Ne),[Ne]),je=o.useMemo(()=>Qu(Ne,u||null),[Ne,u]),Me=((le=r.data)==null?void 0:le.agents)??[],B=o.useMemo(()=>{const E=a.trim();return E?Me.find(P=>P.id===E)??null:null},[Me,a]);o.useEffect(()=>{var P,K;if(!e)return;const E=((P=Me.find(te=>te.isDefault))==null?void 0:P.id)??((K=Me[0])==null?void 0:K.id)??"";!a&&E&&c(E)},[Me,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const E=i??[],P=E.length===1?E[0]:null;P&&d(P.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const E=(B==null?void 0:B.model)??"",P=E.includes("openrouter")?"openrouter":E.includes("anthropic")?"anthropic":E.includes("openai")?"openai":"auto";k(P)},[e,B==null?void 0:B.model,a]),o.useEffect(()=>{e&&(v(null),C(null),de("starter"),se(1))},[e]),o.useEffect(()=>{h(""),b("")},[l]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(w.trim().length>0||we&&x(`Kick off: ${we.name}`))},[w,e,we]);const I=!!a.trim()&&!!l.trim(),T=ie===1?!!a.trim():ie===2?!!l.trim():I,ce=async()=>{var qe;const E=(g==null?void 0:g.checkout)??"/orgx/api/billing/checkout",P=U&&U.trim().length>0?U.trim():"starter",te=await(await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:P,billingCycle:"monthly"})})).json().catch(()=>null),Re=((qe=te==null?void 0:te.data)==null?void 0:qe.url)??(te==null?void 0:te.url)??null;if(!Re)throw new Error((te==null?void 0:te.error)??"Checkout unavailable");window.open(Re,"_blank","noopener,noreferrer")},ge=async()=>{var Re;const E=(g==null?void 0:g.portal)??"/orgx/api/billing/portal",K=await(await fetch(E,{method:"POST"})).json().catch(()=>null),te=((Re=K==null?void 0:K.data)==null?void 0:Re.url)??(K==null?void 0:K.url)??null;if(!te)throw new Error((K==null?void 0:K.error)??"Billing portal unavailable");window.open(te,"_blank","noopener,noreferrer")},J=async()=>{if(!(!I||ee)){if(oe){t(),s==null||s();return}v(null),C(null),pe(!0);try{const E={agentId:a.trim(),message:w.trim()?w.trim():void 0,initiativeId:l.trim(),initiativeTitle:(we==null?void 0:we.name)??null,workstreamId:u.trim()?u.trim():null,taskId:y.trim()?y.trim():null,provider:f!=="auto"?f:null},P=new URLSearchParams;P.set("agentId",E.agentId),P.set("initiativeId",E.initiativeId),E.initiativeTitle&&P.set("initiativeTitle",E.initiativeTitle),E.workstreamId&&P.set("workstreamId",E.workstreamId),E.taskId&&P.set("taskId",E.taskId),E.message&&P.set("message",E.message),E.provider&&P.set("provider",E.provider);const K=await fetch(`/orgx/api/agents/launch?${P.toString()}`,{method:"POST"}),te=await K.json().catch(()=>null);if(!K.ok||!(te!=null&&te.ok))throw(te==null?void 0:te.code)==="upgrade_required"&&(C(te.actions??null),de(te.requiredPlan??"starter")),new Error((te==null?void 0:te.error)??`Launch failed (${K.status})`);t(),s==null||s()}catch(E){v(E instanceof Error?E.message:"Launch failed")}finally{pe(!1)}}},he=!!((ae=B==null?void 0:B.run)!=null&&ae.runId)&&!!((ve=B==null?void 0:B.run)!=null&&ve.pid),V=async()=>{var E;if(!(!((E=B==null?void 0:B.run)!=null&&E.runId)||!he||ee)&&!oe){v(null),pe(!0);try{const P=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(B.run.runId)}`,{method:"POST"}),K=await P.json().catch(()=>null);if(!P.ok||!(K!=null&&K.ok))throw new Error((K==null?void 0:K.error)??`Stop failed (${P.status})`);await r.refetch()}catch(P){v(P instanceof Error?P.message:"Stop failed")}finally{pe(!1)}}},G=async()=>{var E;if(!(!((E=B==null?void 0:B.run)!=null&&E.runId)||ee)){if(oe){t(),s==null||s();return}v(null),pe(!0);try{const P=new URLSearchParams;P.set("runId",B.run.runId),w.trim()&&P.set("message",w.trim()),f&&f!=="auto"&&P.set("provider",f);const K=await fetch(`/orgx/api/agents/restart?${P.toString()}`,{method:"POST"}),te=await K.json().catch(()=>null);if(!K.ok||!(te!=null&&te.ok))throw new Error((te==null?void 0:te.error)??`Restart failed (${K.status})`);t(),s==null||s()}catch(P){v(P instanceof Error?P.message:"Restart failed")}finally{pe(!1)}}};return e?n.jsx(ei,{open:e,onClose:t,maxWidth:"max-w-2xl",children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"border-b border-subtle px-5 py-4 sm:px-6",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:"Launch OpenClaw Agent"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:"Starts a background agent turn and scopes the resulting sessions/activity to the selected OrgX initiative."}),n.jsx("div",{className:"mt-3 inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.03] p-1 text-micro uppercase tracking-[0.12em] text-secondary",children:[[1,"Agent"],[2,"Scope"],[3,"Message"]].map(([E,P])=>n.jsxs("button",{type:"button",onClick:()=>se(E),className:ue("rounded-full px-3 py-1 transition-colors",ie===E?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[E,". ",P]},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(pt,{mode:"wait",children:n.jsxs(ye.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:[ie===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:Me.map(E=>{const P=Js(E.status);return n.jsxs("option",{value:E.id,children:[E.name," (",E.id,") · ",P.label]},E.id)})})]}),B&&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:B.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${Js(B.status).color}55`,color:Js(B.status).color,backgroundColor:Js(B.status).bg},children:Js(B.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:"})," ",B.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",B.workspace??"unknown"]}),((re=B.context)==null?void 0:re.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",B.context.initiativeTitle??B.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:f,onChange:E=>k(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."})]}),B.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",B.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",B.run.status,")"]})]}),B.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:V,disabled:!he||ee,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:G,disabled:ee,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"})]})]})]})]}),ie===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=>h(E.target.value),disabled:!we,className:ue("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",!we&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),Q.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:y,onChange:E=>b(E.target.value),disabled:!we,className:ue("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",!we&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),je.slice(0,80).map(E=>n.jsx("option",{value:E.id,children:E.title},E.id))]}),je.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),ie===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:w,onChange:E=>x(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:((B==null?void 0:B.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:((we==null?void 0:we.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()?((Pe=Q.find(E=>E.id===u))==null?void 0:Pe.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:y.trim()?((Se=je.find(E=>E.id===y))==null?void 0:Se.title)??y:"Any"})]})]})]})]})]},ie)}),_&&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:_}),g&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void ce().catch(E=>v(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 ge().catch(E=>v(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"}),g.pricing&&n.jsx("a",{href:g.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:ie===1?"Pick an agent to configure.":ie===2?"Select an initiative scope (required).":I?"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:[ie>1&&n.jsx("button",{type:"button",onClick:()=>se(E=>E>1?E-1:E),disabled:ee,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"}),ie<3?n.jsx("button",{type:"button",onClick:()=>se(E=>E<3?E+1:E),disabled:!T||ee,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",T&&!ee?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:T&&!ee?{backgroundColor:L.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:J,disabled:!I||ee,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",I&&!ee?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:I&&!ee?{backgroundColor:L.lime}:void 0,children:ee?"Launching…":"Launch"})]})]})]})}):null}const gi=10,Yu=20;function Zu(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:L.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:L.iris,bg:"rgba(124,124,255,0.10)"}}function em(e){return e?e.includes("error")||e.includes("fail")?L.red:e.includes("decision")||e.includes("block")?L.amber:e.includes("complete")||e.includes("success")?L.teal:e.includes("start")||e.includes("launch")?L.lime:L.iris:L.iris}function tm({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var pe,ie,se,oe,we,Ne;const[d,u]=o.useState(!1),[h,y]=o.useState(!1),[b,f]=o.useState(null),k=$o(s),w=Zu((r==null?void 0:r.status)??null),x=o.useMemo(()=>{let Q=0,je=0,Me=0,B=0;for(const I of i)I.status==="running"||I.status==="queued"||I.status==="pending"?Q++:I.status==="blocked"?je++:I.status==="failed"||I.status==="cancelled"?Me++:(I.status==="completed"||I.status==="archived")&&B++;return{running:Q,blocked:je,failed:Me,completed:B}},[i]),_=o.useMemo(()=>[...i].sort((Q,je)=>Date.parse(je.updatedAt??je.lastEventAt??je.startedAt??"")-Date.parse(Q.updatedAt??Q.lastEventAt??Q.startedAt??"")),[i]),v=d?_:_.slice(0,gi),g=_.length>gi,C=o.useMemo(()=>[...a].sort((Q,je)=>Date.parse(je.timestamp)-Date.parse(Q.timestamp)).slice(0,Yu),[a]),U=!!((pe=r==null?void 0:r.run)!=null&&pe.runId)&&!!((ie=r==null?void 0:r.run)!=null&&ie.pid),de=async()=>{var Q;if(!(!((Q=r==null?void 0:r.run)!=null&&Q.runId)||!U||h)){f(null),y(!0);try{const je=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),Me=await je.json().catch(()=>null);if(!je.ok||!(Me!=null&&Me.ok))throw new Error((Me==null?void 0:Me.error)??`Stop failed (${je.status})`);l==null||l()}catch(je){f(je instanceof Error?je.message:"Stop failed")}finally{y(!1)}}},ee=async()=>{var Q;if(!(!((Q=r==null?void 0:r.run)!=null&&Q.runId)||h)){f(null),y(!0);try{const je=new URLSearchParams;je.set("runId",r.run.runId);const Me=await fetch(`/orgx/api/agents/restart?${je.toString()}`,{method:"POST"}),B=await Me.json().catch(()=>null);if(!Me.ok||!(B!=null&&B.ok))throw new Error((B==null?void 0:B.error)??`Restart failed (${Me.status})`);l==null||l()}catch(je){f(je instanceof Error?je.message:"Restart failed")}finally{y(!1)}}};return e?n.jsx(ei,{open:e,onClose:t,maxWidth:"max-w-3xl",children:n.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 px-8 pt-6 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0 text-[13px] text-secondary",children:[n.jsx("span",{children:"Agents"}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"flex-shrink-0 opacity-40",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),n.jsx("span",{className:"truncate text-white font-medium",children:s})]}),n.jsx("button",{type:"button",onClick:t,"aria-label":"Close detail",className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full text-muted transition-colors hover:bg-white/[0.06] hover:text-white focus:outline-none",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.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-8 py-6 space-y-8",children:[n.jsxs("div",{className:"flex items-start gap-5",children:[n.jsx(Rt,{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:"rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest",style:{color:w.color,backgroundColor:w.bg},children:w.label})]}),k&&n.jsx("p",{className:"text-[15px] text-secondary mt-2",children:k})]})]}),n.jsx("div",{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",children:[{label:"Running",value:x.running,color:L.lime},{label:"Blocked",value:x.blocked,color:L.red},{label:"Failed",value:x.failed,color:L.amber},{label:"Completed",value:x.completed,color:L.teal}].map(Q=>n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:Q.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:Q.value>0?Q.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:Q.value})]},Q.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted 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:[v.map(Q=>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:ys(Q.status)}}),n.jsxs("button",{onClick:()=>{c(Q.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:Q.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:St(Q.updatedAt??Q.lastEventAt??Q.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:Q.status}),Q.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(Q.progress),"%"]})]})]})]})]},Q.id)),g&&n.jsx("button",{type:"button",onClick:()=>u(Q=>!Q),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${_.length-gi} older sessions`})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Live Activity"}),C.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:C.map((Q,je)=>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:em(Q.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:Q.title??Q.summary??Q.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:St(Q.timestamp)})]})]},Q.id??je))})]})]}),(r==null?void 0:r.run)&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Controls"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[n.jsxs("p",{className:"text-[13px] text-secondary",children:[n.jsx("span",{className:"text-muted mr-2",children:"Tracked run:"}),r.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-2",children:["(",r.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[n.jsx("button",{type:"button",onClick:de,disabled:!U||h,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-rose-400 transition-colors hover:text-rose-300 hover:bg-rose-400/10 disabled:opacity-40 focus:outline-none",children:h?"Stopping…":"Stop Run"}),n.jsx("button",{type:"button",onClick:ee,disabled:h,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-white bg-white/[0.06] transition-colors hover:bg-white/[0.12] disabled:opacity-40 focus:outline-none",children:h?"Restarting…":"Restart"})]}),b&&n.jsx("p",{className:"w-full text-caption text-rose-400",children:b})]})]}),r&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Settings"}),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-[11px] text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(se=r.model)!=null&&se.includes("openrouter")?"OpenRouter":(oe=r.model)!=null&&oe.includes("anthropic")?"Anthropic":(we=r.model)!=null&&we.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Model"}),n.jsx("p",{className:ue("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-[11px] text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.workspace})]}),((Ne=r.context)==null?void 0:Ne.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.context.initiativeTitle})]})]})]})]})]})}):null}const Ir=120,Va=10,nm=24,Ka=520,sm=58,rm=56,im=20,am=8,ea=new Set(["running","active","in_progress","working","planning","handoff","review"]),om=new Set(["blocked","failed"]),lm=10,cm=[{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"}],dm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bi=[{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 rt(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function gn(e,t){const s=rt(e),r=rt(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of Bi)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function um(e){const t=gn(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=gn(null,r);if(i)return i}return null}function mm(e){const t=rt(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 Qo(e){const t=um(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=rt(e.agentId),r=rt(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=mm(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 pm(e){const t=Qo(e),s=rt(t.agentId);if(s)return`id:${s}`;const r=rt(t.agentName);return r?`name:${r}`:"unassigned"}function fm(e){const t=e.trim();return t?dm.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function Hr(e){const t=(e??"").trim();return t?js(t):!1}function hm(e){var t,s;return!!(Hr((t=e.context)==null?void 0:t.initiativeId)||Hr(((s=e.run)==null?void 0:s.initiativeId)??null))}function xi(e){if(gn(e.agentId,e.agentName))return!0;const s=rt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function sn(e){const t=rt(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=rt(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=rt(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":ea.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function qi(e){const t=rt(e);return t?ea.has(t)||om.has(t):!1}function Ga(e){const t=rt(e);return t?ea.has(t):!1}function Ar(e){return e?!!(qi(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function gm(e){return e?e.state==="active":!1}function xm(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function An(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function yi(e,t){return An(t.updatedAt??t.lastEventAt??t.startedAt)-An(e.updatedAt??e.lastEventAt??e.startedAt)}function ym({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=ys(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(ye.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(pt,{children:i&&n.jsx(ye.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 h=r===d.id,y=Zn(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(ye.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:ue("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",h?"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(Ps,{provider:y.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:St(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const bm=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:c,agentFilter:l,onReconnect:d,onLaunched:u,connectionStatus:h,runtimeInstances:y=[],showSyntheticEntities:b=!1}){var M;const[f,k]=o.useState(new Set),[w,x]=o.useState(!1),[_,v]=o.useState(!1),[g,C]=o.useState(0),[U,de]=o.useState(null),ee=Zi({enabled:!0}),pe=((M=ee.data)==null?void 0:M.agents)??[],ie=o.useMemo(()=>cr(a),[a]),se=o.useMemo(()=>ie===null?s:s.filter(q=>An(q.timestamp)>=ie),[s,ie]);o.useMemo(()=>{var me,Te,et;const q=new Map,ne=[...se].sort((tt,Ce)=>An(Ce.timestamp)-An(tt.timestamp));for(const tt of ne){const Ce=tt.runId;if(!Ce||q.has(Ce))continue;const Ye=((me=tt.summary)==null?void 0:me.trim())??((Te=tt.description)==null?void 0:Te.trim())??((et=tt.title)==null?void 0:et.trim())??"";Ye.length>0&&q.set(Ce,Ye)}return q},[se]);const{agents:oe,hiddenGroupCount:we,filteredOutGroupsByDate:Ne,filteredOutSessionsByDate:Q,visibleSessionCount:je,archivedGroups:Me,sessionCountInScope:B}=o.useMemo(()=>{var $e;const q=b?t.nodes:t.nodes.filter(z=>!Hr(z.initiativeId)),ne=b?pe:pe.filter(z=>!hm(z)),me=b?y:y.filter(z=>!Hr(z.initiativeId)),Te=new Map,et=new Map,tt=[...me].sort((z,Y)=>An(Y.lastEventAt??Y.lastHeartbeatAt)-An(z.lastEventAt??z.lastHeartbeatAt));for(const z of tt){z.runId&&!Te.has(z.runId)&&Te.set(z.runId,z);const Y=gn(z.agentId,z.agentName??z.displayName),Ae=rt((Y==null?void 0:Y.agentId)??z.agentId);if(Ae){const De=et.get(Ae)??[];De.push(z),et.set(Ae,De)}}const Ce=new Map;for(const z of q){const Y=Qo(z),Ae=pm(z),De=rt(Y.agentId),Le=rt(Y.agentName);let Oe=Ce.get(Ae)??null;if(!Oe&&De&&Le){const _e=`name:${Le}`,He=Ce.get(_e);He&&(Ce.delete(_e),He.groupKey=Ae,Ce.set(Ae,He),Oe=He)}if(!Oe&&Le){const _e=Array.from(Ce.values()).find(He=>rt(He.agentName)===Le);_e&&(Oe=_e)}Oe?(Oe.nodes.push(z),!Oe.agentId&&Y.agentId&&(Oe.agentId=Y.agentId),(Oe.agentName==="OrgX"||!Oe.agentName)&&Y.agentName&&(Oe.agentName=Y.agentName)):Ce.set(Ae,{groupKey:Ae,agentId:Y.agentId,agentName:Y.agentName??Y.agentId??"OrgX",nodes:[z],latest:z,runtime:null,runtimeActiveCount:0})}for(const z of ne){const Y=gn(z.id,z.name),Ae=(Y==null?void 0:Y.agentId)??z.id,De=(Y==null?void 0:Y.agentName)??z.name,Le=rt(Ae),Oe=rt(De),_e=Le?`id:${Le}`:null,He=Oe?`name:${Oe}`:null;let st=null;if(_e&&Ce.has(_e))st=_e;else if(He&&Ce.has(He))st=He;else{const Ve=Array.from(Ce.entries()).find(([,Et])=>Le&&rt(Et.agentId)===Le||Oe&&rt(Et.agentName)===Oe);st=(Ve==null?void 0:Ve[0])??null}if(st){const Ve=Ce.get(st);Ve.catalogAgent=z,!Ve.agentId&&Ae&&(Ve.agentId=Ae),(Ve.agentName==="OrgX"||!Ve.agentName)&&De&&(Ve.agentName=De),_e&&Ve.groupKey!==_e&&!Ce.has(_e)&&(Ce.delete(Ve.groupKey),Ve.groupKey=_e,Ce.set(_e,Ve))}else{const Ve=_e??He??`catalog:${De.toLowerCase()}`;Ce.set(Ve,{groupKey:Ve,agentId:Ae,agentName:De,nodes:[],latest:null,catalogAgent:z,runtime:null,runtimeActiveCount:0})}}for(const z of Bi){const Y=`orgx:${z.id}`,Ae=`id:${Y}`;let De=Ce.get(Ae)??null;if(!De){const Le=Array.from(Ce.entries()).find(([,Oe])=>{const _e=gn(Oe.agentId,Oe.agentName);return rt(_e==null?void 0:_e.agentId)===rt(Y)});Le&&(Ce.delete(Le[0]),De=Le[1],De.groupKey=Ae,Ce.set(Ae,De))}if(De||(De={groupKey:Ae,agentId:Y,agentName:z.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Ce.set(Ae,De)),De.agentId=Y,De.agentName=z.name,!De.catalogAgent){const Le=ne.find(Oe=>{const _e=gn(Oe.id,Oe.name);return rt(_e==null?void 0:_e.agentId)===rt(Y)});Le&&(De.catalogAgent=Le)}}const Ye=new Map(Bi.map((z,Y)=>[rt(`orgx:${z.id}`),Y]));for(const z of Ce.values()){z.nodes.length>0&&(z.nodes.sort(yi),z.latest=z.nodes[0]);const Y=[],Ae=new Set;if(($e=z.latest)!=null&&$e.runId){const Le=Te.get(z.latest.runId);Le&&!Ae.has(Le.id)&&(Y.push(Le),Ae.add(Le.id))}for(const Le of z.nodes){if(!Le.runId)continue;const Oe=Te.get(Le.runId);Oe&&!Ae.has(Oe.id)&&(Y.push(Oe),Ae.add(Oe.id))}const De=rt(z.agentId);if(De)for(const Le of et.get(De)??[])Ae.has(Le.id)||(Y.push(Le),Ae.add(Le.id));Y.sort((Le,Oe)=>An(Oe.lastEventAt??Oe.lastHeartbeatAt)-An(Le.lastEventAt??Le.lastHeartbeatAt)),z.runtime=Y[0]??null,z.runtimeActiveCount=Y.filter(Le=>gm(Le)).length}const ze=Array.from(Ce.values()).sort((z,Y)=>{const Ae=xi(z),De=xi(Y);if(Ae!==De)return Ae?-1:1;if(Ae&&De){const Le=gn(z.agentId,z.agentName),Oe=gn(Y.agentId,Y.agentName),_e=Ye.get(rt((Le==null?void 0:Le.agentId)??z.agentId))??999,He=Ye.get(rt((Oe==null?void 0:Oe.agentId)??Y.agentId))??999;if(_e!==He)return _e-He}return z.latest&&Y.latest?yi(z.latest,Y.latest):z.latest&&!Y.latest?-1:!z.latest&&Y.latest?1:z.agentName.localeCompare(Y.agentName)}),dt=To(a),at=dt.id==="live",nt=dt.minutes===null||at?null:Date.now()-dt.minutes*6e4,xe=[],Xe=[];let ke=0,W=0;for(const z of ze){const Y=(z.runtimeActiveCount??0)>0,Ae=xi(z);if(z.nodes.length===0){const _e=Ar(z.catalogAgent);(Ae||at&&(_e||Y))&&xe.push(z);continue}if(at){const _e=z.nodes.filter(Ve=>qi(sn(Ve))),He=z.nodes.filter(Ve=>!qi(sn(Ve))),st=Ar(z.catalogAgent);if(_e.length===0){Ae||st||Y?xe.push({...z,nodes:[],latest:null}):(ke+=1,W+=z.nodes.length,Xe.push(z));continue}W+=He.length,He.length>0&&Xe.push({...z,nodes:He,latest:He[0]??null}),xe.push({...z,nodes:_e,latest:_e[0]??null});continue}if(nt===null){xe.push(z);continue}const De=z.nodes.filter(_e=>Ga(sn(_e))?!0:An(_e.updatedAt??_e.lastEventAt??_e.startedAt)>=nt),Le=Ar(z.catalogAgent);if(De.length===0){Ae||Le||Y?xe.push({...z,nodes:[],latest:null}):(ke+=1,W+=z.nodes.length,Xe.push(z));continue}const Oe=z.nodes.filter(_e=>Ga(sn(_e))?!1:An(_e.updatedAt??_e.lastEventAt??_e.startedAt)<nt);W+=Oe.length,Oe.length>0&&Xe.push({...z,nodes:Oe,latest:Oe[0]}),xe.push({...z,nodes:De,latest:De[0]})}return{agents:xe.slice(0,Ir),hiddenGroupCount:Math.max(0,xe.length-Ir),filteredOutGroupsByDate:ke,filteredOutSessionsByDate:W,visibleSessionCount:xe.slice(0,Ir).reduce((z,Y)=>z+Y.nodes.length,0),archivedGroups:Xe,sessionCountInScope:q.length}},[a,t.nodes,pe,y,b]);o.useEffect(()=>{v(!1),C(0)},[a]);const I=o.useMemo(()=>Me.reduce((q,ne)=>q+ne.nodes.length,0),[Me]),T=o.useMemo(()=>oe.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[oe]),ce=o.useMemo(()=>{if(T.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const ne of T)f.has(ne)&&(q+=1);return{allCollapsed:q===T.length,allExpanded:q===0}},[f,T]),ge=o.useMemo(()=>{const q=[];for(const ne of Me)for(const me of ne.nodes)q.push({node:me,agentName:ne.agentName});return q.sort((ne,me)=>yi(ne.node,me.node)),q.slice(0,(g+1)*lm)},[Me,g]),J=q=>{k(ne=>{const me=new Set(ne);return me.has(q)?me.delete(q):me.add(q),me})},he=()=>{k(()=>ce.allCollapsed?new Set:new Set(T))},V=o.useMemo(()=>U?oe.find(q=>q.groupKey===U)??null:null,[oe,U]),G=o.useMemo(()=>(V==null?void 0:V.nodes)??[],[V]),le=o.useMemo(()=>{if(!V)return[];const q=rt(V.agentName),ne=rt(V.agentId),me=gn(V.agentId,V.agentName);return se.filter(Te=>{const et=rt(Te.agentName),tt=rt(Te.agentId),Ce=gn(Te.agentId,Te.agentName);return q!==null&&et===q||ne!==null&&tt===ne||me!==null&&Ce!==null&&rt(me.agentId)===rt(Ce.agentId)})},[se,V]),ae=B===0,ve=pe.length>0,re=o.useRef(null),[Pe,Se]=o.useState(0),[E,P]=o.useState(0),K=o.useCallback(q=>{const ne=q.currentTarget.scrollTop;Se(me=>Math.abs(me-ne)<1?me:ne)},[]);o.useEffect(()=>{const q=re.current;if(!q)return;const ne=()=>{const me=q.clientHeight,Te=q.scrollTop;P(et=>et===me?et:me),Se(et=>Math.abs(et-Te)<1?et:Te)};if(ne(),typeof ResizeObserver<"u"){const me=new ResizeObserver(()=>ne());return me.observe(q),()=>me.disconnect()}return window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[oe.length]);const{visibleAgentGroups:te,topVirtualSpacerPx:Re,bottomVirtualSpacerPx:qe,virtualizationEnabled:Ee}=o.useMemo(()=>{if(!(oe.length>nm&&E>0))return{visibleAgentGroups:oe,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const ne=oe.map(ze=>{const at=f.has(ze.groupKey)?0:Math.min(ze.nodes.length,Va);let nt=sm;return at>0&&(nt+=im+at*rm,ze.nodes.length>at&&(nt+=20)),nt+am}),me=new Array(ne.length+1).fill(0);for(let ze=0;ze<ne.length;ze+=1)me[ze+1]=me[ze]+ne[ze];const Te=me[me.length-1],et=Math.max(0,Pe-Ka),tt=Pe+E+Ka;let Ce=0;for(;Ce<oe.length&&me[Ce+1]<et;)Ce+=1;let Ye=Ce;for(;Ye<oe.length&&me[Ye]<tt;)Ye+=1;return Ye<=Ce&&(Ye=Math.min(oe.length,Ce+1)),{visibleAgentGroups:oe.slice(Ce,Ye),topVirtualSpacerPx:me[Ce],bottomVirtualSpacerPx:Math.max(0,Te-me[Ye]),virtualizationEnabled:!0}},[oe,f,Pe,E]);return n.jsxs($s,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(Ju,{open:w,onClose:()=>x(!1),onLaunched:()=>{ee.refetch(),u==null||u()}}),n.jsx(tm,{open:U!==null,onClose:()=>de(null),agentName:(V==null?void 0:V.agentName)??"",catalogAgent:(V==null?void 0:V.catalogAgent)??null,sessions:G,activity:le,onSelectSession:i,onRefresh:()=>ee.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[je," of ",B]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:he,disabled:T.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:ce.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:ce.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>x(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:re,onScroll:K,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[oe.length===0&&!ae&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-body text-secondary",children:"No sessions match the selected activity window."})]}),oe.length===0&&ae&&!d&&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 active chats yet. Start a session to see agents 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:[Ee&&Re>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Re}}),te.map(q=>{var _e;const ne=q.groupKey,me=f.has(ne),Te=q.latest,et=Te?sn(Te):null,tt=q.nodes.length>0,Ce=q.nodes.length===1,Ye=Ar(q.catalogAgent),ze=q.runtime??null,dt=(q.runtimeActiveCount??0)>0,at=!tt&&dt&&ze!==null,nt=tt||at,xe=Te?r===Te.id:!1,Xe=q.agentName||((_e=q.catalogAgent)==null?void 0:_e.name)||q.agentId||"OrgX",ke=gn(q.agentId,Xe),W=(ke==null?void 0:ke.agentName)??fm(Xe),$e=(ke==null?void 0:ke.role)??$o(W),z=Zn(q.agentId,W,ze==null?void 0:ze.displayName,Te==null?void 0:Te.runtimeProvider,Te==null?void 0:Te.runtimeClient),Y=ke===null&&(z.id==="codex"||z.id==="openai"||z.id==="anthropic"||z.id==="openclaw"),Ae=$e?`${Xe} — ${$e}`:Xe,De=me?[]:tt?q.nodes.slice(0,Va):[],Le=Math.max(0,tt?q.nodes.length-De.length:0),Oe=rt(l)===rt(W)||rt(l)===rt(Ae);return n.jsxs(ye.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:ue("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",xe&&"border-white/20 bg-white/[0.05]",Oe&&"border-[#0AD4C4]/30",!tt&&!Ye&&!dt&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Ce?i(q.nodes[0].id):at?J(ne):!tt&&Ye?de(ne):c?c(Oe?null:W):Te&&i(Te.id)},className:"flex flex-1 items-start gap-2.5 rounded-lg px-1 py-0.5 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[Y?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(Ps,{provider:z.id,size:"sm",showRing:!1})}):n.jsx(zu,{running:q.nodes.filter(He=>{const st=sn(He);return st==="running"||st==="handoff"||st==="review"}).length,blocked:q.nodes.filter(He=>{const st=sn(He);return st==="blocked"||st==="failed"}).length,paused:q.nodes.filter(He=>{const st=sn(He);return st==="paused"||st==="cancelled"}).length,size:36,children:n.jsx(Rt,{name:W,size:"sm",hint:`${q.agentId??""} ${W}`})}),ke&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})}),Te&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:ys(et??Te.status),borderColor:L.cardBg}}),!Te&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ye?ys("running"):"rgba(255,255,255,0.2)",borderColor:L.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:$e?`${Xe} — ${$e}`:Xe,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[W,$e&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",$e]})]})}),n.jsx("div",{className:"flex items-center gap-1.5",children:tt?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const He={};for(const st of q.nodes){const Ve=sn(st);He[Ve]=(He[Ve]??0)+1}return Object.entries(He).map(([st,Ve])=>`${Ve} ${st}`).join(" · ")})(),children:(()=>{const He={};for(const Ve of q.nodes){const Et=sn(Ve);He[Et]=(He[Et]??0)+1}const st=q.nodes.length;return Object.entries(He).map(([Ve,Et])=>n.jsx("span",{style:{width:`${Et/st*100}%`,backgroundColor:ys(Ve)}},Ve))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:q.nodes.length})]}):Ye||dt?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:ys("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,q.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:()=>de(ne),"aria-label":`View ${W} 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:()=>{nt&&J(ne)},disabled:!nt,"aria-label":nt?me?"Expand sessions":"Collapse sessions":"No sessions to expand",className:ue("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",nt?"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:ue("transition-transform",nt&&!me?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(pt,{initial:!1,children:nt&&!me&&n.jsx(ye.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 He=new Map,st=[];for(const Je of De){const jt=sn(Je);if(jt==="blocked"||jt==="paused"||jt==="failed"){const Ut=`${jt}:${Je.blockerReason??""}`,Bt=He.get(Ut)??[];Bt.push(Je),He.set(Ut,Bt)}else st.push(Je)}const Ve=[];for(const[Je,jt]of He)jt.length>3?Ve.push({status:Je.split(":")[0],nodes:jt}):st.push(...jt);const Et=(Je,jt)=>{const Ut=r===Je.id,Bt=sn(Je),yn=Zn(Je.agentName,Je.title,Je.lastEventSummary,Je);return n.jsx(ye.button,{onClick:()=>i(Je.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(jt*.015,.12)},className:ue("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Ut?"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(Ps,{provider:yn.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Je.title,children:Je.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:yn.accent},children:yn.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Bt}),n.jsx("span",{title:qr(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now()),children:St(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now())})]}),Je.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(Je.progress)}%`,background:`linear-gradient(90deg, ${L.lime}, ${L.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:ys(Bt)},"aria-label":Bt,title:Bt})]})},Je.id)};return n.jsxs(n.Fragment,{children:[st.map((Je,jt)=>Et(Je,jt)),Ve.map(Je=>n.jsx(ym,{status:Je.status,nodes:Je.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Je.status}-${Je.nodes.length}`))]})})(),Le>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",Le," older sessions hidden"]})]})})})]},ne)}),Ee&&qe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:qe}})]}),we>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Ir," most recent agent groups (",we," older groups omitted)."]}),d&&h!=="connected"&&!ve&&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:cm.map(q=>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:q.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:q.name}),n.jsx("p",{className:"text-micro text-muted",children:q.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"})]},q.id))})]}),Q>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{v(q=>!q),_&&C(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:ue("transition-transform",_?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[I," archived session",I===1?"":"s",Ne>0?` across ${Ne} agent${Ne===1?"":"s"}`:""]})]}),n.jsx(pt,{initial:!1,children:_&&n.jsx(ye.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[ge.map(({node:q,agentName:ne})=>{const me=sn(q),Te=q.runtimeProvider?{id:xm(q.runtimeProvider)}:Zn(q.agentName,q.title,q.lastEventSummary,q);return n.jsxs("button",{onClick:()=>i(q.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(Ps,{provider:Te.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"truncate text-caption font-medium text-primary",children:ne}),n.jsx("span",{className:"text-micro text-muted",title:qr(q.updatedAt??q.lastEventAt??q.startedAt??Date.now()),children:St(q.updatedAt??q.lastEventAt??q.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:q.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:me})]})]},q.id)}),ge.length<I&&n.jsxs("button",{onClick:()=>C(q=>q+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 (",I-ge.length," remaining)"]})]})})})]})]})]})}),wm=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),vm=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),km=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),jm=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Nm=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function Ts(e){return e?Dt(e):""}function bi(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Im(e){return e.some(t=>wm.has(t))}function Am(e){return e.some(t=>vm.has(t))}function Sm(e){return e.some(t=>km.has(t))}function _m(e){return e.some(t=>jm.has(t))}function Cm(e){return e.some(t=>Nm.has(t))}function $n(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 Mm(e){const t=Ts(e.sessionStatus),s=Ts(e.sessionPhase),r=Ts(e.sessionState),i=Ts(e.sliceStatus),a=Ts(e.activityStatus),c=Ts(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(C=>C.length>0),u=bi(e.blockingDecisionCount),h=bi(e.nonBlockingDecisionCount),y=bi(e.blockerCount),b=l==="run_failed",f=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",k=b||Im(d),w=Am(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,x=Sm(d)||y>0,_=f||_m(d),v=Cm(d)||l==="run_started";if(k)return $n("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(_&&!w&&!k&&y===0&&!e.blockerReason)return h>0?$n("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):$n("completed","Execution completed successfully.",{tone:"positive"});if(w||x)return u>0||e.decisionRequired===!0||l==="decision_requested"?$n("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):$n("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:x?"critical":"warning"});if(_)return h>0?$n("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):$n("completed","Execution completed successfully.",{tone:"positive"});if(v){const C=h>0?`Running with ${h} optional decision${h===1?"":"s"} available.`:"Running.";return $n("in_progress",C,{tone:"neutral"})}return $n("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const wi=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Em(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function bs(e,t){const s=[];let r=0,i=0;wi.lastIndex=0;for(let a=wi.exec(e);a;a=wi.exec(e)){const[c]=a,l=a.index;l>r&&s.push(e.slice(r,l));const d=`${t}-${i++}`,u=a[1],h=a[2],y=a[3],b=a[4],f=a[5],k=a[6],w=a[7];u&&h&&Em(h)?s.push(n.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):y?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:y},d)):b||f?s.push(n.jsx("strong",{className:"font-semibold text-white",children:b??f},d)):k||w?s.push(n.jsx("em",{className:"italic text-bright",children:k??w},d)):s.push(c),r=l+c.length}return r<e.length&&s.push(e.slice(r)),s}function Tm(e,t){const s=e.split(`
204
- `),r=[];return s.forEach((i,a)=>{r.push(...bs(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function Or(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Rm(e){const t=Or(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Dm(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function Lm(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("|")&&Rm(l)){const b=Or(i),k=Or(l).map(x=>Dm(x));r+=2;const w=[];for(;r<t.length;){const x=t[r]??"";if(!x.trim()||!x.includes("|"))break;w.push(Or(x)),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((x,_)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:k[_]??"left"},children:bs(x,`tbl-h-${r}-${_}`)},`tbl-h-${_}`))})}),n.jsx("tbody",{children:w.map((x,_)=>n.jsx("tr",{className:_<w.length-1?"border-b border-subtle":void 0,children:b.map((v,g)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:k[g]??"left"},children:bs(x[g]??"",`tbl-r-${r}-${_}-${g}`)},`tbl-r-${_}-c-${g}`))},`tbl-r-${_}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const b=a.slice(3).trim(),f=[];for(r+=1;r<t.length&&!(t[r]??"").trim().startsWith("```");)f.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:f.join(`
207
- `)})})]},`code-${r}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const b=d[1].length,f=d[2],k=b===1?"text-title font-semibold":b===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:ue("tracking-[-0.01em] text-white",k),children:bs(f,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const b=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!k)break;b.push(k[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:b.map((f,k)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:bs(f,`ul-${r}-${k}`)},`ul-${r}-${k}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const b=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!k)break;b.push(k[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:b.map((f,k)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:bs(f,`ol-${r}-${k}`)},`ol-${r}-${k}`))},`ol-${r}`));continue}const y=[];for(;r<t.length;){const b=t[r]??"",f=b.trim();if(!f||/^(#{1,3})\s+/.test(f)||/^\s*[-*]\s+/.test(b)||/^\s*\d+\.\s+/.test(b)||f.startsWith("```"))break;y.push(b),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Tm(y.join(`
208
- `),`p-${r}`)},`p-${r}`))}return s}function Vr({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:bs(r,"inline")}):n.jsx("div",{className:ue("space-y-2",s),children:Lm(r)}):null}function Jo(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Fm(e){if(!e)return;const t=Jo(e.metadata);return t?{...e,...t}:e}const Yo={run_started:{icon:"play",label:"Run started",color:L.teal},run_completed:{icon:"check_circle",label:"Run completed",color:L.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:L.red},artifact_created:{icon:"file",label:"Artifact",color:L.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:L.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:L.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:L.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:L.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:L.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:L.red},milestone_completed:{icon:"flag",label:"Milestone",color:L.cyan},delegation:{icon:"workflow",label:"Delegation",color:L.iris}};function Ln(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 zi(e){return e?e.toLowerCase():""}function $m(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Ln(t,["source","event","eventType","artifact_type","action","kind"]),Ln(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function Pm(e,t){const s=zi(Ln(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:L.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:L.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:L.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:L.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:L.cyan}:Yo.artifact_created}function Om(e){const t=Fm(Jo(e.metadata)),s=$m(e,t),r=zi(Ln(t,["source"])),i=zi(Ln(t,["action"])),a=Ln(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"&&Ln(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:L.teal};if(a==="auto_continue_stopped"){const l=Ln(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Autopilot blocked",color:L.red}:l==="budget_exhausted"?{icon:"infinity",label:"Budget exhausted",color:L.amber}:{icon:"infinity",label:"Autopilot stopped",color:L.amber}}if(a==="autopilot_transition"){const l=Ln(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Autopilot blocked",color:L.red}:{icon:"infinity",label:"Autopilot transition",color:L.teal}}const c=Ln(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Slice completed",color:L.lime}:{icon:"infinity",label:"Autopilot slice",color:L.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:L.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:L.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:L.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:L.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:L.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:L.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:L.teal};if(e.type==="artifact_created")return Pm(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:L.red}:{icon:"shield_check",label:"Decision approved",color:L.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Dispatch",color:L.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:L.teal}}return Yo[e.type]??{icon:"message",label:"Activity",color:L.textMuted}}function Bm({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(Po,{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 Kr(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Wi(e){if(!e)return;const t=Kr(e.metadata);return t?{...e,...t}:e}function qm(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function zm(e){let t=0;for(const s of e){const r=Wi(Kr(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 Wm=o.memo(function({items:t,session:s,agentName:r,onBack:i,onOpenItem:a}){const[c,l]=o.useState(!1),d=o.useMemo(()=>[...t].sort((f,k)=>Date.parse(f.timestamp)-Date.parse(k.timestamp)),[t]),u=o.useMemo(()=>zm(d),[d]),h=o.useMemo(()=>{if(d.length<2)return null;const f=Date.parse(d[0].timestamp),w=Date.parse(d[d.length-1].timestamp)-f;return w<6e4?`${Math.round(w/1e3)}s`:w<36e5?`${Math.round(w/6e4)}m`:`${(w/36e5).toFixed(1)}h`},[d]),y=o.useMemo(()=>{let f=null,k=null,w=null,x=null,_=null;for(const g of d){const C=Wi(Kr(g.metadata));if(C&&(!f&&typeof C.domain=="string"&&(f=C.domain),!k&&typeof C.provider=="string"&&(k=C.provider),!w&&typeof C.model=="string"&&(w=C.model),!x&&typeof C.spawn_guard_model_tier=="string"&&(x=C.spawn_guard_model_tier),!_&&typeof C.kickoff_context_hash=="string"&&(_=C.kickoff_context_hash),f&&(k||w)&&x&&_))break}return!(f||k||w||x||_)?null:{domain:f,provider:k,model:w,modelTier:x,kickoffContextHash:_}},[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:L.lime,boxShadow:`0 0 12px ${L.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:ot(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(Rt,{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":""]}),h&&n.jsx("span",{children:h}),u&&n.jsx("span",{className:"text-muted",children:u}),(y==null?void 0:y.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:ot(y.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"?`${L.lime}20`:s.status==="failed"?`${L.red}20`:`${L.teal}20`,color:s.status==="running"?L.lime:s.status==="failed"?L.red:L.teal},children:s.status}),y&&(y.provider||y.model||y.modelTier||y.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>l(f=>!f),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&&y&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(y.provider||y.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[y.provider?`${ot(y.provider)} · `:"",y.model?or(y.model):"—"]}),y.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",ot(y.modelTier)]}),y.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 ",y.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(pt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${L.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((f,k)=>{var ee;const w=Om(f),x=w.color,_=(ee=Wi(Kr(f.metadata)))==null?void 0:ee.model,v=typeof _=="string"?or(_):null,g=ot(f.title??""),C=f.type==="run_failed",U=f.type==="artifact_created",de=f.type==="decision_requested"||f.type==="decision_resolved";return n.jsxs(ye.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:k*.02},onClick:()=>a==null?void 0:a(f),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:`${x}20`,color:x,border:`1px solid ${x}40`},children:n.jsx(Bm,{icon:w.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":de?"text-amber-300":U?"text-cyan-300":"text-bright"}`,children:g}),f.summary&&f.summary!==g&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:ot(f.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:qr(f.timestamp),children:qm(f.timestamp)}),v&&n.jsx("span",{className:"text-micro text-faint",children:v})]})]},f.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":"",h?` over ${h}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:qr(d[d.length-1].timestamp),children:St(d[d.length-1].timestamp)})]})]})]})});function Um({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(pt,{children:r&&n.jsx(ye.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:`${L.teal}08`,border:`1px solid ${L.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 Hm={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function Vm({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,userStateLabel:l,userStateWhy:d,relativeTime:u,timeLabel:h,isRecent:y,enableMotion:b,onOpen:f,ariaLabel:k,artifactSnippet:w}){const x="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",_=n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Rt,{name:a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:ue("absolute inset-y-0 left-0 w-[2px] rounded-full",y&&"pulse-soft"),style:{backgroundColor:c,boxShadow:`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:"truncate text-caption text-secondary",title:r,children:r}),n.jsx("p",{className:"mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug text-bright",children:s||t})]}),n.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[n.jsx("span",{className:"text-caption text-secondary",children:h}),n.jsx("span",{className:"text-micro text-muted",children:u})]})]}),w?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border border-cyan-400/20 bg-cyan-500/[0.06] px-2.5 py-1.5",children:[n.jsxs("svg",{width:"14",height:"14",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.jsxs("span",{className:"min-w-0 flex-1 truncate text-caption text-cyan-200/90",children:[n.jsx("span",{className:"font-semibold",children:w.label}),w.preview&&n.jsx("span",{className:"ml-1.5 text-cyan-200/60",children:w.preview})]}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-50",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(Vr,{mode:"inline",text:i})}):null,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})})]})]})]});return b?n.jsx(ye.button,{type:"button",variants:Hm,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:f,className:x,"aria-label":k,children:_},e):n.jsx("button",{type:"button",onClick:f,className:ue(x,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":k,children:_},e)}function Km({open:e,onClose:t,children:s}){return n.jsx(ei,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function Gm(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 Xm={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 Qm({item:e,className:t}){const s=o.useMemo(()=>El(e),[e]),r=Gm(e),i=Xm[r];return!s.taskDescription&&!s.outcomeDescription&&!s.nextStep?null:n.jsxs("div",{className:`rounded-lg border ${i.border} ${i.bg} p-6 space-y-5 ${t??""}`,children:[s.taskDescription&&n.jsx(vi,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(vi,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(vi,{label:"Next step",value:s.nextStep,styles:i})]})}function vi({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-[10px] font-semibold uppercase tracking-widest ${s.label}`,children:e}),n.jsx("p",{className:"text-[14px] leading-relaxed text-white mt-1",children:t})]})})}const Xa=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),Jm=[{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"}],Ys=[{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"}],Qa={type:"spring",stiffness:400,damping:25},Ja={scale:.985};function Kt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ym(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 Zs(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?$t(Cn(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function Zm(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function ep(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 Gr(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Os(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 Zo(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function tp(e){return e==="agent"?"assistant":e}function np(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function sp(e,t){return t.map(s=>({id:s.id,role:tp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function el(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function Bs(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Br(e){const t=Bs(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=Bs(t.latestMessage),i=Bs(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 rp(e){const t=Bs(e);if(!t)return null;const s=Br({...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=>Bs(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=>Bs(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)=>Kt(a.createdAt)-Kt(c.createdAt)),launches:i.sort((a,c)=>Kt(c.requestedAt)-Kt(a.requestedAt))}}function ip(e,t,s){const r=Kt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Kt(s.startIso),c=Kt(s.endIso);return!(a&&r<a||c&&r>c)}const i=cr(t,Date.now());return i?r>=i:!0}async function er(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 ki(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)=>Kt(i.lastActivityAt??i.updatedAt)-Kt(r.lastActivityAt??r.updatedAt))}function ap(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)=>Kt(i.lastActivityAt??i.updatedAt)-Kt(r.lastActivityAt??r.updatedAt))}const tl=o.createContext(null),nl=o.createContext(null);function ta(){const e=o.useContext(tl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function na(){const e=o.useContext(nl);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function op({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:c,timeFilterId:l,customTimeRange:d,snapshot:u,onRequestRefresh:h}){const[y,b]=o.useState((u==null?void 0:u.threads)??[]),[f,k]=o.useState(null),[w,x]=o.useState(null),[_,v]=o.useState(!1),[g,C]=o.useState(null),[U,de]=o.useState("resting"),[ee,pe]=o.useState(""),[ie,se]=o.useState(!1),[oe,we]=o.useState(!1),[Ne,Q]=o.useState(null),[je,Me]=o.useState(null),[B,I]=o.useState([]),[T,ce]=o.useState(""),[ge,J]=o.useState([]),[he,V]=o.useState(""),[G,le]=o.useState(null),[ae,ve]=o.useState(""),[re,Pe]=o.useState(!1),[Se,E]=o.useState(""),[P,K]=o.useState([]),[te,Re]=o.useState(!1),[qe,Ee]=o.useState("auto"),[M,q]=o.useState(!1),[ne,me]=o.useState(!1),[Te,et]=o.useState(!1),tt=o.useRef(null),Ce=o.useRef(null),Ye=o.useRef(null),ze=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b(R=>ap(R,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{f&&b(R=>R.sort((X,fe)=>Kt(fe.lastActivityAt)-Kt(X.lastActivityAt)))},[f]);const{data:dt}=Zi({enabled:!0,refetchInterval:8e3}),at=o.useMemo(()=>{var X,fe;const R=new Map;for(const Fe of Jm)R.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.handle,domain:Fe.domain,domainLabel:Fe.domainLabel,role:Fe.role,status:"idle",currentTask:null,isSystem:!1});if(dt!=null&&dt.agents)for(const Fe of dt.agents){const Ke=R.get(Fe.id);Ke?(Ke.status=Fe.status==="running"?"running":(X=Fe.blockers)!=null&&X.length?"blocked":"idle",Ke.currentTask=Fe.currentTask??null):R.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Fe.status==="running"?"running":(fe=Fe.blockers)!=null&&fe.length?"blocked":"idle",currentTask:Fe.currentTask??null,isSystem:Xa.has(Fe.id)})}for(const Fe of t){const Ke=(Fe.agentId??"").trim(),wt=(Fe.agentName??"").trim();!Ke||!wt||R.has(Ke)||R.set(Ke,{id:Ke,name:wt,handle:Ke,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:Xa.has(Ke)})}return Array.from(R.values()).filter(Fe=>!Fe.isSystem).sort((Fe,Ke)=>Fe.name.localeCompare(Ke.name))},[dt,t]),nt=o.useMemo(()=>s.map(R=>({id:R.id,name:R.name})).sort((R,X)=>R.name.localeCompare(X.name)),[s]),xe=o.useMemo(()=>at.find(R=>R.id===T)??null,[at,T]),Xe=o.useMemo(()=>{const R=new Set(ge);return at.filter(X=>R.has(X.id))},[at,ge]),ke=o.useMemo(()=>nt.find(R=>R.id===he)??null,[nt,he]);o.useEffect(()=>{T&&J(R=>R.filter(X=>X!==T))},[T]);const W=o.useMemo(()=>at.slice(0,8),[at]),$e=o.useMemo(()=>{const R=ae.trim().toLowerCase();return R?at.filter(X=>X.name.toLowerCase().includes(R)||X.handle.toLowerCase().includes(R)||X.domain.toLowerCase().includes(R)||X.role.toLowerCase().includes(R)):at},[at,ae]),z=o.useMemo(()=>{const R=Se.trim().toLowerCase();return R?nt.filter(X=>X.name.toLowerCase().includes(R)):nt},[nt,Se]),Y=o.useMemo(()=>{const R=i.trim().toLowerCase(),X=y.filter(fe=>!ep(fe,a)||!ip(fe,l,d)?!1:R.length===0?!0:Zm(fe).includes(R));return X.sort((fe,Fe)=>{const Ke=Kt(Fe.lastActivityAt)-Kt(fe.lastActivityAt);return c==="newest"?Ke:-Ke}),X},[d,i,c,a,y,l]),Ae=o.useMemo(()=>{if(!f||Y.some(X=>X.id===f))return Y;const R=y.find(X=>X.id===f);return R?[R,...Y]:Y},[f,Y,y]),De=o.useMemo(()=>y.find(R=>R.id===f)??null,[f,y]),Le=o.useMemo(()=>B.filter(R=>R.status!=="ready").length,[B]),_e=ee.trim().length>0&&!ie,He=o.useMemo(()=>Le>0?`${Le} attachment(s) still processing.`:"Press Enter to send.",[Le]),st=o.useMemo(()=>ie?"Sending…":oe?"Launching…":"Send",[oe,ie]),Ve=o.useMemo(()=>new Nl({api:"/orgx/api/chat/usechat"}),[]),{messages:Et,setMessages:Je,sendMessage:jt,status:Ut,error:Bt,clearError:yn}=bl({id:`orgx-chat-guidance-${r??"global"}`,transport:Ve,onError:R=>{Q(Zs((R==null?void 0:R.message)??null,"send"))}});o.useEffect(()=>{if(!w){Je([]);return}Je(sp(w.id,w.messages))},[w,Je]);const bn=o.useMemo(()=>{const R=[...Et].reverse().find(fe=>fe.role==="assistant");if(!R)return null;const X=np(R);return X.length>0?X:null},[Et]),rs=o.useRef(null);o.useEffect(()=>{if(Ut!=="ready"&&Ut!=="error"||!bn)return;const R=[...Et].reverse().find(X=>X.role==="assistant");!R||R.id===rs.current||(rs.current=R.id,K(X=>[...X,{id:`guidance_${R.id}`,role:"agent",body:bn,timestamp:new Date().toISOString()}]))},[Ut,bn,Et]);const ht=o.useCallback(()=>{pe(""),I([]),me(!1),et(!1),Q(null),Me(null)},[]),Ot=o.useCallback(R=>{K(X=>[...X,{...R,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Nt=o.useCallback(()=>K([]),[]),Mn=o.useCallback(()=>Re(R=>!R),[]),ut=o.useMemo(()=>Ys.find(R=>R.id===qe)??Ys[0],[qe]),En=o.useCallback(()=>{Ee(R=>{const X=Ys.findIndex(fe=>fe.id===R);return Ys[(X+1)%Ys.length].id})},[]),Gt=o.useCallback(async()=>{typeof h=="function"&&await h()},[h]),Lt=o.useCallback(async R=>{var Fe;v(!0),C(null);const X=await er(`/orgx/api/chat/threads/${encodeURIComponent(R)}`);if(!X.ok||!((Fe=X.data)!=null&&Fe.thread))return v(!1),C(Zs(X.error,"load")),null;const fe=rp(X.data.thread);return fe?(x(fe),v(!1),fe):(v(!1),C("Thread detail payload was invalid."),null)},[]),Zt=o.useCallback(async(R,X)=>{X&&(Ye.current=X),k(R),await Lt(R),requestAnimationFrame(()=>{var fe;return(fe=Ce.current)==null?void 0:fe.focus()})},[Lt]),wn=o.useCallback(()=>{var R;k(null),x(null),C(null),v(!1),(R=Ye.current)==null||R.focus()},[]),an=o.useCallback(R=>{window.setTimeout(()=>{I(X=>X.map(fe=>fe.id===R?{...fe,status:"indexing",updatedAt:new Date().toISOString()}:fe))},80),window.setTimeout(()=>{I(X=>X.map(fe=>{var wt;if(fe.id!==R)return fe;const Fe=((wt=fe.mimeType)==null?void 0:wt.toLowerCase())==="application/x-msdownload"||fe.name.toLowerCase().endsWith(".exe"),Ke=(fe.sizeBytes??0)>25*1024*1024;return Fe?{...fe,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:Ke?{...fe,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...fe,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),is=o.useCallback(R=>{if(!R||R.length===0)return;const X=new Date().toISOString(),fe=Array.from(R).map(Fe=>({id:`draft_att_${crypto.randomUUID()}`,name:Fe.name,mimeType:Fe.type||null,sizeBytes:Number.isFinite(Fe.size)?Fe.size:null,status:"preparing",error:null,masked:!1,createdAt:X,updatedAt:X}));I(Fe=>Fe.concat(fe)),fe.forEach(Fe=>an(Fe.id)),Qn("chat_attachment_state_changed",{count:fe.length,state:"preparing"})},[an]),as=o.useCallback(R=>{I(X=>X.map(fe=>fe.id===R?{...fe,status:"preparing",error:null,updatedAt:new Date().toISOString()}:fe)),an(R),Qn("chat_attachment_state_changed",{state:"retry"})},[an]),on=o.useCallback(R=>{ce(X=>X===R?"":R),J(X=>X.filter(fe=>fe!==R)),le(null),ve("")},[]),ln=o.useCallback(R=>{J(X=>X.includes(R)?X.filter(fe=>fe!==R):X.concat(R))},[]),qt=o.useCallback(()=>{Pe(!1),E(""),le(R=>R==="assignee"?null:"assignee"),ve("")},[]),Wn=o.useCallback(()=>{Pe(!1),E(""),le(R=>R==="watcher"?null:"watcher"),ve("")},[]),vn=o.useCallback(()=>{le(null),ve(""),Pe(R=>!R),E("")},[]),Un=o.useCallback(async(R,X)=>{var wt;q(!0);const fe=nt.find(Ze=>Ze.id===X)??null,Fe=await er("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:R,project_id:r??void 0,initiativeId:(fe==null?void 0:fe.id)??null,initiativeTitle:(fe==null?void 0:fe.name)??null,relinked:!0})});if(q(!1),!Fe.ok||!((wt=Fe.data)!=null&&wt.thread)){C(Fe.error??"Scope link failed.");return}const Ke=Br(Fe.data.thread);Ke&&b(Ze=>ki(Ze,Ke)),await Lt(R),await Gt(),Qn("chat_thread_linked_initiative",{threadId:R,initiativeId:(fe==null?void 0:fe.id)??null})},[nt,Lt,Gt,r]),kn=o.useCallback(async R=>{yn(),await jt({text:R.prompt},{body:{threadId:R.thread.id,project_id:r??void 0,initiativeId:R.thread.initiativeId??(ke==null?void 0:ke.id)??void 0,initiativeTitle:R.thread.initiativeTitle??(ke==null?void 0:ke.name)??void 0,assigneeId:(xe==null?void 0:xe.id)??R.thread.assigneeId??void 0,assigneeName:(xe==null?void 0:xe.name)??R.thread.assigneeName??void 0,watcherIds:Xe.map(X=>X.id),watcherNames:Xe.map(X=>X.name)}}),await Gt(),await Lt(R.thread.id)},[yn,Lt,Gt,xe==null?void 0:xe.id,xe==null?void 0:xe.name,ke==null?void 0:ke.id,ke==null?void 0:ke.name,Xe,jt,r]),cn=o.useCallback(async()=>{var Ke,wt;const R=ee.trim();if(!R)return Q("Write a message before sending."),{thread:null,messageId:null};Q(null),Me(null),se(!0);const X=await er("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:f??void 0,project_id:r??void 0,initiativeId:(ke==null?void 0:ke.id)??(w==null?void 0:w.initiativeId)??void 0,initiativeTitle:(ke==null?void 0:ke.name)??(w==null?void 0:w.initiativeTitle)??void 0,assigneeId:(xe==null?void 0:xe.id)??(w==null?void 0:w.assigneeId)??void 0,assigneeName:(xe==null?void 0:xe.name)??(w==null?void 0:w.assigneeName)??void 0,watcherIds:Xe.map(Ze=>Ze.id),watcherNames:Xe.map(Ze=>Ze.name),body:R,attachments:B.map(Ze=>({id:Ze.id,name:Ze.name,mimeType:Ze.mimeType,sizeBytes:Ze.sizeBytes,status:Ze.status,error:Ze.error,masked:Ze.masked}))})});if(se(!1),!X.ok||!((Ke=X.data)!=null&&Ke.thread))return Q(Zs(X.error,"send")),Qn("chat_message_send_failed",{reason:X.error??"unknown"}),{thread:null,messageId:null};const fe=Br(X.data.thread);if(!fe)return Q("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(Ze=>ki(Ze,fe)),Ot({role:"user",body:R}),qe!=="auto"&&xe&&Ot({role:"system",body:`Routing to ${xe.name} via ${ut.label}`}),Qn("chat_message_sent",{threadId:fe.id,watcherCount:fe.watcherIds.length}),await Gt();const Fe=X.data.message&&typeof X.data.message.id=="string"?X.data.message.id:((wt=fe.latestMessage)==null?void 0:wt.id)??null;return k(fe.id),await Lt(fe.id),kn({thread:fe,prompt:R}).catch(Ze=>{Ot({role:"error",body:Zs(Ze instanceof Error?Ze.message:String(Ze??""),"send")})}),ht(),de("reviewing"),{thread:fe,messageId:Fe}},[w==null?void 0:w.assigneeId,w==null?void 0:w.assigneeName,w==null?void 0:w.initiativeId,w==null?void 0:w.initiativeTitle,f,ee,B,Lt,Gt,ht,kn,xe==null?void 0:xe.id,xe==null?void 0:xe.name,ke==null?void 0:ke.id,ke==null?void 0:ke.name,qe,ut,Xe,r]),Hn=o.useCallback(async(R,X)=>{var xt,mn,Vn,ls,pn,Fn,Tn;if(!X){Ot({role:"error",body:"Send a message first to launch."});return}if(!xe){Ot({role:"error",body:"Pick an agent with @ before launching."});return}if(Le>0&&!Te){me(!0),Ot({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}we(!0),Q(null),Me(null);const fe=await er("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:xe.id,message:ee.trim().length>0?ee.trim():R.lastSnippet??R.title,initiativeId:R.initiativeId??(ke==null?void 0:ke.id)??void 0,initiativeTitle:R.initiativeTitle??(ke==null?void 0:ke.name)??void 0,workstreamId:R.workstreamId??void 0,taskId:R.taskId??void 0,provider:qe!=="auto"?qe:void 0})}),Fe=((xt=fe.data)==null?void 0:xt.sessionId)??((mn=fe.data)==null?void 0:mn.runId)??null,Ke=fe.ok&&Fe?"running":fe.ok?"queued":"blocked",wt=fe.ok?null:fe.error??"Launch request failed before queueing.",Ze=await er("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:R.id,messageId:X,assigneeId:xe.id,assigneeName:xe.name,watcherIds:Xe.map(vt=>vt.id),watcherNames:Xe.map(vt=>vt.name),executionMode:"local_queue",provider:((Vn=fe.data)==null?void 0:Vn.provider)??(qe!=="auto"?qe:"openclaw"),runId:Fe??void 0,status:Ke,blockedReason:wt??void 0,warnings:Le>0?[`${Le} attachment(s) were not ready at launch.`]:[]})});if(we(!1),et(!1),me(!1),!Ze.ok||!((ls=Ze.data)!=null&&ls.thread)){Q(Ze.error?Zs(Ze.error,"launch"):wt??"Launch state could not be persisted. Message remained saved."),Qn("chat_launch_failed",{threadId:R.id,reason:Ze.error??wt??"unknown"});return}const os=Br(Ze.data.thread);if(os&&b(vt=>ki(vt,os)),await Lt(R.id),await Gt(),!fe.ok){Q(`Launch blocked: ${wt??"Set assignee and retry."}`),Qn("chat_launch_blocked",{threadId:R.id,reason:wt??"unknown"});return}const un=((pn=fe.data)==null?void 0:pn.provider)==="anthropic"?"Claude Code":((Fn=fe.data)==null?void 0:Fn.provider)==="openai"?"Codex":ut.shortLabel,qs=(Tn=fe.data)!=null&&Tn.model?` (${fe.data.model})`:"";Me(Fe?`Launch started via ${un}${qs}. Thread timeline now tracks execution state.`:`Launch queued locally via ${un}. Run starts when a worker is available.`),Qn(Fe?"chat_launch_started":"chat_launch_queued",{threadId:R.id,runId:Fe,assigneeId:xe.id})},[ee,Te,Lt,Gt,xe,ke==null?void 0:ke.id,ke==null?void 0:ke.name,qe,ut,Xe,Le]),It=o.useCallback(async()=>{var X;const R=await cn();(X=R.thread)!=null&&X.id&&await Zt(R.thread.id)},[Zt,cn]),dn=o.useCallback(async()=>{const R=await cn();R.thread&&(await Hn(R.thread,R.messageId),await Zt(R.thread.id))},[Hn,Zt,cn]),jn=o.useCallback(async()=>{if(_e){if(xe){await dn();return}await It()}},[_e,dn,It,xe]),Ht=o.useMemo(()=>({threads:y,activeThreadId:f,activeThread:w,activeThreadSummary:De,displayedThreads:Ae,composerMode:U,draft:ee,draftAttachments:B,sending:ie,launching:oe,composerError:Ne,composerNotice:je,selectedAssigneeId:T,selectedAssignee:xe,selectedWatcherIds:ge,selectedWatchers:Xe,selectedInitiativeId:he,selectedInitiative:ke,agentOptions:at,quickAssigneeOptions:W,initiativeOptions:nt,agentPickerMode:G,agentPickerQuery:ae,filteredAgentOptions:$e,scopePickerOpen:re,scopePickerQuery:Se,filteredInitiativeOptions:z,panelLoading:_,panelError:g,scopeSaving:M,launchWarningOpen:ne,launchWarningAccepted:Te,unresolvedAttachmentCount:Le,canSend:_e,composerGuidance:He,primaryActionLabel:st,guidanceStatus:Ut,guidancePreview:bn,guidanceError:Bt??null,inlineMessages:P,threadSidebarOpen:te,workspaceId:r,selectedProvider:qe,selectedProviderDef:ut}),[y,f,w,De,Ae,U,ee,B,ie,oe,Ne,je,T,xe,ge,Xe,he,ke,at,W,nt,G,ae,$e,re,Se,z,_,g,M,ne,Te,Le,_e,He,st,Ut,bn,Bt,P,te,r,qe,ut]),Tt=o.useMemo(()=>({setDraft:pe,setComposerMode:de,setDraftAttachments:I,selectAssignee:on,toggleWatcher:ln,setSelectedInitiativeId:V,toggleAssigneePicker:qt,toggleWatcherPicker:Wn,toggleScopePicker:vn,setAgentPickerQuery:ve,setScopePickerQuery:E,setAgentPickerMode:le,setScopePickerOpen:Pe,handlePrimaryAction:jn,handleFilesAdded:is,handleRetryAttachment:as,openThreadPanel:Zt,closeThreadPanel:wn,loadThreadDetail:Lt,applyScopeLink:Un,resetComposer:ht,setComposerError:Q,setComposerNotice:Me,setLaunchWarningAccepted:et,pushInlineMessage:Ot,clearInlineMessages:Nt,toggleThreadSidebar:Mn,setSelectedProvider:Ee,cycleProvider:En,fileInputRef:tt,panelHeadingRef:Ce,composerShellRef:ze}),[on,ln,qt,Wn,vn,jn,is,as,Zt,wn,Lt,Un,ht,Ot,Nt,Mn,En]);return n.jsx(tl.Provider,{value:Ht,children:n.jsx(nl.Provider,{value:Tt,children:e})})}const lp={type:"spring",stiffness:500,damping:35,mass:.5};function cp({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=zn(),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(ye.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:ue("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(pt,{initial:!1,children:c.map(d=>n.jsx(ye.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:lp,className:ue("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:ue("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:ue("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:St(d.timestamp)})]}),n.jsxs("p",{className:ue("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 Ya({open:e,onClose:t}){const s=zn(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:h}=ta(),{openThreadPanel:y,closeThreadPanel:b,loadThreadDetail:f,applyScopeLink:k,panelHeadingRef:w}=na(),x=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,_=o.useCallback((g,C)=>{y(g,C)},[y]),v=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(pt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ye.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:v,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(ye.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Yt.durationEntrance/1e3,ease:Yt.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:v,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:ue("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("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:"No threads yet. Send a message to start one."}):n.jsx("div",{className:"space-y-1.5",children:r.map(g=>n.jsxs("button",{type:"button",onClick:C=>_(g.id,C.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===g.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:g.lastSnippet?`"${g.lastSnippet.length>40?g.lastSnippet.slice(0,40)+"...":g.lastSnippet}"`:g.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:g.lastActivityAt,children:St(g.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[g.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",g.assigneeName]}),n.jsx("span",{children:g.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Os(g.status)),children:Gr(g.status)})]})]},g.id))})}),n.jsx(pt,{initial:!1,children:i&&n.jsxs(ye.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:Yt.durationStandard/1e3,ease:Yt.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:w,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:ue("rounded-full border px-2 py-0.5 text-micro font-semibold",Os((c==null?void 0:c.status)??"message_only")),children:Gr((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}),x&&n.jsx("button",{type:"button",onClick:()=>void f(x),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(g=>n.jsx("article",{className:ue("flex",g.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",g.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":g.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:g.senderName??Zo(g.role)}),n.jsx("time",{dateTime:g.createdAt,children:St(g.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:g.body})]})},g.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(g=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Os(el(g.status))),children:g.status}),n.jsx("span",{children:g.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:g.requestedAt,children:St(g.requestedAt)})]},g.id))]})]})})]})]})]})})}function Za(){const e=zn(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=ta(),{openThreadPanel:h,closeThreadPanel:y,loadThreadDetail:b,applyScopeLink:f,setComposerMode:k,toggleThreadSidebar:w,panelHeadingRef:x}=na(),_=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,v=o.useCallback(()=>{w()},[w]);return u?n.jsx(pt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ye.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:v,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(ye.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Yt.durationEntrance/1e3,ease:Yt.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:v,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(ye.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:Ja,transition:Qa,onClick:()=>{v(),k("focused"),requestAnimationFrame(()=>{const g=document.getElementById("chat-dock-input");g instanceof HTMLTextAreaElement&&g.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((g,C)=>n.jsxs(ye.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:Qa,delay:e?0:Math.min(C*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Ja,onClick:U=>void h(g.id,U.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===g.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:g.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:g.lastActivityAt,children:St(g.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:g.lastSnippet??g.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[g.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Rt,{name:g.assigneeName,hint:g.assigneeName,size:"xs"}),n.jsx("span",{children:g.assigneeName})]}),n.jsx("span",{children:g.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Os(g.status)),children:Gr(g.status)})]})]},g.id))})}),n.jsx(pt,{initial:!1,children:s&&n.jsxs(ye.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:Yt.durationStandard/1e3,ease:Yt.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:x,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:ue("rounded-full border px-2 py-0.5 text-micro font-semibold",Os((i==null?void 0:i.status)??"message_only")),children:Gr((i==null?void 0:i.status)??"message_only")}),n.jsx("button",{type:"button",onClick:y,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}),_&&n.jsx("button",{type:"button",onClick:()=>void b(_),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(g=>n.jsx("article",{className:ue("flex",g.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",g.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":g.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:g.senderName??Zo(g.role)}),n.jsx("time",{dateTime:g.createdAt,children:St(g.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:g.body})]})},g.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(g=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Os(el(g.status))),children:g.status}),n.jsx("span",{children:g.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:g.requestedAt,children:St(g.requestedAt)})]},g.id))]})]})})]},"sidebar-panel")]})}):null}const dp={type:"spring",stiffness:500,damping:30,mass:.5};function up({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=zn(),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 h=s.toLowerCase();return u.name.toLowerCase().includes(h)||u.handle.toLowerCase().includes(h)||u.domain.toLowerCase().includes(h)||u.role.toLowerCase().includes(h)}):t;if(!e||l.length===0)return null;const d=l.slice(0,6);return n.jsx(pt,{children:n.jsx(ye.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:dp,className:ue("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,h)=>{const y=h===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:ue("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",y?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Rt,{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 mp={type:"spring",stiffness:500,damping:30,mass:.5};function pp({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=zn(),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(pt,{children:n.jsx(ye.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:mp,className:ue("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:ue("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,h)=>{const y=h+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:ue("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",y?"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 fp({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:c,onQueryChange:l,onSelectAssignee:d,onToggleWatcher:u,onClose:h,onSwitchMode:y,anchorRef:b}){const f=zn();return n.jsx(pt,{children:e&&n.jsxs(ye.div,{initial:f?!1:{opacity:0,scale:.95,y:8},animate:f?{}:{opacity:1,scale:1,y:0},exit:f?{}:{opacity:0,scale:.95,y:8},transition:f?void 0:Yt.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:()=>y("assignee"),className:ue("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:()=>y("watcher"),className:ue("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:h,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(k=>{const w=a===k.id;return n.jsx("button",{type:"button",onClick:()=>d(k.id),title:k.name,className:ue("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",w?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":w,"aria-label":`Select ${k.name} as assignee`,children:n.jsx(Rt,{name:k.name,hint:k.name,size:"xs"})},k.id)})}),n.jsx("input",{value:i,onChange:k=>l(k.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(k=>{const w=a===k.id,x=c.includes(k.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(k.id);return}w||u(k.id)},className:ue("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",w?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":x?"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(Rt,{name:k.name,hint:k.name,size:"xs"}),n.jsx("span",{children:k.name})]}),n.jsx("span",{className:"text-micro",children:w?"Assignee":x?"Watcher":"Select"})]},k.id)})})]})})}const eo=24,to=200;function no(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 hp(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 so({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 Ui="orgx-chat-dock-collapsed";function gp(){try{return localStorage.getItem(Ui)==="1"}catch{return!1}}function xp(){const e=ta(),t=na(),s=zn(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState(gp),l=o.useCallback(()=>{c(W=>{const $e=!W;try{localStorage.setItem(Ui,$e?"1":"0")}catch{}return $e})},[]),[d,u]=o.useState(!1),[h,y]=o.useState(!1),b=o.useRef(null),[f,k]=o.useState(!1),[w,x]=o.useState(""),[_,v]=o.useState(0),[g,C]=o.useState(-1),[U,de]=o.useState(!1),[ee,pe]=o.useState(""),[ie,se]=o.useState(0),[oe,we]=o.useState(-1),{composerMode:Ne,draft:Q,draftAttachments:je,sending:Me,launching:B,selectedAssigneeId:I,selectedAssignee:T,selectedWatcherIds:ce,selectedInitiative:ge,agentOptions:J,quickAssigneeOptions:he,agentPickerMode:V,agentPickerQuery:G,filteredAgentOptions:le,initiativeOptions:ae,canSend:ve,activeThreadId:re,guidanceStatus:Pe,inlineMessages:Se,displayedThreads:E,launchWarningOpen:P,launchWarningAccepted:K,selectedProvider:te,selectedProviderDef:Re}=e,qe=Q.trim(),Ee=Se.length>0;qe.length>0;const M=o.useCallback(()=>{const W=r.current;if(!W)return;W.style.height="0";const $e=Math.min(Math.max(W.scrollHeight,eo),to);W.style.height=`${$e}px`},[]);o.useLayoutEffect(()=>{M()},[Q,M]);const q=o.useMemo(()=>{if(!f)return J;const W=w.toLowerCase();return W?J.filter($e=>$e.name.toLowerCase().includes(W)||$e.handle.toLowerCase().includes(W)||$e.domain.toLowerCase().includes(W)||$e.role.toLowerCase().includes(W)):J},[J,f,w]),ne=o.useMemo(()=>{if(!U)return ae;const W=ee.toLowerCase();return W?ae.filter($e=>$e.name.toLowerCase().includes(W)):ae},[ae,U,ee]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),Se.length<=2){y(!1);return}return y(!1),b.current=window.setTimeout(()=>{y(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[Se.length]),o.useEffect(()=>{const W=$e=>{if(($e.metaKey||$e.ctrlKey)&&$e.key==="k"){if($e.preventDefault(),a){c(!1);try{localStorage.setItem(Ui,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var z;return(z=r.current)==null?void 0:z.focus()})}};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[t,a]);const me=o.useCallback(()=>{Ne==="resting"&&t.setComposerMode("focused")},[Ne,t]),Te=o.useCallback(()=>{window.setTimeout(()=>{qe.length===0&&!Ee&&!f&&!U&&je.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),k(!1),de(!1))},100)},[qe,Ee,f,U,je.length,t]),et=o.useCallback(W=>{const $e=W.target.value,z=W.target.selectionStart??$e.length;t.setDraft($e),(Ne==="resting"||Ne==="focused")&&t.setComposerMode("composing");const Y=$e.slice(0,z),Ae=Y.match(/@(\w*)$/);if(Ae){k(!0),x(Ae[1]),v(0),C(z-Ae[0].length),de(!1);return}const De=Y.match(/#(\w*)$/);if(De){de(!0),pe(De[1]),se(0),we(z-De[0].length),k(!1);return}f&&k(!1),U&&de(!1)},[Ne,t,f,U]),tt=o.useCallback(W=>{var Ae;const $e=Q.slice(0,g),z=Q.slice(((Ae=r.current)==null?void 0:Ae.selectionStart)??Q.length),Y=`${$e}@${W.name} ${z}`;t.setDraft(Y),t.selectAssignee(W.id),k(!1),x(""),requestAnimationFrame(()=>{if(r.current){const De=$e.length+W.name.length+2;r.current.setSelectionRange(De,De),r.current.focus()}})},[Q,g,t]),Ce=o.useCallback(W=>{var Y;const $e=Q.slice(0,oe),z=Q.slice(((Y=r.current)==null?void 0:Y.selectionStart)??Q.length);if(W){const Ae=`${$e}#${W.name} ${z}`;t.setDraft(Ae),t.setSelectedInitiativeId(W.id),requestAnimationFrame(()=>{if(r.current){const De=$e.length+W.name.length+2;r.current.setSelectionRange(De,De),r.current.focus()}})}else{const Ae=`${$e}${z}`;t.setDraft(Ae),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange($e.length,$e.length),r.current.focus())})}de(!1),pe("")},[Q,oe,t]),Ye=o.useCallback(W=>{if(f&&q.length>0){if(W.key==="ArrowDown"){W.preventDefault(),v($e=>($e+1)%q.length);return}if(W.key==="ArrowUp"){W.preventDefault(),v($e=>($e-1+q.length)%q.length);return}if(W.key==="Enter"||W.key==="Tab"){W.preventDefault(),tt(q[_]);return}if(W.key==="Escape"){W.preventDefault(),k(!1);return}}if(U){const $e=ne.length+1;if(W.key==="ArrowDown"){W.preventDefault(),se(z=>(z+1)%$e);return}if(W.key==="ArrowUp"){W.preventDefault(),se(z=>(z-1+$e)%$e);return}if(W.key==="Enter"||W.key==="Tab"){W.preventDefault(),Ce(ie===0?null:ne[ie-1]);return}if(W.key==="Escape"){W.preventDefault(),de(!1);return}}if(W.key==="Enter"&&!W.shiftKey){W.preventDefault(),t.handlePrimaryAction();return}W.key==="Escape"&&(W.preventDefault(),V?t.setAgentPickerMode(null):Ee?t.clearInlineMessages():(t.setComposerMode("resting"),W.target.blur()))},[t,V,Ee,f,q,_,tt,U,ne,ie,Ce]),ze=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),dt=Me||B?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"})]}),at=(Ne==="reviewing"||Ee)&&Se.length>0,nt=Pe==="submitted"||Pe==="streaming",xe=o.useRef(Se.length),[Xe,ke]=o.useState(0);return o.useEffect(()=>{if(!a){xe.current=Se.length,ke(0);return}const W=Se.length-xe.current;W>0&&ke(W)},[a,Se.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(Ya,{open:d,onClose:()=>u(!1)}),n.jsx(Za,{}),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(ye.button,{type:"button",onClick:()=>{l(),requestAnimationFrame(()=>{var W;return(W=r.current)==null?void 0:W.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:ue("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(pt,{children:Xe>0&&n.jsx(ye.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:ue("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:Xe>9?"9+":Xe},"unread")}),re&&Xe===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(Ya,{open:d,onClose:()=>u(!1)}),n.jsx(Za,{}),n.jsxs("div",{ref:W=>{t.composerShellRef.current=W},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(pt,{children:P&&n.jsxs(ye.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:K,onChange:W=>t.setLaunchWarningAccepted(W.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(fp,{open:V!==null,mode:V??"assignee",agents:le,quickAgents:he,query:G,selectedAssigneeId:I,selectedWatcherIds:ce,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(ye.section,{"data-testid":"chat-dock","data-state":Ne,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Yt.durationEntrance/1e3,ease:Yt.easingEntrance},className:ue("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",Ne!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:l,className:ue("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:W=>{t.fileInputRef.current=W},type:"file",multiple:!0,className:"hidden",onChange:W=>{t.handleFilesAdded(W.target.files),W.currentTarget.value=""}}),n.jsx(pt,{children:at&&n.jsx(cp,{messages:Se,isStreaming:nt,collapsed:h,onClick:ze})}),n.jsxs("div",{className:"relative",children:[n.jsx(up,{open:f,agents:q,query:w,activeIndex:_,anchorRect:null,onSelect:tt,onClose:()=>k(!1)}),n.jsx(pp,{open:U,initiatives:ne,query:ee,activeIndex:ie,onSelect:Ce,onClose:()=>de(!1)})]}),n.jsx(pt,{initial:!1,children:je.length>0&&n.jsx(ye.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:je.map(W=>n.jsxs("div",{className:ue("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",W.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:`${no(W.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:no(W.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:W.name}),n.jsxs("p",{className:"text-micro text-muted",children:[hp(W.mimeType,W.name),W.sizeBytes?` · ${Ym(W.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments($e=>$e.filter(z=>z.id!==W.id)),className:ue("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 ${W.name}`,children:"×"}),W.status!=="ready"&&W.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]"})}),W.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(W.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"})]},W.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var W;return(W=t.fileInputRef.current)==null?void 0:W.click()},className:ue("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(ye.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:ue("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",te==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":te==="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(so,{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:Q,onFocus:me,onBlur:Te,onChange:et,onKeyDown:Ye,placeholder:"Ask anything",rows:1,className:ue("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:eo,maxHeight:to,overflowY:"auto"},"aria-expanded":Ne!=="resting"})]}),E.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:ue("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(ye.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!ve,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:ue("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",ve?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:T?`Send to ${T.name} via ${Re.shortLabel}`:`Send via ${Re.shortLabel}`,"aria-label":T?`Send to ${T.name} via ${Re.shortLabel}`:`Send message via ${Re.shortLabel}`,children:dt})]}),n.jsx(pt,{children:(T||ge)&&Ne!=="resting"&&n.jsxs(ye.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:[T&&n.jsxs("button",{ref:W=>{i.current=W},type:"button",onClick:t.toggleWatcherPicker,className:ue("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(Rt,{name:T.name,hint:T.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",T.name]}),T.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),ge&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",ge.name]}),te!=="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(so,{icon:Re.icon}),Re.shortLabel]})]})})]})]})]})}const ji=50,yp=50,tr=20,ro=3600,io=12e3,Sr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"};function bp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function ao(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function es(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function _r(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Cr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Ni(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function oo(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function ks(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function sa(e){if(!e)return;let t={...e},s=ks(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=ks(s.metadata),r+=1;return t}function bt(e){const t=ks(e==null?void 0:e.metadata);return sa(t)}function wp(e){const t=sa(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 Hi(e){if(e.runId)return e.runId;const t=bt(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 ir(e){const t=bt(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 lo(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const vp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,kp=/^[0-9a-f]{20,}$/i,sl=/^\d+$/,rl=/^(user|usr|clerk)_[a-z0-9]+$/i;function Jt(e){if(!e)return null;const t=e.trim();return!t||vp.test(t)||kp.test(t)||sl.test(t)||rl.test(t)?null:t}const jp=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Np(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return jp.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function co(e,t,s){if(!e)return null;let r=null;for(const a of t){const c=Jt(lo(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=Jt(lo(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Ip(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 uo(e){const t=bt(e),s=ir(e),r=Jr(e),i=Jt(s.agentId),a=Jt(s.agentName),c=Jt(e.requesterAgentId??null),l=Jt(e.requesterAgentName??null),u=(c||l?{id:c,name:l,label:l??c??"OrgX"}:null)??co(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,h=Jt(e.executorAgentId??null),y=Jt(e.executorAgentName??null),f=(h||y?{id:h,name:y,label:y??h??"Agent"}:null)??co(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&&f?Ip(u,f)?{requester:u,executor:f,mode:"single",primaryLabel:f.label,subtitle:f.label}:{requester:u,executor:f,mode:"handoff",primaryLabel:f.label,subtitle:`${u.label} -> ${f.label}`}:u&&!f?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested dispatch`}:!u&&f?{requester:null,executor:f,mode:"single",primaryLabel:f.label,subtitle:f.label}:r.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:Jt(e.agentName??null)??Jt(e.agentId??null)??"OrgX",subtitle:Jt(e.agentName??null)??Jt(e.agentId??null)??"OrgX"}}function Ii(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function nr(e){const t=bt(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const i of s){const a=t[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const r=t.orgx_context;if(r&&typeof r=="object"&&!Array.isArray(r)){const i=r,a=i.workstreamId??i.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Ai(e){const t=bt(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 mo=new Map([["autopilot_slice_artifact_buffered","artifact"],["decision_buffered","decision"],["auto_continue_spawn_guard_blocked","decision"],["auto_continue_spawn_guard_rate_limited","decision"],["agent_launch_spawn_guard_blocked","decision"],["agent_launch_spawn_guard_rate_limited","decision"],["agent_restart_spawn_guard_blocked","decision"],["agent_restart_spawn_guard_rate_limited","decision"],["next_up_fallback_spawn_guard_blocked","decision"],["next_up_fallback_spawn_guard_rate_limited","decision"],["autopilot_slice_mcp_handshake_failed","decision"],["autopilot_slice_timeout","decision"],["autopilot_slice_log_stall","decision"],["autopilot_autofix_scheduled","decision"],["autopilot_autofix_executed","message"],["autopilot_autofix_skipped","message"]]);function Mr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Ap(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 Ls(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 Sp(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 _p(e){const t=bt(e),s=Mr(e.kind)??Mr(t==null?void 0:t.activity_bucket)??Mr(t==null?void 0:t.activityBucket)??Mr(t==null?void 0:t.bucket);if(s)return s;if(e.type==="artifact_created")return"artifact";if(e.type==="decision_requested"||e.type==="decision_resolved")return"decision";const r=Sp(t),i=e.decisionRequired===!0||Ap(t,["decision_required","decisionRequired"])===!0,a=Ls(t,["artifacts","artifact_count","artifactCount"])??0,c=Ls(t,["decisions","decision_count","decisionCount"])??0,l=Ls(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ls(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 h=_n(lt(t,["stop_reason","stopReason"])??"");if(h==="blocked"||h==="error")return"decision"}return r&&mo.has(r)?mo.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 Xr(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 Cp(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 Mp(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 Si(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function _i(e){return e==="completed"?L.lime:e==="needs_input"?L.amber:e==="issue"?L.red:L.teal}function Ep(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 po(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function ts(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 Pn(e){const t=ts(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=ts(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function Tp(e){const t=ts(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 Rp(e,t){for(const s of t){const r=Tp(e[s]);if(r!==null)return r}return null}function Er(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 il(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Er(e,["blocking_decision_ids","blockingDecisionIds"]),s=Er(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=Er(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=Er(l,["id","decision_id","decisionId"]),u=l.blocking!==!1;for(const h of d)i.add(h),u?t.includes(h)||t.push(h):s.includes(h)||s.push(h)}return{decisionIds:Array.from(i),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function al(e){if(!e)return null;const t=bt(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=ir(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,h=Array.isArray(u)?u.filter(K=>typeof K=="string"&&K.trim().length>0):[],y=Op(h),b=t.task_ids??t.taskIds,f=Array.isArray(b)?b.filter(K=>typeof K=="string"&&K.trim().length>0):[],k=t.milestone_ids??t.milestoneIds,w=Array.isArray(k)?k.filter(K=>typeof K=="string"&&K.trim().length>0):[],x=lt(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),_=lt(t,["initiative_title","initiativeTitle"]),v=lt(t,["initiative_status","initiativeStatus"]),g=nr(e),C=lt(t,["workstream_title","workstreamTitle"]),U=lt(t,["workstream_status","workstreamStatus"]),de=lt(t,["task_title","taskTitle"]),ee=lt(t,["milestone_title","milestoneTitle"]),pe=lt(t,["domain"]),ie=lt(t,["phase","slice_phase","slicePhase"]),se=lt(t,["next_step","nextStep"]),oe=Rp(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),we=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,Ne=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,Q=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,je=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,Me=typeof t.error=="string"?t.error:null,B=Pn(t.artifacts??t.artifact_count??t.artifactCount),I=Pn(t.decisions??t.decision_count??t.decisionCount),T=il(t),ce=t.decisions_needed??t.decisionsNeeded;let ge=Pn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),J=Pn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((ge===null||J===null)&&Array.isArray(ce)){let K=0,te=0;for(const Re of ce){if(!Re||typeof Re!="object"||Array.isArray(Re))continue;Re.blocking===!1?te+=1:K+=1}ge===null&&(ge=K),J===null&&(J=te)}ge===null&&I!==null&&e.decisionRequired===!0&&(ge=I>0?I:1),J===null&&I!==null&&ge!==null&&(J=Math.max(0,I-ge)),ge===null&&I!==null&&J!==null&&(ge=Math.max(0,I-J));const he=Pn(t.status_updates_applied??t.statusUpdatesApplied),V=Pn(t.task_updates??t.taskUpdates),G=Pn(t.milestone_updates??t.milestoneUpdates),le=he??(V!==null||G!==null?(V??0)+(G??0):null),ae=Pn(t.status_updates_buffered??t.statusUpdatesBuffered),ve=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,re=ts(t.token_budget??t.tokenBudget),Pe=ts(t.tokens_used??t.tokensUsed),Se=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)??y,P=y&&!a.agentName?null:Se;return{event:s,agentId:P,agentName:E,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:x,domain:pe,phase:ie,progressPct:oe,nextStep:se,requiredSkills:h,initiativeStatus:v,initiativeTitle:_,workstreamId:g,workstreamStatus:U,workstreamTitle:C,taskTitle:de,milestoneTitle:ee,taskIds:f,milestoneIds:w,parsedStatus:we,hasOutput:Ne,artifacts:B,decisions:I,blockingDecisions:ge,nonBlockingDecisions:J,decisionIds:T.decisionIds,blockingDecisionIds:T.blockingDecisionIds,nonBlockingDecisionIds:T.nonBlockingDecisionIds,statusUpdatesApplied:le,statusUpdatesBuffered:ae,stopReason:ve,tokenBudget:re,tokensUsed:Pe,logPath:Q,outputPath:je,error:Me}}function fo(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function Dp(e){const t=sa(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),h=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),y=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,b=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,f=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,k=typeof s.provider=="string"?s.provider:null,w=typeof s.model=="string"?s.model:null,x=typeof s.domain=="string"?s.domain:null,_=s.required_skills??s.requiredSkills,v=Array.isArray(_)?_.filter(C=>typeof C=="string"&&C.trim().length>0):[];return!!c||!!(l||d||u)||!!y||!!(f||k||w||x)||v.length>0?{pluginVersion:c,skillPack:l||d||u||h?{name:l,version:d,checksum:u,source:h}:null,kickoffContextHash:y,kickoffContextSource:b,modelTier:f,provider:k,model:w,domain:x,requiredSkills:v}:null}function ol(e){if(!e)return null;const t=bt(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 Lp(e){const t=bt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=ol(e);if(!r&&!s)return null;let i="Artifact";e.type==="artifact_created"?i="Created artifact":(r==null?void 0:r.source)==="toolOutput"||(r==null?void 0:r.source)==="toolOutputs"?i="Tool output":(r==null?void 0:r.source)==="toolResult"||(r==null?void 0:r.source)==="toolResults"?i="Result":(r==null?void 0:r.source)==="output"||(r==null?void 0:r.source)==="outputs"?i="Output":s&&(i="Registered artifact");let a="";if(r){const c=r.value;if(typeof c=="string")a=c.length>80?c.slice(0,80)+"…":c;else if(Array.isArray(c))a=`${c.length} item${c.length===1?"":"s"}`;else if(c&&typeof c=="object"){const l=Object.keys(c);a=l.length<=4?l.join(", "):`${l.length} fields`}}return{label:i,preview:a,hasRegisteredId:s}}function Fp(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 ll(e){const t=bt(e);if(!t)return[];const s=[],r=new Set,i=(c,l)=>{if(typeof l!="string")return;const d=l.trim();if(!d||!Fp(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,h]of Object.entries(c)){const y=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(h))for(const k of h)i(y,k);else i(y,h);h&&typeof h=="object"&&!Array.isArray(h)&&a(h,y,d+1)}};return a(t),s}function lt(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 $p(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 Pp(e,t){if(!e)return null;const s=bt(e);if(!s)return null;const r=lt(s,["event","event_name","eventName"]),i=ks(s.spawn_guard),a=ks(i==null?void 0:i.checks),c=ks((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=lt(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=$p(l),u=ts(c==null?void 0:c.current)??d.domainCurrent,h=ts(c==null?void 0:c.max)??d.domainMax,y=d.totalCurrent,b=d.totalMax,f=typeof(c==null?void 0:c.passed)=="boolean"?c.passed:null,k=((r==null?void 0:r.includes("rate_limited"))??!1)||!!(l&&/rate limit/i.test(l))||f===!1;return!((r==null?void 0:r.includes("spawn_guard"))??!1)&&!k&&!i&&!l?null:{event:r,blockedReason:l,domain:lt(s,["domain"])??lt(i,["domain","task_domain"]),modelTier:lt(s,["spawn_guard_model_tier","model_tier"])??lt(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:h,totalCurrent:y,totalMax:b,retryAt:lt(s,["next_retry_at","nextRetryAt"]),retryInMs:ts(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:k}}function Op(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 ${ot(i)}`}return null}function Bp(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 Ci(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&&Bp(r)?a:r??a;if(c)return rr(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"?rr(i):sr.test(i)||qp.test(i)||sl.test(i)||rl.test(i)?"OrgX":rr(i)}const sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qp=/^[0-9a-f]{20,}$/i,zp=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function Qr(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(zp)??[]){const l=c.trim().toLowerCase();sr.test(l)&&t.add(l)}typeof e.runId=="string"&&sr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=bt(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();sr.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();sr.test(d)&&t.add(d)}}return t}function Wp(e){if(!e)return[];const t=bt(e);return il(t).decisionIds}function Up(e,t,s){if(!e)return[];const r=bt(e),i=lt(r,["workstream_id","workstreamId"]),a=lt(r,["initiative_id","initiativeId"]),c=Qr(e);if(!i&&!a&&c.size===0)return[];const l=es(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const f=bt(b);if(!f)continue;const k=lt(f,["workstream_id","workstreamId"]),w=lt(f,["initiative_id","initiativeId"]),x=Qr(b),_=c.size>0&&Array.from(c).some(ee=>x.has(ee)),v=!!i&&!!k&&i===k;if(!_&&!v&&!(!!a&&!!w&&a===w))continue;const C=ll(b).filter(ee=>!s.has(ee.path));if(C.length===0)continue;const U=Math.abs(es(b.timestamp)-l);if(!_&&U>7200*1e3)continue;const de=_?0:v?1:2;!_&&U>1200*1e3||d.push({priority:de,delta:U,evidence:C})}if(d.length===0)return[];d.sort((b,f)=>b.priority!==f.priority?b.priority-f.priority:b.delta-f.delta);const u=[],h=new Set(s),y=d[0].priority;for(const b of d){if(b.priority!==y)break;for(const f of b.evidence)if(!h.has(f.path)&&(h.add(f.path),u.push({key:`related.${f.key}`,path:f.path}),u.length>=8))return u}return u}function Hp(e,t){if(!e)return null;const s=bt(e),r=lt(s,["workstream_id","workstreamId"]),i=lt(s,["initiative_id","initiativeId"]),a=Qr(e);if(!r&&!i&&a.size===0)return null;const c=es(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const h=al(u);if(!h)continue;const y=bt(u);if(!y)continue;const b=lt(y,["workstream_id","workstreamId"]),f=lt(y,["initiative_id","initiativeId"]),k=Qr(u),w=a.size>0&&Array.from(a).some(U=>k.has(U)),x=!!r&&!!b&&r===b;if(!w&&!x&&!(!!i&&!!f&&i===f))continue;const v=Math.abs(es(u.timestamp)-c);if(!w&&v>1200*1e3)continue;const g=w?"shared_id":x?"workstream":"initiative",C=g==="shared_id"?0:g==="workstream"?1:2;l.push({priority:C,delta:v,relation:g,detail:h})}if(l.length===0)return null;l.sort((u,h)=>u.priority!==h.priority?u.priority-h.priority:u.delta-h.delta);const d=l[0];return{detail:d.detail,relation:d.relation}}function _n(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function ti(e){const t=_n(e);return["done","complete","completed","stopped","success"].includes(t)}function Vp(e){const t=_n(e.parsedStatus),s=_n(e.event);return t==="failed"||t==="error"||t==="timed_out"||t==="timeout"||t==="aborted"||s.includes("error")||s.includes("timeout")?"critical":t==="blocked"||e.stopReason==="blocked"?"warning":ti(t)||e.stopReason==="completed"?"positive":"neutral"}function Kp(e){if(ti(e.parsedStatus)||e.stopReason==="completed")return 100;const t=_n(e.parsedStatus);if(t==="blocked"||t==="error"||t==="failed")return 100;const s=e.event;return s==="auto_continue_started"?3:s==="next_up_manual_dispatch_started"?8:s==="autopilot_slice_dispatched"?14:s==="autopilot_slice_status_updates_buffered"?72:s==="autopilot_slice_result"?92:s==="autopilot_autofix_scheduled"?6:s==="autopilot_autofix_executed"?18:s==="autopilot_autofix_skipped"||s==="auto_continue_stopped"?100:s.startsWith("autopilot_slice")?56:null}function cl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Gp(e,t){if(!e&&t===null)return null;const s=e?Vp(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=cl(e.progressPct)??0,d=r(l);return{pct:l,source:"metadata",label:d?i:"Reported by slice metadata",tone:s,terminalStop:d}}if(t!==null){const l=r(t);return{pct:t,source:"session",label:l?i:"Derived from runtime session",tone:s,terminalStop:l}}if(!e)return null;const a=Kp(e);if(a===null)return null;const c=r(a);return{pct:a,source:"lifecycle",label:c?i:"Estimated from dispatch lifecycle",tone:s,terminalStop:c}}function Xp(e,t,s,r=null){var _;const i=bt(e),a=_n(lt(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=_n(e.state??e.phase??e.kind??e.type),l=_n((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=_n((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=lt(i,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,h=Math.max(0,(s==null?void 0:s.decisions)??(t==null?void 0:t.decisions)??0),y=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,h):0)),b=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,h-y)),f=e.decisionRequired===!0||e.type==="decision_requested"||y>0||l==="needs_decision"&&b===0,k=e.type==="run_completed"||e.type==="milestone_completed"||ti(l)||d==="completed",w=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),x=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:_t(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:"Budget exhausted",summary:_t(e.title)??"Autopilot stopped because the configured token budget was exhausted.",hint:"Restart with an explicit token budget or a narrower workstream scope.",tone:"warning"};if(d==="completed")return{label:"Completed",summary:_t(e.title)??"Autopilot stopped because the current dispatch scope is complete.",hint:null,tone:"positive"};if(d==="stopped")return{label:"Stopped",summary:_t(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:f?"Needs decision":"Blocked",summary:_t(e.title)??(f?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:f?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:f?"warning":"critical"};if(d==="error")return{label:"Error",summary:_t(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 v=String((i==null?void 0:i.old_state)??""),g=String((i==null?void 0:i.new_state)??""),C=String((i==null?void 0:i.reason)??"");return g==="running"?{label:"Autopilot activated",summary:`State changed from ${v} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:g==="blocked"||g==="error"?{label:g==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${v} to ${g}${C?`: ${C}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${v} → ${g}${C?` (${C})`:""}.`,hint:null,tone:"neutral"}}if(w)return{label:"Rate limited",summary:u?_t(u)??"Spawn guard rate limit reached.":"Spawn guard rate limit reached.",hint:"Adjust limits in settings or wait for the window to reset before retrying.",tone:"warning"};if(x)return{label:"Spawn guard blocked",summary:u?_t(u)??"Spawn guard denied dispatch.":"Spawn guard denied dispatch.",hint:"Review guard checks, then retry or approve an override.",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?_t(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const v=f||(((_=r.nextAction)==null?void 0:_.toLowerCase().includes("decision"))??!1);return{label:v?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(v?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:v?"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:"Blocked",summary:u?_t(u)??"Execution is blocked.":"Execution is blocked and needs intervention.",hint:f?"Resolve the pending decision, then resume the session.":"Open the session and retry after fixing the blocker.",tone:"critical"}:f?{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"}:k&&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"}:k?{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 dl(e){if(typeof e=="string")return n.jsx(Vr,{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:dl(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:ot(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 _t(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=or(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:ot(t)}const Qp=[/^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 Jp(e){return Qp.some(t=>t.test(e))}function Jr(e){const t=e.title??"";return Jp(t)?/Exec failed|SIGKILL|SIGTERM|Error: /i.test(t)?{title:"Execution failed",isSystem:!0}:/outbox replay|changeset replayed/i.test(t)?{title:"Changes synced",isSystem:!0}:/execution policy/i.test(t)?{title:"System directive",isSystem:!0}:{title:"System event",isSystem:!0}:{title:ot(t)||ot(Xr(e.type)),isSystem:!1}}const Yp=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 ar(e){const t=bt(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&&Yp.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function ho(e){var d;if(!e||!ar(e))return null;const t=bt(e),s=Pn((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=lt(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),c=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",l=a?` for ${ot(a).toLowerCase()}`:"";return`${c}${l} were synced from local replay.`}function Mi(e){if(!ar(e))return null;const t=bt(e);if(!t)return null;const s=lt(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=lt(t,["event","event_name","eventName"])??"",i=lt(t,["changeset_id","changesetId"])??"",a=lt(t,["entity_type","entityType"])??"",c=lt(t,["entity_id","entityId"])??"",l=Hi(e)??"",d=Jr(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function Zp(e){if(!e)return null;const t=bt(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 go(e){return e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1")}function xo(e,t){const r=(_t(t??e.summary)??_t(e.description)??ot(e.title||Xr(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(),i=r.split(`
211
- `).map(c=>go(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let a=i[0]??go(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const ef=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:h=null,timeFilterId:y="live",onTimeFilterChange:b,customTimeRange:f={startIso:null,endIso:null},onCustomTimeRangeChange:k,hasMore:w=!1,isLoadingMore:x=!1,onLoadMore:_,onClearSelection:v,onClearWorkstreamFilter:g,onClearAgentFilter:C,onFocusRunId:U,onOpenDecision:de,requestedActivityItemId:ee=null,onActivityItemRequestHandled:pe,onPlayNextUp:ie,onStartAutopilot:se,onPauseWorkstream:oe,onCreateInitiative:we,onOpenMissionControl:Ne,onOpenSettings:Q,workspaceId:je=null,chatSnapshot:Me,onRefreshData:B,isLoading:I=!1}){var Be;const T=zn(),{open:ce}=Xo(),[ge,J]=o.useState("all"),[he,V]=o.useState(!1),[G,le]=o.useState(!1),[ae,ve]=o.useState(""),[re,Pe]=o.useState(new Set),[Se,E]=o.useState({}),[P,K]=o.useState("newest"),[te,Re]=o.useState(!1),[qe,Ee]=o.useState(!1),[M,q]=o.useState(ji),[ne,me]=o.useState(null),[Te,et]=o.useState(null),[tt,Ce]=o.useState(!1),[Ye,ze]=o.useState(1),[dt,at]=o.useState("structured"),[nt,xe]=o.useState(null),[Xe,ke]=o.useState("feed"),[W,$e]=o.useState(null),[z,Y]=o.useState(null),[Ae,De]=o.useState(!1),[Le,Oe]=o.useState(null),[_e,He]=o.useState(null),[st,Ve]=o.useState(!1),[Et,Je]=o.useState(null),[jt,Ut]=o.useState(!1),Bt=o.useRef(Date.now()),yn=o.useRef(null),bn=o.useRef(null),rs=o.useRef(null),ht=o.useRef(null),Ot=o.useRef(null),[Nt,Mn]=o.useState(()=>_r(f.startIso)),[ut,En]=o.useState(()=>_r(f.endIso)),[Gt,Lt]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Zt=o.useMemo(()=>To(y),[y]),wn=o.useMemo(()=>_r(f.startIso),[f.startIso]),an=o.useMemo(()=>_r(f.endIso),[f.endIso]),is=o.useMemo(()=>!Nt||!ut?!1:ut.getTime()>=Nt.getTime(),[ut,Nt]),as=o.useMemo(()=>y!=="custom"?Zt.label:wn&&an?`${Cr(wn)} - ${Cr(an)}`:"Custom range",[an,wn,y,Zt.label]);o.useEffect(()=>{Mn(wn),En(an)},[an,wn]),o.useEffect(()=>{if(typeof window>"u")return;const m=()=>Lt(window.innerWidth<=640);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),o.useEffect(()=>{const j=()=>{Bt.current=Date.now()};window.addEventListener("pointerdown",j),window.addEventListener("keydown",j);const N=setInterval(()=>{Date.now()-Bt.current>3e5&&Ut(!0)},3e4);return()=>{window.removeEventListener("pointerdown",j),window.removeEventListener("keydown",j),clearInterval(N)}},[]);const on=o.useMemo(()=>{const m=s.filter(O=>O.status==="completed").length,j=s.filter(O=>O.status==="blocked"||O.status==="failed").length,N=t.filter(O=>{var be;return O.type==="decision_requested"&&((be=O.metadata)==null?void 0:be.status)==="pending"}).length;return{completed:m,blocked:j,decisions:N}},[s,t]),ln=o.useMemo(()=>{const m=new Map;for(const j of s)m.set(j.runId,j.title),m.set(j.id,j.title);return m},[s]),qt=o.useMemo(()=>{const m=new Map;for(const j of s)j.status&&(m.set(j.runId,j.status),m.set(j.id,j.status));return m},[s]),Wn=o.useMemo(()=>{var j;const m=new Map;for(const N of s){const O={status:N.status??null,phase:N.phase??null,state:N.state??null,blockerCount:Array.isArray(N.blockers)?N.blockers.length:0,blockerReason:N.blockerReason??((j=N.blockerDiagnostics)==null?void 0:j.reason)??null};m.set(N.runId,O),m.set(N.id,O)}return m},[s]),vn=o.useMemo(()=>{const m=new Map;for(const j of r){const N={status:j.status??null,blockingDecisions:Math.max(0,j.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(j.decisionCount??0)-(j.blockingDecisionCount??0)),updatedEpoch:es(j.updatedAt??j.lastEventAt??j.startedAt??null)},O=[j.runId,j.sliceRunId].filter(be=>typeof be=="string"&&be.trim().length>0).map(be=>be.trim());for(const be of O){const Ue=m.get(be);(!Ue||N.updatedEpoch>=Ue.updatedEpoch)&&m.set(be,N)}}return m},[r]),Un=o.useMemo(()=>{const m=new Map;for(const j of s){const N=cl(j.progress);N!==null&&(m.set(j.runId,N),m.set(j.id,N))}return m},[s]),kn=o.useMemo(()=>{const m=new Map;for(const j of s)!j.agentId||!j.agentName||m.set(j.agentId,j.agentName);return m},[s]),cn=o.useMemo(()=>{const m=new Map;for(const j of s){const N=j.workstreamId??null;m.set(j.runId,N),m.set(j.id,N)}return m},[s]),Hn=o.useMemo(()=>{const m=new Map;for(const j of i)m.set(j.id,j.name);return m},[i]),It=o.useMemo(()=>{const m=new Map;for(const j of i)for(const N of j.workstreams??[])m.set(N.id,N.name);return m},[i]);o.useMemo(()=>{const m=[...s];return m.sort((j,N)=>{const O=es(j.updatedAt??j.lastEventAt??j.startedAt??null);return es(N.updatedAt??N.lastEventAt??N.startedAt??null)-O}),m},[s]);const dn=o.useMemo(()=>t.map(m=>{const j=Hi(m),N=_p(m),O=bt(m),be=j?Wn.get(j)??null:null,Ue=j?vn.get(j)??null:null,Qe=Mm({sessionStatus:(be==null?void 0:be.status)??(j?qt.get(j)??null:null),sessionPhase:(be==null?void 0:be.phase)??null,sessionState:(be==null?void 0:be.state)??null,sliceStatus:(Ue==null?void 0:Ue.status)??null,activityType:m.type,activityStatus:lt(O,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:lt(O,["stop_reason","stopReason"]),decisionRequired:m.decisionRequired??!1,blockingDecisionCount:Ls(O,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ue==null?void 0:Ue.blockingDecisions)??0,nonBlockingDecisionCount:Ls(O,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ue==null?void 0:Ue.nonBlockingDecisions)??0,blockerCount:(be==null?void 0:be.blockerCount)??0,blockerReason:(be==null?void 0:be.blockerReason)??null}),yt=Ep(N,Qe),fn=[m.title,m.description,m.summary,m.agentName,wp(O)].filter(Wt=>typeof Wt=="string"&&Wt.length>0).join(" ").toLowerCase(),ft=O==null?void 0:O.scope,ct=ft==="milestone"||ft==="workstream"?ft:void 0;return{item:m,bucket:N,userState:yt.state,userStateWhy:yt.why,canonicalProjection:Qe,runId:j,timestampEpoch:es(m.timestamp),searchText:fn,scopeGroupId:ct?j??null:null,scope:ct}}),[t,Wn,qt,vn]),jn=o.useMemo(()=>{let m=0;for(const j of dn)m=Math.max(m,j.timestampEpoch);return m<=0?!1:Date.now()-m<6e4},[dn]),Ht=o.useMemo(()=>new Set(c.filter(m=>m&&m.trim().length>0)),[c]),Tt=Ht.size>0,R=o.useMemo(()=>lr.filter(m=>["live","24h","7d","all"].includes(m.id)),[]),X=o.useMemo(()=>{if(!Tt)return null;for(const m of Ht){const j=s.find(N=>N.runId===m||N.id===m);if(j)return j}return null},[Tt,Ht,s]),fe=o.useMemo(()=>Tt?X!=null&&X.runtimeProvider?{id:bp(X.runtimeProvider)}:Zn(X==null?void 0:X.agentId,X==null?void 0:X.agentName,X==null?void 0:X.title,X==null?void 0:X.lastEventSummary,X==null?void 0:X.runtimeClient,l):Zn(),[X,Tt,l]),Fe=o.useMemo(()=>h?Zn(h):Zn(),[h]),{filtered:Ke,filteredTotal:wt,hiddenCount:Ze,hiddenSyncCount:os}=o.useMemo(()=>{const m=[];let j=0,N=0;const O=new Set,be=ae.trim().toLowerCase();for(const ft of dn){const ct=ft.runId;if(Tt&&(!ct||!Ht.has(ct)))continue;if(d){const hn=nr(ft.item),Cs=ct?cn.get(ct)??null:null;if((hn??Cs)!==d)continue}const Wt=ir(ft.item);if(h&&Wt.agentName!==h)continue;const fs=Mi(ft.item);if(fs){if(O.has(fs)){N+=1;continue}if(O.add(fs),!he){N+=1;continue}}else if(!he&&ar(ft.item)){N+=1;continue}if(!(ge==="completed"&&ft.userState!=="completed")&&!(ge==="needs_attention"&&ft.userState!=="needs_input"&&ft.userState!=="issue")&&!(ge==="in_progress"&&ft.userState!=="in_progress")){if(be.length>0){const hn=ct?ln.get(ct)??ct:"";if(!`${ft.searchText} ${hn.toLowerCase()}`.includes(be))continue}m.length<io?m.push(ft):j+=1}}const Ue=[...m].sort((ft,ct)=>{const Wt=ct.timestampEpoch-ft.timestampEpoch;return P==="newest"?Wt:-Wt}),Qe=Math.min(Math.max(1,Math.min(ro,M)),Ue.length),yt=Ue.slice(0,Qe),fn=Ue.length+j;return{filtered:yt,filteredTotal:fn,hiddenCount:Math.max(0,fn-yt.length),hiddenSyncCount:N}},[ge,h,dn,Tt,ae,ln,M,d,Ht,cn,he,P]),un=o.useMemo(()=>{const m=new Map;for(const N of Ke){const O=Cp(N.item.timestamp),be=m.get(O);be?be.push(N):m.set(O,[N])}return Array.from(m.keys()).sort((N,O)=>{const be=Number(O)-Number(N);return P==="newest"?be:-be}).map(N=>({key:N,label:Mp(N),items:m.get(N)??[]}))},[Ke,P]),qs=o.useMemo(()=>un.map(m=>{const j=new Map;for(const N of m.items){const O=Jr(N.item).title.trim().toLowerCase(),be=Mi(N.item),Ue=be?`${N.item.type}::sync::${be}`:`${N.item.type}::${O}`,Qe=j.get(Ue);Qe?(Qe.count+=1,Qe.firstTimestamp=Math.min(Qe.firstTimestamp,N.timestampEpoch),Qe.allItems.push(N),N.timestampEpoch>Qe.representative.timestampEpoch&&(Qe.representative=N)):j.set(Ue,{key:Ue,representative:N,count:1,firstTimestamp:N.timestampEpoch,allItems:[N]})}return{...m,clusters:Array.from(j.values())}}),[un]),xt=o.useCallback(m=>{Pe(j=>{const N=new Set(j);return N.has(m)?N.delete(m):N.add(m),N}),E(j=>{if(Object.prototype.hasOwnProperty.call(j,m)){const N={...j};return delete N[m],N}return{...j,[m]:tr}})},[]),mn=o.useCallback((m,j)=>{E(N=>{const O=N[m]??tr,be=Math.min(j,O+tr);return be===O?N:{...N,[m]:be}})},[]),Vn=o.useCallback(()=>{!k||!b||!Nt||!ut||ut.getTime()<Nt.getTime()||(k({startIso:Nt.toISOString(),endIso:ut.toISOString()}),b("custom"),Ee(!1))},[ut,Nt,k,b]),ls=o.useCallback(()=>{Mn(null),En(null),k==null||k({startIso:null,endIso:null}),y==="custom"&&(b==null||b("live"))},[k,b,y]),pn=o.useMemo(()=>Math.min(ro,Math.min(io,wt)),[wt]);o.useEffect(()=>{q(ji),Pe(new Set),E({})},[ge,h,Tt,ae,d,he,P,y]),o.useEffect(()=>{if(!te)return;const m=N=>{var be;const O=N.target;O instanceof Node&&((be=yn.current)!=null&&be.contains(O)||Re(!1))},j=N=>{N.key==="Escape"&&Re(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",j),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",j)}},[te]),o.useEffect(()=>{if(!qe)return;const m=N=>{var be;const O=N.target;O instanceof Node&&((be=bn.current)!=null&&be.contains(O)||Ee(!1))},j=N=>{N.key==="Escape"&&Ee(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",j),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",j)}},[qe]);const Fn=o.useRef(_);Fn.current=_;const Tn=o.useRef(w);Tn.current=w;const vt=o.useRef(x);vt.current=x,o.useEffect(()=>{const m=rs.current,j=ht.current;if(!m||!j)return;const N=new IntersectionObserver(O=>{var Ue;if(O.some(Qe=>Qe.isIntersecting)){if(Ke.length<pn){q(Qe=>Math.min(pn,Math.max(Qe,ji)+yp));return}Tn.current&&!vt.current&&((Ue=Fn.current)==null||Ue.call(Fn))}},{root:m,rootMargin:"0px 0px 600px 0px"});return N.observe(j),()=>N.disconnect()},[Ke.length,pn]);const zt=o.useMemo(()=>ne?Ke.findIndex(m=>m.item.id===ne):-1,[ne,Ke]),F=zt>=0?Ke[zt]:null,cs=o.useMemo(()=>{var j;const m=new Map;for(const N of a){const O=(j=N==null?void 0:N.sliceRunId)==null?void 0:j.trim();!O||m.has(O)||m.set(O,N)}return m},[a]),Vt=o.useMemo(()=>{if(!F)return null;const m=F.runId??Hi(F.item);return m?cs.get(m)??null:null},[F,cs]),Xt=o.useMemo(()=>ol((F==null?void 0:F.item)??null),[F]),Rn=o.useMemo(()=>Ai((F==null?void 0:F.item)??null),[F]),Ns=o.useMemo(()=>al((F==null?void 0:F.item)??null),[F]),ds=o.useMemo(()=>Ns?null:Hp((F==null?void 0:F.item)??null,t),[Ns,F,t]),Ge=o.useMemo(()=>F?uo(F.item):null,[F]),Dn=o.useMemo(()=>Ge?Ge.executor??Ge.requester:null,[Ge]),Z=Ns??(ds==null?void 0:ds.detail)??null,Is=o.useMemo(()=>{var m,j;return Ci((Z==null?void 0:Z.requesterAgentName)??((m=Ge==null?void 0:Ge.requester)==null?void 0:m.name)??null,(Z==null?void 0:Z.requesterAgentId)??((j=Ge==null?void 0:Ge.requester)==null?void 0:j.id)??null,kn)},[Z,Ge,kn]),Kn=o.useMemo(()=>Np(Is),[Is]),zs=o.useMemo(()=>{var j,N;const m=Ci((Z==null?void 0:Z.agentName)??((j=Ge==null?void 0:Ge.executor)==null?void 0:j.name)??null,(Z==null?void 0:Z.agentId)??((N=Ge==null?void 0:Ge.executor)==null?void 0:N.id)??null,kn);return m==="—"?(Ge==null?void 0:Ge.primaryLabel)??"Codex":m},[Z,Ge,kn]),dr=o.useMemo(()=>F!=null&&F.runId?Un.get(F.runId)??null:null,[F,Un]),Ct=o.useMemo(()=>Gp(Z,dr),[Z,dr]),D=o.useMemo(()=>{const m=Z;if(!m)return null;const j=m.initiativeId??(F==null?void 0:F.item.initiativeId)??null,N=j?i.find(hn=>hn.id===j)??null:null,O=m.initiativeTitle??(N==null?void 0:N.name)??null,be=m.initiativeStatus??(N==null?void 0:N.status)??null,Ue=(N==null?void 0:N.workstreams)??[],Qe=Ue.length>0?Ue.length:null,yt=Qe!==null?Ue.filter(hn=>ti(hn.status)).length:null,fn=Qe&&yt!==null?Math.round(yt/Qe*100):null,ft=m.workstreamId??null,ct=ft&&Ue.length>0?Ue.find(hn=>hn.id===ft)??null:null,Wt=m.workstreamTitle??(ct==null?void 0:ct.name)??(ft?It.get(ft)??null:null),fs=m.workstreamStatus??(ct==null?void 0:ct.status)??null;return{initiativeId:j,initiativeTitle:O,initiativeStatus:be,totalInitiativeWorkstreams:Qe,doneInitiativeWorkstreams:yt,initiativeWorkstreamPct:fn,workstreamId:ft,workstreamTitle:Wt,workstreamStatus:fs,taskTitle:m.taskTitle,milestoneTitle:m.milestoneTitle,scopedTaskCount:m.taskIds.length,scopedMilestoneCount:m.milestoneIds.length,statusUpdatesApplied:m.statusUpdatesApplied,statusUpdatesBuffered:m.statusUpdatesBuffered,artifacts:m.artifacts,decisions:m.decisions,blockingDecisions:m.blockingDecisions,nonBlockingDecisions:m.nonBlockingDecisions,tokensUsed:m.tokensUsed,tokenBudget:m.tokenBudget,nextStep:m.nextStep,phase:m.phase,stopReason:m.stopReason,parsedStatus:m.parsedStatus}},[Z,F,i,It]),At=o.useMemo(()=>F?Xp(F.item,Z,D?{decisions:D.decisions,blockingDecisions:D.blockingDecisions,nonBlockingDecisions:D.nonBlockingDecisions,stopReason:D.stopReason,parsedStatus:D.parsedStatus}:null,F.canonicalProjection??null):null,[Z,F,D]),us=o.useMemo(()=>{if(!D)return[];const m=[];At&&m.push({label:"Status",value:At.label}),D.scopedTaskCount>0&&m.push({label:"Tasks",value:D.scopedTaskCount}),D.scopedMilestoneCount>0&&m.push({label:"Milestones",value:D.scopedMilestoneCount});const j=D.artifacts??0;j>0&&m.push({label:"Artifacts",value:j});const N=D.decisions??0;N>0&&m.push({label:"Decisions",value:N}),D.blockingDecisions&&D.blockingDecisions>0&&m.push({label:"Blocking",value:D.blockingDecisions,tone:"critical"}),D.stopReason&&m.push({label:"Stop reason",value:Ks(D.stopReason)??ot(D.stopReason)});const O=Ml(D.tokensUsed,D.tokenBudget);return O&&m.push({label:"Token usage",value:O}),m},[D,At]),As=o.useMemo(()=>{const m=new Set;for(const j of Wp((F==null?void 0:F.item)??null))m.add(j);for(const j of(Z==null?void 0:Z.decisionIds)??[])m.add(j);for(const j of(Z==null?void 0:Z.blockingDecisionIds)??[])m.add(j);for(const j of(Z==null?void 0:Z.nonBlockingDecisionIds)??[])m.add(j);return Array.from(m)},[Z,F]),Ss=o.useMemo(()=>de?As.length>0||(F==null?void 0:F.item.decisionRequired)===!0||((D==null?void 0:D.blockingDecisions)??0)>0?!0:(At==null?void 0:At.label)==="Needs decision":!1,[As,F,D,At,de]),Ws=o.useMemo(()=>Ct?Ct.tone==="positive"?L.lime:Ct.tone==="warning"?L.amber:Ct.tone==="critical"?L.red:L.teal:L.teal,[Ct]),ur=(Ct==null?void 0:Ct.terminalStop)===!0,it=o.useMemo(()=>Dp(bt((F==null?void 0:F.item)??null)),[F]),Qt=o.useMemo(()=>bt((F==null?void 0:F.item)??null),[F]),gt=o.useMemo(()=>Pp((F==null?void 0:F.item)??null,Z),[Z,F]),Us=o.useMemo(()=>{if(!(gt!=null&&gt.retryAt))return null;const m=new Date(gt.retryAt);if(!Number.isFinite(m.getTime()))return null;const j=m.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),N=St(gt.retryAt);return N?`${j} (${N})`:j},[gt]),mr=o.useMemo(()=>F?ir(F.item):{agentId:null,agentName:null},[F]),Hs=o.useMemo(()=>po(ks(F==null?void 0:F.item.metadata)??void 0),[F]);o.useMemo(()=>po(Qt),[Qt]);const ms=o.useMemo(()=>{const m=ll((F==null?void 0:F.item)??null);return m.length>0?m:Up((F==null?void 0:F.item)??null,t,new Set)},[F,t]),pr=o.useMemo(()=>{if(ms.length===0)return null;const m=ms[0];return m?fo(m.path):null},[ms]),_s=o.useMemo(()=>{const m=_t(nt);if(m)return m;const j=ho((F==null?void 0:F.item)??null);return j||(_t(F==null?void 0:F.item.summary)??_t(F==null?void 0:F.item.description))},[nt,F]),ps=o.useMemo(()=>F?ar(F.item):!1,[F]),Ft=o.useMemo(()=>{if(!Z||!F)return null;const m=Z.initiativeId??F.item.initiativeId??null,j=Z.workstreamId??nr(F.item);if(!m||!j)return null;const N=_n((D==null?void 0:D.parsedStatus)??Z.parsedStatus),O=_n((D==null?void 0:D.stopReason)??Z.stopReason),be=Math.max(0,(D==null?void 0:D.blockingDecisions)??Z.blockingDecisions??(F.item.decisionRequired?1:0)),Ue=Math.max(0,(D==null?void 0:D.nonBlockingDecisions)??Z.nonBlockingDecisions??0),Qe=N==="blocked"||N==="error"||N==="failed"||O==="blocked"||O==="error"||F.item.type==="blocker_created",yt=!Qe&&be===0&&Ue>0&&(N==="needs_decision"||N==="completed"||O==="completed");return!Qe&&!yt?null:{initiativeId:m,workstreamId:j,runId:F.runId??null,event:Z.event,requestedByAgentId:Z.requesterAgentId??F.item.requesterAgentId??null,requestedByAgentName:Z.requesterAgentName??F.item.requesterAgentName??null,actionLabel:Qe?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Qe?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Qe}},[Z,F,D]),Gn=o.useCallback(()=>{me(null)},[]),fr=o.useCallback(async(m,j)=>{if(j){He(null),Oe(m);try{await j()}catch(N){He(N instanceof Error?N.message:"Action failed")}finally{Oe(N=>N===m?null:N)}}},[]),Xn=o.useCallback(async()=>{var m;if(!(!Ft||st)){Ve(!0),Je(null);try{const j=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:Ft.initiativeId,workstreamId:Ft.workstreamId,runId:Ft.runId,event:Ft.event,requestedByAgentId:Ft.requestedByAgentId,requestedByAgentName:Ft.requestedByAgentName,graceMs:1e4})}),N=await j.json().catch(()=>null);if(!j.ok||(N==null?void 0:N.ok)!==!0)throw new Error((N==null?void 0:N.error)||`Request failed (${j.status})`);const O=(m=N==null?void 0:N.scheduled)!=null&&m.dueAt?new Date(N.scheduled.dueAt):null,be=O&&Number.isFinite(O.getTime())?O.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Je(be?`Scheduled. Auto action starts by ${be} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(j){const N=j instanceof Error?j.message:"Failed to schedule auto-fix";Je(Cn(N)||N)}finally{Ve(!1)}}},[Ft,st]);o.useEffect(()=>{if(!Te)return;const m=window.setTimeout(()=>et(null),2e3);return()=>window.clearTimeout(m)},[Te]),o.useEffect(()=>{He(null)},[ge,ae,y]),o.useEffect(()=>{if(!ee){Ot.current=null;return}const m=ee.trim();!m||Ot.current===m||!t.some(N=>N.id===m)||(Ot.current=m,le(!1),J("all"),ve(""),ze(1),me(m),pe==null||pe(m))},[t,pe,ee]);const Nn=o.useCallback(async(m,j)=>{if(j)try{await navigator.clipboard.writeText(j),et(`${m} copied`)}catch{et("Copy failed")}},[]);o.useEffect(()=>{at("structured"),Ce(!1),Ve(!1),Je(null)},[ne]),o.useEffect(()=>{xe(null),ke("feed");const m=Zp((F==null?void 0:F.item)??null);if(!m||Mt())return;const j=new URLSearchParams({turnId:m.turnId});m.sessionKey&&j.set("sessionKey",m.sessionKey),m.runId&&j.set("run",m.runId);const N=new AbortController;return fetch(`/orgx/api/live/activity/detail?${j.toString()}`,{method:"GET",signal:N.signal}).then(async O=>{var Ue;return O.ok?((Ue=(await O.json()).detail)==null?void 0:Ue.summary)??null:(O.status===404&&ke("missing"),null)}).then(O=>{typeof O=="string"&&O.trim().length>0?(xe(O),ke("local")):ke("missing")}).catch(O=>{O instanceof DOMException&&O.name==="AbortError"||ke("missing")}),()=>N.abort()},[F]),o.useEffect(()=>{$e(null),Y(null);const m=F==null?void 0:F.item;if(!m||Ae)return;const j=(nt??m.summary??m.description??m.title??"").trim();if(!j||Mt())return;const N=new AbortController;return fetch("/orgx/api/live/activity/headline",{method:"POST",headers:{"Content-Type":"application/json"},signal:N.signal,body:JSON.stringify({text:j,title:m.title??null,type:m.type})}).then(async O=>O.ok?await O.json():((O.status===404||O.status===405)&&De(!0),null)).then(O=>{const be=O==null?void 0:O.headline;typeof be=="string"&&be.trim().length>0&&(De(!1),$e(be.trim()),Y((O==null?void 0:O.source)??null))}).catch(O=>{O instanceof DOMException&&O.name}),()=>N.abort()},[F,nt,Ae]);const p=o.useCallback(m=>{var O;if(Ke.length===0)return;const N=((zt>=0?zt:0)+m+Ke.length)%Ke.length;ze(m),me(((O=Ke[N])==null?void 0:O.item.id)??null)},[zt,Ke]);o.useEffect(()=>{ne&&(zt>=0||me(null))},[zt,ne]),o.useEffect(()=>{if(!ne)return;const m=j=>{j.key==="ArrowRight"||j.key.toLowerCase()==="l"?(j.preventDefault(),p(1)):(j.key==="ArrowLeft"||j.key.toLowerCase()==="h")&&(j.preventDefault(),p(-1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[ne,p]);const A=Ht.size===1,$=A?[...Ht][0]:null,S=$?s.find(m=>m.runId===$||m.id===$)??null:null,H=o.useMemo(()=>{if(!A)return[];const m=[],j=new Set;for(const N of dn){if(!N.runId||!Ht.has(N.runId))continue;const O=Mi(N.item);if(O){if(j.has(O)||(j.add(O),!he))continue}else if(!he&&ar(N.item))continue;m.push(N.item)}return m},[A,dn,Ht,he]),Ie=!T&&Ke.length<=160,We=(m,j,N)=>{const O=m.item,be=N??O.id,Ue=ir(O),Qe=uo(O),yt=Qe.executor??Qe.requester,fn=Ci(Jt((yt==null?void 0:yt.name)??Qe.primaryLabel??O.agentName??Ue.agentName??null),Jt((yt==null?void 0:yt.id)??O.agentId??Ue.agentId??null),kn)||"OrgX",ft=_i(m.userState),ct=P==="newest"&&j<2,Wt=m.runId,fs=ho(O),{title:hn}=Jr(O),Cs=fs??_t(O.summary),hr=_t(O.description),ra=xo(O,Cs??hr??null),ia=O.initiativeId?Hn.get(O.initiativeId)??ot(O.initiativeId):null,ni=nr(O)??(Wt?cn.get(Wt)??null:null),aa=ni?It.get(ni)??ot(ni):null,ul=[ia,aa].filter(Boolean).join(" > ")||ia||aa||ot(O.type),ml=Si(m.userState),pl=new Date(O.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),fl=St(O.timestamp),hl=m.bucket==="artifact"?Lp(O):null;return n.jsx(Vm,{renderKey:be,displayTitle:hn,headline:ra,contextLabel:ul,detailText:(Cs??hr)!==ra?Cs??hr:null,displayAgentName:fn,railColor:ft,userStateLabel:ml,userStateWhy:m.userStateWhy,relativeTime:fl,timeLabel:pl,isRecent:ct,enableMotion:Ie,onOpen:()=>{ze(1),me(O.id)},ariaLabel:`Open activity details for ${hn||Xr(O.type)}`,artifactSnippet:hl},be)};return n.jsx(op,{sessions:s,initiatives:i??[],workspaceId:je??null,query:ae,statusFilter:ge,sortOrder:P,timeFilterId:y,customTimeRange:f,snapshot:Me,onRequestRefresh:B,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[A&&H.length>0?n.jsx(Wm,{items:H,session:S,agentName:((Be=H[0])==null?void 0:Be.agentName)??null,onBack:v,onOpenItem:m=>{ze(1),me(m.id)}}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex flex-col gap-2.5",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2.5",children:[n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Activity"}),n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary tabular-nums",children:wt}),Ze>0&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums",children:["+",Ze," hidden"]}),os>0&&!he&&n.jsxs("button",{type:"button",onClick:()=>V(!0),className:"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",title:"Show low-signal sync replay events",children:[os," sync hidden"]}),he&&n.jsx("button",{type:"button",onClick:()=>V(!1),className:"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]",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsxs("div",{className:"relative",ref:bn,children:[n.jsxs("button",{type:"button",onClick:()=>{Ee(m=>!m),Re(!1)},"aria-haspopup":"menu","aria-expanded":qe,className:ue("inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors",qe?"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-[240px] truncate",children:as}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:ue("transition-transform duration-200",qe&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(pt,{children:qe&&n.jsx(ye.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(m=>m.id!=="custom").map(m=>{const j=y===m.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(m.id),Ee(!1)},className:ue("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",j?"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:m.label},m.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),Gt?n.jsx("input",{type:"datetime-local",step:300,value:Ni(Nt),onChange:m=>Mn(oo(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(oa,{selected:Nt,onChange:m=>Mn(m instanceof Date?m:null),selectsStart:!0,startDate:Nt,endDate:ut,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"}),Gt?n.jsx("input",{type:"datetime-local",step:300,min:Ni(Nt),value:Ni(ut),onChange:m=>En(oo(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(oa,{selected:ut,onChange:m=>En(m instanceof Date?m:null),selectsEnd:!0,minDate:Nt??void 0,startDate:Nt,endDate:ut,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:is?`${Cr(Nt)} - ${Cr(ut)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:ls,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:Vn,disabled:!is,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("span",{className:ue("h-1.5 w-1.5 flex-shrink-0 rounded-full",jn&&"pulse-soft"),style:{backgroundColor:L.lime},"aria-label":"Live",title:jn?"New activity within the last minute":"Live activity feed"})]}),n.jsx("div",{className:"flex w-full items-center gap-2 md:w-[320px]",children:n.jsxs("div",{className:"relative min-w-0 flex-1",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute left-2.5 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:ae,onChange:m=>ve(m.target.value),placeholder:"Search activity...",className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.03] py-2 pl-9 pr-2 text-body text-primary placeholder:text-muted transition-colors focus:border-[#BFFF00]/30 focus:outline-none","aria-label":"Search activity"})]})})]}),n.jsx("div",{className:"flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[(Tt||d||h)&&n.jsxs(n.Fragment,{children:[Tt&&n.jsxs("button",{onClick:v,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[ao(fe.id)?n.jsx(Ps,{provider:fe.id,size:"xs"}):n.jsx(Rt,{name:(X==null?void 0:X.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:g,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:"×"})]}),h&&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:[ao(Fe.id)?n.jsx(Ps,{provider:Fe.id,size:"xs"}):n.jsx(Rt,{name:h,hint:h,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Agent: ",h]}),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(Sr).map(m=>{const j=ge===m;return n.jsx("button",{type:"button",onClick:()=>J(m),"aria-pressed":j,className:ue("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",j?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:Sr[m]},m)})}),n.jsx("button",{type:"button",onClick:()=>le(m=>!m),className:ue("inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border bg-white/[0.03] text-muted transition-colors hover:bg-white/[0.08] hover:text-primary",G?"border-lime/30 text-lime":"border-white/[0.1]"),"aria-pressed":G,"aria-label":G?"Expand activity density":"Compact activity density",title:G?"Expand activity density":"Compact activity density",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[n.jsx("path",{d:"M4 7h16"}),n.jsx("path",{d:G?"M4 12h16":"M4 12h10"}),n.jsx("path",{d:"M4 17h16"})]})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:yn,children:[n.jsxs("button",{type:"button",onClick:()=>{Re(m=>!m),Ee(!1)},"aria-haspopup":"menu","aria-expanded":te,"aria-label":"Activity filters",title:"Activity filters",className:ue("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:ue("transition-transform duration-200",te&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(pt,{children:te&&n.jsx(ye.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(m=>n.jsx("button",{type:"button",onClick:()=>{K(m.id),Re(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",P===m.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:m.label},m.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(Sr).map(m=>{const j=ge===m;return n.jsx("button",{type:"button",onClick:()=>{J(m),Re(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",j?"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:Sr[m]},m)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{V(m=>!m)},className:ue("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",he?"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:he?"Hide sync replay events":"Show sync replay events"}),n.jsx("p",{className:"mt-1 text-micro leading-relaxed text-muted",children:"Changeset replay and outbox sync events are low-signal operational noise for most users."})]})]})})})]})]})})]})}),n.jsxs("div",{ref:rs,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[Ke.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.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("span",{className:"mt-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.04] text-secondary",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-body font-semibold text-primary",children:I?"Syncing activity feed...":Tt?"No activity yet for this session":d?"No activity yet for this workstream":"No matching activity right now."}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:I?"Live updates usually appear within a few seconds after dispatch.":`Try widening the time window (${as}), changing filters, or launch the next workstream.`})]})]}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:R.map(m=>{const j=y===m.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(m.id),className:ue("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",j?"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:m.label},`empty-time-${m.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(Tt||d||h)&&n.jsx("button",{type:"button",onClick:()=>{Tt&&v(),d&&(g==null||g()),h&&(C==null||C())},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"}),ie&&n.jsx("button",{type:"button",onClick:()=>void fr("play",ie),disabled:Le!==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:Le==="play"?"Starting...":"Start next session"}),!ie&&Ne&&n.jsx("button",{type:"button",onClick:Ne,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"})]}),_e&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:_e})]})}),n.jsx(Um,{completedCount:on.completed,decisionsCount:on.decisions,blockerCount:on.blocked,visible:jt,onDismiss:()=>{Ut(!1),Bt.current=Date.now()}}),Ke.length>0&&n.jsxs("div",{className:"space-y-4",children:[qs.map(m=>{const j=G?m.clusters.slice(0,4):m.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:m.label}),Ie?n.jsx(pt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:j.map((N,O)=>{const be=re.has(N.key),Ue=N.allItems.slice(1),Qe=Ue.length,yt=Math.min(Qe,Se[N.key]??tr),fn=Ue.slice(0,yt);if(N.count===1)return We(N.representative,O);const ft=`cluster:${N.key}`;return n.jsxs("div",{children:[We(N.representative,O,ft),n.jsxs("button",{type:"button",onClick:ct=>{ct.stopPropagation(),xt(N.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:["×",N.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:be?"hide":`and ${N.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",be?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),be&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[fn.map((ct,Wt)=>We(ct,O+Wt+1)),yt<Qe&&n.jsxs("button",{type:"button",onClick:ct=>{ct.stopPropagation(),mn(N.key,Qe)},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 (",Qe-yt," remaining)"]})]})]},N.key)})})}):n.jsx("div",{className:"space-y-2",children:j.map((N,O)=>{const be=re.has(N.key),Ue=N.allItems.slice(1),Qe=Ue.length,yt=Math.min(Qe,Se[N.key]??tr),fn=Ue.slice(0,yt);if(N.count===1)return We(N.representative,O);const ft=`cluster:${N.key}`;return n.jsxs("div",{children:[We(N.representative,O,ft),n.jsxs("button",{type:"button",onClick:ct=>{ct.stopPropagation(),xt(N.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:["×",N.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:be?"hide":`and ${N.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",be?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),be&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[fn.map((ct,Wt)=>We(ct,O+Wt+1)),yt<Qe&&n.jsxs("button",{type:"button",onClick:ct=>{ct.stopPropagation(),mn(N.key,Qe)},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 (",Qe-yt," remaining)"]})]})]},N.key)})}),G&&m.clusters.length>j.length&&n.jsxs("p",{className:"mt-1.5 text-caption text-muted",children:["+",m.clusters.length-j.length," more"]})]},m.key)}),n.jsx("div",{ref:ht,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:ue("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",x?"opacity-100":w?"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]"})]})})}),!w&&!x&&Ke.length>0&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:Ze>0?`${Ke.length} of ${wt} events`:"You’ve reached the beginning"})]})]})]}),n.jsx(xp,{}),n.jsx(Km,{open:F!==null,onClose:Gn,children:F&&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:_i(F.userState),boxShadow:`0 0 12px ${_i(F.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Si(F.userState)," · ",zt+1,"/",Ke.length]}),Te&&n.jsx(In,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:Te})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[F.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(F.runId),Gn()},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:()=>p(-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:()=>p(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:()=>Ce(m=>!m),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),tt&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Ce(!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:[F.runId&&n.jsx("button",{type:"button",onClick:()=>{Nn("Run id",F.runId??""),Ce(!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"}),mr.agentId&&n.jsx("button",{type:"button",onClick:()=>{Nn("Agent id",mr.agentId??""),Ce(!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:()=>{Nn("Event id",F.item.id),Ce(!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:Gn,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(pt,{mode:"wait",custom:Ye,children:n.jsx(ye.section,{custom:Ye,initial:{opacity:0,x:Ye*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:Ye*-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:W||xo(F.item,nt)||ot(F.item.title||Xr(F.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(F.item.timestamp).toLocaleString()," · ",St(F.item.timestamp),z==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const m=(Z==null?void 0:Z.workstreamId)??nr(F.item)??(F.runId?cn.get(F.runId)??null:null),j=m?It.get(m)??ot(m):null,O=[(Z==null?void 0:Z.initiativeTitle)??(F.item.initiativeId?Hn.get(F.item.initiativeId)??null:null),j].filter(Boolean).join(" > ");return O?n.jsx(In,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:O})}):null})(),n.jsx(In,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Si(F.userState)}),n.jsxs(In,{tone:"muted",children:[n.jsx(Rt,{name:(Dn==null?void 0:Dn.label)??(Ge==null?void 0:Ge.primaryLabel)??"OrgX",hint:Dn?Ii(Dn):(Ge==null?void 0:Ge.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Dn==null?void 0:Dn.label)??(Ge==null?void 0:Ge.primaryLabel)??"OrgX"})]}),ps&&n.jsx(In,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(Qm,{item:F.item}),Xt&&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:Xt.source==="metadata"?"Artifact":ot(Xt.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[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:()=>at("structured"),"aria-pressed":dt==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${dt==="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:()=>at("json"),"aria-pressed":dt==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${dt==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Rn&&n.jsx("button",{type:"button",onClick:()=>ce(Rn),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:dt==="structured"?dl(Xt.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(Xt.value,null,2)})})})]}),At&&n.jsxs("div",{className:ue("rounded-xl border px-3.5 py-3",At.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",At.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",At.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",At.tone==="neutral"&&"border-cyan-400/22 bg-cyan-500/[0.07]"),children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/78",children:At.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:At.summary}),At.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:At.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[F.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(F.runId),Gn()},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"}),Ss&&n.jsx("button",{type:"button",onClick:()=>{de==null||de(As[0]??null),Gn()},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:As.length>0?"Resolve decision":"Resolve decisions"}),Rn&&!Xt&&n.jsx("button",{type:"button",onClick:()=>ce(Rn),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"}),pr&&n.jsx("a",{href:pr,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"}),Ft&&n.jsx("button",{type:"button",onClick:()=>void Xn(),disabled:st,className:ue("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",Ft.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:st?"Scheduling...":Ft.actionLabel})]}),Ft&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Et??Ft.helperText})]}),gt&&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(In,{tone:gt.isRateLimited?"muted":"red",children:gt.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:gt.domainCurrent!==null&&gt.domainMax!==null?`${gt.domainCurrent}/${gt.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:gt.totalCurrent!==null&&gt.totalMax!==null?`${gt.totalCurrent}/${gt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[gt.domain&&n.jsxs(In,{tone:"muted",children:["Domain: ",ot(gt.domain)]}),gt.modelTier&&n.jsxs(In,{tone:"muted",children:["Tier: ",ot(gt.modelTier)]}),Us&&n.jsxs(In,{tone:"muted",children:["Retry: ",Us]}),!Us&&gt.retryInMs!==null&&n.jsxs(In,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(gt.retryInMs/1e3)),"s"]})]}),gt.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:_t(gt.blockedReason)??gt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Q&&n.jsx("button",{type:"button",onClick:Q,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"}),Ft&&n.jsx("button",{type:"button",onClick:()=>void Xn(),disabled:st,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:st?"Scheduling...":"Retry now"})]})]}),us.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Results"}),n.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-caption sm:grid-cols-3",children:us.map(m=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:m.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${m.tone==="critical"?"text-red-300":"text-primary"}`,children:m.value})]},m.label))})]}),Ge&&!Z&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Delegation"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-body text-secondary",children:[n.jsx("span",{className:"flex items-center gap-1.5",children:Ge.requester?n.jsxs(n.Fragment,{children:[n.jsx(Rt,{name:Ge.requester.label,hint:Ii(Ge.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ge.requester.label})]}):n.jsx("span",{children:rr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:Ge.mode==="handoff"?"Delegated handoff":Ge.mode==="requested"?"Dispatch requested":Ge.mode==="single"?"Direct execution":"System event"}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"flex items-center gap-1.5",children:Ge.executor?n.jsxs(n.Fragment,{children:[n.jsx(Rt,{name:Ge.executor.label,hint:Ii(Ge.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ge.executor.label})]}):n.jsx("span",{children:rr("Not assigned")})})]}),Ge.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:Ge.subtitle})]}),Z&&n.jsxs("div",{className:"space-y-5",children:[n.jsxs("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:Ks(Z.event)??ot(Z.event)})]}),ds&&n.jsxs("p",{className:"mt-1 px-1 text-caption text-muted",children:["Based on related activity (",ot(ds.relation),")."]})]}),Ct&&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:Ws},children:ur?(At==null?void 0:At.label)??"Stopped":`${Ct.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,Ct.pct)}%`,backgroundColor:Ws}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:Ct.label})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),n.jsxs("div",{className:"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.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-body text-primary",children:[n.jsx(Rt,{name:Kn.primary,hint:Kn.secondary??Kn.primary,size:"xs"}),n.jsx("span",{children:Kn.primary})]}),Kn.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",Kn.secondary]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Executor"}),n.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-body text-primary",children:[n.jsx(Rt,{name:zs,hint:zs,size:"xs"}),n.jsx("span",{children:zs})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-body text-primary",children:Z.dispatcherClient?ot(Z.dispatcherClient):"OrgX"})]}),(Z.domain||Z.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-body text-primary",children:[Z.domain??"",Z.requiredSkills.length>0?`${Z.domain?" · ":""}${Z.requiredSkills.join(", ")}`:""]})]})]})]}),D&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 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?Yn(D.initiativeId):"—")})]}),D.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:ot(D.initiativeStatus)})]}),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??(D.workstreamId?Yn(D.workstreamId):"—")})]}),D.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:ot(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 px-1 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:Ks(D.phase)??ot(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:Ks(D.parsedStatus)??ot(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:Ks(D.stopReason)??ot(D.stopReason)})]})]})]}),Z.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:Z.error})]}),_s&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Xe==="missing"&&!ps&&n.jsx("p",{className:"mb-1 text-caption text-amber-200/75",children:"Full local turn transcript was unavailable; showing the event summary payload."}),n.jsx(Vr,{mode:"block",text:_s,className:"text-body leading-relaxed text-primary"})]}),_t(F.item.description)&&_t(F.item.description)!==_s&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Details"}),n.jsx(Vr,{mode:"block",text:_t(F.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),Vt&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Narrative"}),n.jsxs("div",{className:"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:Vt.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:Vt.dispatch})]}),Vt.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:Vt.highlights.slice(0,3).map((m,j)=>n.jsx("li",{children:m},`${Vt.sliceRunId}:highlight:${j}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:Vt.outcome.summary})]})]})]}),ms.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Evidence"}),n.jsx("div",{className:"space-y-2",children:ms.filter((m,j,N)=>N.findIndex(O=>O.path===m.path)===j).map((m,j)=>{const N=fo(m.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:ot(m.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Fs(m.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[N&&n.jsx("a",{href:N,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 Nn(`${ot(m.key)} path`,m.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"})]})]},`${m.key}:${m.path}:${j}`)})})]}),F&&Ai(F.item)&&!Xt&&n.jsxs("button",{type:"button",onClick:()=>{const m=Ai(F.item);m&&ce(m)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:L.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:L.cyan},children:"View registered artifact"})]}),(it||(Z==null?void 0:Z.logPath)||Hs)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(it||(Z==null?void 0:Z.logPath)||(Z==null?void 0:Z.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:[it&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[it.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:ot(it.domain)})]}),(it.provider||it.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:[it.provider?`${ot(it.provider)} · `:"",it.model?or(it.model):"—"]})]}),it.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:ot(it.modelTier)})]}),it.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",it.pluginVersion]})]})]}),(it==null?void 0:it.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:[it.skillPack.name??"—",it.skillPack.version?`@${it.skillPack.version}`:"",it.skillPack.source?` · ${it.skillPack.source}`:""]}),it.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var m;return void Nn("Skill pack checksum",((m=it.skillPack)==null?void 0:m.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",it.skillPack.checksum.slice(0,12)]})]}),it&&it.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"}),it.requiredSkills.map(m=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:m},m))]}),(it==null?void 0:it.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:[it.kickoffContextSource?`${it.kickoffContextSource} · `:"",it.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void Nn("Kickoff context hash",it.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"})]}),((Z==null?void 0:Z.logPath)||(Z==null?void 0:Z.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(Z==null?void 0:Z.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: ",Fs(Z.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void Nn("Log path",(Z==null?void 0:Z.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"})]}),(Z==null?void 0:Z.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: ",Fs(Z.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void Nn("Output path",(Z==null?void 0:Z.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: ",Yn(D.initiativeId)]}),(D==null?void 0:D.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",Yn(D.workstreamId)]})]})]})]}),Hs&&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:Hs})]})]})},F.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"})]})})]})})}),tf=o.lazy(async()=>({default:(await Pt(()=>import("./BWEwjt1W.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))).MissionControlView})),nf=o.lazy(async()=>({default:(await Pt(()=>import("./IUexzymk.js"),__vite__mapDeps([9,1,2,3,4,10,7]))).SessionInspector})),sf=o.lazy(async()=>({default:(await Pt(()=>import("./rttbDbEx.js"),__vite__mapDeps([11,1,2,3,4,8,7,10]))).DecisionQueue})),rf=o.lazy(()=>Pt(()=>import("./CL_wXqR7.js"),__vite__mapDeps([12,1,2,3,4,7])).then(e=>({default:e.TriageQueue}))),af=o.lazy(()=>Pt(()=>import("./ic2FaMnh.js"),__vite__mapDeps([13,1,2,3,4,7])).then(e=>({default:e.TriageDetailModal}))),of=o.lazy(async()=>({default:(await Pt(()=>import("./6mILZQ2a.js").then(t=>t.a),__vite__mapDeps([5,1,2,3,4,6,7]))).NextUpPanel})),lf=o.lazy(async()=>({default:(await Pt(()=>import("./D3iMTYEj.js"),__vite__mapDeps([14,1,2,3,4,7]))).SettingsModal})),cf=o.lazy(async()=>({default:(await Pt(()=>import("./D8JNX8kq.js"),__vite__mapDeps([15,1,2,3,4,7]))).BulkSessionsModal})),df=o.lazy(async()=>({default:(await Pt(()=>import("./B5zYRHc3.js"),__vite__mapDeps([16,1,2,3,4,11,8,7,10]))).BulkDecisionsModal})),uf=o.lazy(async()=>({default:(await Pt(()=>import("./CgaottFX.js"),__vite__mapDeps([17,1,2,3,4,7]))).BulkOutboxModal})),mf=o.lazy(async()=>({default:(await Pt(()=>import("./8dksYiq4.js"),__vite__mapDeps([18,1,2,3,4,7]))).BulkHandoffsModal})),pf=o.lazy(async()=>({default:(await Pt(()=>import("./CzCxAZlW.js"),__vite__mapDeps([19,1,2,3,4,6,7]))).ArtifactViewerModal})),ff=o.lazy(async()=>({default:(await Pt(()=>import("./DnA8dpj6.js"),__vite__mapDeps([20,1,2,3,4,8,7]))).SliceDetailModal})),hf=o.lazy(async()=>({default:(await Pt(()=>import("./CC63EwFD.js"),__vite__mapDeps([21,1,2,3,4,7]))).RealtimeOrchestratorModal})),yo={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},gf={connected:L.lime,reconnecting:L.amber,disconnected:L.red},Ei="orgx.demo_mode",Ti="orgx.dev_mode",Ri="orgx.show_synthetic_entities",Vi="orgx.selected_workspace_id",bo={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},wo=new Set(["running","active","queued","pending","in_progress","working","planning"]),xf=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function rn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function yf(e){const t=rn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function bf(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 wf(e){const t=e.trim().toLowerCase();return t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted")?{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"}:t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth")?{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"}:t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes")?{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"}:{title:"Live stream degraded",message:bf(e),action:"settings"}}function Di(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 vf(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 vo(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function ko(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 Li(e,t){const s=bo[e.status]??99,r=bo[t.status]??99;return s!==r?s-r:rn(e.updatedAt??e.lastEventAt??e.startedAt)-rn(t.updatedAt??t.lastEventAt??t.startedAt)}function jo(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 kf(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 jf(e){if(js(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Nf(e){if(js(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function If(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Af(e){return xf.test(e)}function Tr(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 Sf(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function _f(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Cf(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 Mf(e,t){ss(e,t)}function Ef(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 Tf(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Cf(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Vi);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function Rf(){const e=Bc();return e.showGate?n.jsx(Ed,{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(Du,{children:n.jsx(Pf,{onboarding:e})})}function Df(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 Lf(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 No(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 Io(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Ff(){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:Zr,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function $f(){const{state:e}=Xo();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(pf,{})}):null}function Pf({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(Ei)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ri)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ti)==="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,h]=o.useState(()=>Tf()),y=o.useCallback(p=>{d(p);try{localStorage.setItem("orgx-dashboard-view",p)}catch{}},[]),{data:b=[]}=ns({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const p=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!p.ok)return[];const A=await p.json().catch(()=>null),$=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const H of $){if(!H||typeof H!="object"||Array.isArray(H))continue;const Ie=Tr(H,["id"]);if(!Ie)continue;const We=Tr(H,["status","priority"]);if(!Sf(We))continue;const Be=Tr(H,["title","name"])??(Ie.length>10?`${Ie.slice(0,8)}…`:Ie),m=H.is_default===!0,j=_f({title:Be,isDefault:m}),N=Tr(H,["created_at"]);S.push({id:Ie,title:j,status:We,isDefault:m,createdAt:N})}return S.sort((H,Ie)=>{if(H.isDefault!==Ie.isDefault)return H.isDefault?-1:1;const We=rn(H.createdAt)-rn(Ie.createdAt);return We!==0?We:H.title.localeCompare(Ie.title)}),S},staleTime:6e4}),f=o.useMemo(()=>{var p;return u?((p=b.find(A=>A.id===u))==null?void 0:p.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),k=o.useMemo(()=>!u||b.some(p=>p.id===u)?b:[{id:u,title:f,status:null,isDefault:!1,createdAt:null},...b],[u,f,b]);o.useEffect(()=>{u&&b.length!==0&&(b.some(p=>p.id===u)||h(null))},[u,b]),t||e.state.hasApiKey&&e.state.connectionVerified;const w=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:x,isLoading:_,error:v,refetch:g,approveDecision:C,rejectDecision:U,approveAllDecisions:de,bulkDecisionAction:ee,decisionMutation:pe}=pc({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...w}),ie=t||r,se=o.useMemo(()=>ie?x.sessions.nodes:x.sessions.nodes.filter(p=>!jf(p)),[x.sessions.nodes,ie]),oe=o.useMemo(()=>x.activity.filter(p=>!(!ie&&Nf(p)||!a&&If(p))),[x.activity,ie,a]),we=x.connection==="connected"||x.decisions.length>0,[Ne,Q]=o.useState(null),[je,Me]=o.useState(!1),[B,I]=o.useState(null),[T,ce]=o.useState(null),[ge,J]=o.useState(null),[he,V]=o.useState(null),[G,le]=o.useState("live"),[ae,ve]=o.useState({startIso:null,endIso:null}),re=o.useRef(new Set),[Pe,Se]=o.useState(null),[E,P]=o.useState(null),[K,te]=o.useState(null),[Re,qe]=o.useState(null),Ee=o.useRef(null),M=o.useCallback(p=>{Ee.current&&clearTimeout(Ee.current),qe(p),Ee.current=setTimeout(()=>qe(null),4e3)},[]),[q,ne]=o.useState(!1),[me,Te]=o.useState(!1),[et,tt]=o.useState([]),Ce=o.useRef(null),Ye=o.useRef(null),[ze,dt]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[at,nt]=o.useState(!1),[xe,Xe]=o.useState(null),[ke,W]=o.useState("agents"),[$e,z]=o.useState("initiatives"),[Y,Ae]=o.useState("next_up"),De=o.useCallback(p=>{if(W(p),p==="initiatives"){z("initiatives"),Ae("next_up");return}p==="decisions"&&(z("initiatives"),Ae("in_progress"),Oe("needs_attention"))},[]),[Le,Oe]=o.useState("all"),_e=o.useMemo(()=>Array.isArray(x.sliceRuns)?x.sliceRuns:[],[x.sliceRuns]),st=o.useMemo(()=>Ho({sessions:se,sliceRuns:_e}),[_e,se]).length,Ve=o.useMemo(()=>Vo(_e),[_e]),Et=Ve.length+(we?x.decisions.length:0),[Je,jt]=o.useState(null),Ut=o.useCallback(p=>{const A=_e.find($=>$.initiativeId===p.initiativeId&&$.workstreamId===p.workstreamId)??null;jt({source:"queue",item:p,linkedSliceRun:A})},[_e]),Bt=o.useCallback((p,A)=>{jt({source:"in_progress",row:p,sliceRun:A})},[]),yn=o.useCallback(p=>{jt({source:"needs_input",sliceRun:p})},[]),bn=o.useCallback(async(p,A)=>{var S;const $=p.runId??p.sliceRunId;if(!$){M("Cannot accept — no run ID found on this slice.");return}try{const H=A?`Accepted: ${A}`:"Accepted from dashboard",Ie=`/orgx/api/runs/${encodeURIComponent($)}/actions/complete`,We=await fetch(Ie,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:H})});if(!We.ok){const j=await We.json().catch(()=>null),N=(j==null?void 0:j.error)??(j==null?void 0:j.message)??`Failed to accept slice (${We.status})`;M(N);return}const Be=await We.json().catch(()=>null),m=((S=Be==null?void 0:Be.data)==null?void 0:S.remoteOk)===!0;M(m?"Slice accepted and marked complete.":"Slice accepted locally. Remote sync pending."),g()}catch{M("Failed to accept slice — network error.")}},[g,M]),rs=o.useCallback(async(p,A)=>{const $=p.runId??p.sliceRunId;if(!$||!A.trim()){M("Cannot post feedback — missing run ID or note.");return}try{const S=await fetch(`/orgx/api/entities/run/${encodeURIComponent($)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:A.trim(),commentType:"review_feedback",severity:"warn",tags:["changes_requested"]})});if(!S.ok){const H=await S.json().catch(()=>null);M((H==null?void 0:H.error)??(H==null?void 0:H.message)??`Failed to post feedback (${S.status})`);return}M("Changes requested — feedback posted.")}catch{M("Failed to post feedback — network error.")}},[M]),ht=ed({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:x.snapshotVersion}),Ot=nd({authToken:null,embedMode:!1}),{model:Nt,actions:Mn}=id({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),ut=o.useMemo(()=>Nt.items.filter(p=>p.kind==="failure_diagnostic"),[Nt.items]),En=o.useMemo(()=>({...Nt,items:ut,total:ut.length}),[ut,Nt]),[Gt,Lt]=o.useState(null),[Zt,wn]=o.useState(0),an=o.useCallback(p=>{Lt(p);const A=ut.findIndex($=>$.id===p.id);wn(A>=0?A:0)},[ut]),is=o.useCallback(p=>{if(ut.length===0)return;const A=(Zt+p+ut.length)%ut.length;wn(A),Lt(ut[A]??null)},[Zt,ut]),as=ht,on=o.useMemo(()=>ht.items.find(p=>p.autoIntentEnabled===!0&&(p.autoRuntimeState==="running"||p.autoRuntimeState==="stopping"))??null,[ht.items]),ln=!!on;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(Ei,"1"):window.localStorage.removeItem(Ei)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(Ri,"1"):window.localStorage.removeItem(Ri)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(Ti,"1"):window.localStorage.removeItem(Ti)}catch{}},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(Vi,u):window.localStorage.removeItem(Vi)}catch{}try{const p=new URL(window.location.href);u?Mf(p.searchParams,u):Ef(p.searchParams),p.searchParams.delete("initiative"),p.searchParams.delete("initiative_id"),p.searchParams.delete("project"),window.history.replaceState(null,"",`${p.pathname}${p.search}${p.hash}`)}catch{}}},[u]);const qt=o.useCallback((p,A)=>{dt($=>({open:!0,tab:p??$.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),Wn=o.useCallback(p=>{if(s(p),!(typeof window>"u"))try{const A=new URL(window.location.href);p?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),vn=o.useCallback(()=>{qt("orgx")},[qt]),Un=o.useCallback(()=>{Pt(()=>import("./BWEwjt1W.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))},[]),{data:kn}=Ko(l==="mission-control",u),{data:cn}=Ru(l==="mission-control",u),{data:Hn=[]}=ns({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[It,dn]=o.useState(null),[jn,Ht]=o.useState(""),[Tt,R]=o.useState(!1),X=o.useCallback((p,A)=>{dn({type:p,initiativeId:A}),Ht(""),R(!1)},[]),fe=o.useCallback(()=>{dn(null),Ht(""),R(!1)},[]),Fe=o.useCallback(()=>{ce(null)},[]),Ke=o.useCallback(()=>{J(null),V(null)},[]),wt=o.useCallback(()=>{te(null)},[]);o.useEffect(()=>{var $;const p=(($=se[0])==null?void 0:$.id)??null;if(!p){Ne!==null&&Q(null);return}if(Ne===null){Q(p);return}se.some(S=>S.id===Ne)||Q(p)},[se,Ne]),o.useEffect(()=>{if(!T)return;se.some(A=>A.id===T)||ce(null)},[T,se]);const Ze=o.useCallback(p=>{Pt(()=>import("./IUexzymk.js"),__vite__mapDeps([9,1,2,3,4,10,7])),Q(p),Me(!0),I(null),ce(p),J(null),V(null)},[]),os=o.useCallback(p=>{Pt(()=>import("./IUexzymk.js"),__vite__mapDeps([9,1,2,3,4,10,7])),Q(p.id),Me(!0),ce(p.id),J(p.workstreamId??null),V(p.title),I({workstreamId:p.workstreamId??null,text:`Intervention requested for "${p.title}". `}),M(`Opened intervention composer for ${p.title}.`)},[]),un=o.useCallback(p=>{const A=p.trim();if(!A)return;const $=se.find(S=>S.runId===A||S.id===A)??null;$&&(Ze($.id),M(`Focused session: ${$.title}`))},[se,Ze]),qs=o.useCallback(p=>{var S;const A=(S=p.id)==null?void 0:S.trim();if(!A)return;const $=Di(p);if($){const H=se.find(Ie=>Ie.runId===$||Ie.id===$)??null;H&&(Q(H.id),ce(H.id))}y("activity"),W("activity"),Me(!1),Se(A),M("Opened activity detail from session timeline.")},[se,y]),xt=o.useMemo(()=>se.find(p=>p.id===T)??null,[T,se]),mn=o.useMemo(()=>{var $,S;const p=(($=xt==null?void 0:xt.runId)==null?void 0:$.trim())??"",A=((S=xt==null?void 0:xt.id)==null?void 0:S.trim())??"";return!p||!A?[]:p===A?[p]:[p,A]},[xt==null?void 0:xt.id,xt==null?void 0:xt.runId]),Vn=o.useMemo(()=>{const p=new Set;for(const A of mn){const $=A.trim();$.length>0&&p.add($)}return p},[mn]),ls=o.useMemo(()=>{const p=new Map;for(const A of se){const $=A.workstreamId??null;A.runId&&p.set(A.runId,$),A.id&&p.set(A.id,$)}return p},[se]),pn=o.useMemo(()=>{const p=mn.length>0?mn.join("|"):"*",A=(ge==null?void 0:ge.trim())||"*",$=(K==null?void 0:K.trim())||"*";return`${p}::${A}::${$}`},[ge,K,mn]),Fn=o.useCallback(p=>{re.current.add(pn),le(p)},[pn]);o.useEffect(()=>{if(re.current.has(pn)||_)return;const p=Date.now(),A=oe.filter(H=>{const Ie=Di(H);if(Vn.size>0&&(!Ie||!Vn.has(Ie)))return!1;if(ge){const We=vo(H);if((ko(We,["workstreamId","workstream_id"])??(Ie?ls.get(Ie)??null:null))!==ge)return!1}if(K){const We=vo(H);if((ko(We,["agentName","agent_name"])??H.agentName)!==K)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(H=>{const Ie=cr(H,p);return A.some(We=>{const Be=rn(We.timestamp);return Be?Ie===null||Be>=Ie:!1})})??"all";re.current.add(pn),S!==G&&le(S)},[ge,oe,pn,G,ls,K,_,Vn]);const Tn=Nc({seed:oe,timeFilterId:G,customSinceIso:G==="custom"?ae.startIso:null,customUntilIso:G==="custom"?ae.endIso:null,runId:(xt==null?void 0:xt.runId)??null,projectId:u,pageSize:50,demoMode:t}),vt=o.useMemo(()=>se.find(p=>p.id===Ne)??null,[se,Ne]),zt=o.useMemo(()=>se.filter(p=>wo.has(p.status)).length,[se]),F=o.useMemo(()=>_e.length>0?Ve.length:se.filter(p=>{const A=Dt(p.status),$=Dt(p.phase??""),S=Dt(p.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||$==="blocked"||S==="error"?!0:wo.has(A)||A==="handoff"||A==="review"?!1:p.blockers.length>0}).length,[_e.length,Ve.length,se]);o.useMemo(()=>se.filter(p=>p.status==="failed").length,[se]);const cs=o.useMemo(()=>se.filter(p=>p.status==="completed").length,[se]);o.useMemo(()=>{const p=(we?x.decisions.length:0)+F;return[{id:"active",label:"Running",value:zt,color:zt>0?L.lime:L.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:p,color:p>0?L.amber:L.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:cs,color:L.teal,icon:"session"}]},[zt,F,cs,x.decisions.length,se,we]),o.useMemo(()=>x.decisions.length>0?Math.max(0,...x.decisions.map(p=>p.waitingMinutes)):0,[x.decisions]);const Vt=o.useMemo(()=>v?wf(v):null,[v]),Xt=o.useMemo(()=>{const p=[];if(Vt){const A=Vt.action==="refresh"&&typeof g=="function";p.push({id:`stream-error:${v}`,kind:"error",icon:"notification",title:Vt.title,message:Vt.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void g():()=>qt("orgx")})}return x.connection!=="connected"&&p.push({id:`connection:${x.connection}`,kind:x.connection==="disconnected"?"error":"info",icon:"notification",title:x.connection==="disconnected"?"Connection lost":"Reconnecting",message:x.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:vn}),Re&&p.push({id:`ops:${Re}`,kind:"info",icon:/decision/i.test(Re)?"decision":"workstream",title:"Update",message:Re}),p},[x.connection,x.outbox.lastReplayError,x.outbox.pendingTotal,x.outbox.replayStatus,v,Vt,vn,g,qt,Re]);o.useEffect(()=>{const p=new Set(Xt.map(A=>A.id));tt(A=>A.filter($=>p.has($)))},[Xt]);const Rn=o.useMemo(()=>Xt.filter(p=>!et.includes(p.id)),[et,Xt]),Ns=we?x.decisions.length:0,ds=zt+F+Ns,Ge=o.useCallback(p=>{tt(A=>A.includes(p)?A:A.concat(p))},[]),Dn=o.useCallback(()=>{tt(Xt.map(p=>p.id))},[Xt]);o.useEffect(()=>{if(!me)return;const p=$=>{var H,Ie;const S=$.target;S&&((H=Ye.current)!=null&&H.contains(S)||(Ie=Ce.current)!=null&&Ie.contains(S)||Te(!1))},A=$=>{$.key==="Escape"&&Te(!1)};return document.addEventListener("mousedown",p),document.addEventListener("touchstart",p),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("touchstart",p),document.removeEventListener("keydown",A)}},[me]);const Z=o.useMemo(()=>{var $;const p=new Map;for(const S of se){const H=S.initiativeId??S.groupId??"unscoped",Ie=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",We=Df(Ie),Be=p.get(H)??{id:H,name:Ie,category:We,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(S.progress!==null&&(Be.progressTotal+=S.progress,Be.progressCount+=1),Be.statusCounts[S.status]=(Be.statusCounts[S.status]??0)+1,S.agentName&&(Be.allAgents.add(S.agentName),["running","queued","pending","blocked"].includes(S.status)&&Be.activeAgents.add(S.agentName)),S.workstreamId){const m=x.sessions.groups.find(N=>N.id===S.workstreamId),j=(($=m==null?void 0:m.label)==null?void 0:$.trim())||S.workstreamId;Be.workstreams.set(S.workstreamId,j)}Be.latestEpoch=Math.max(Be.latestEpoch,rn(S.updatedAt??S.lastEventAt??S.startedAt)),p.set(H,Be)}const A=[];for(const S of p.values()){const H=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,Ie=S.category,We=Lf(Ie),Be=Math.round(Math.max(0,Math.min(100,H))/100*(We.length-1)),m=(S.statusCounts.blocked??0)>0,j=(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,N=!j&&!m&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,O=We.map((be,Ue)=>{let Qe="upcoming";return(j||Ue<Be)&&(Qe="completed"),Ue===Be&&!j&&(Qe=m?"warning":"current"),{name:be,status:Qe}});A.push({id:S.id,name:S.name,status:j?"completed":m?"blocked":N?"paused":"active",rawStatus:j?"completed":m?"blocked":N?"paused":"active",category:Ie,health:Math.max(0,Math.min(100,H)),phases:O,currentPhase:j?We.length-1:Be,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:`${S.workstreams.size} workstreams are active right now.`,workstreams:Array.from(S.workstreams.entries()).map(([be,Ue])=>({id:be,name:Ue,status:"active"}))})}return A.sort((S,H)=>{const Ie=S.status==="blocked"?0:S.status==="active"?1:2,We=H.status==="blocked"?0:H.status==="active"?1:2;return Ie!==We?Ie-We:H.health-S.health})},[se,x.sessions.groups]),Is=o.useMemo(()=>{const p=(S,H)=>{var Ie,We;return{...S,...H,health:H.health>0?H.health:S.health,activeAgents:Math.max(S.activeAgents,H.activeAgents),totalAgents:Math.max(S.totalAgents,H.totalAgents),avatars:(Ie=S.avatars)!=null&&Ie.length?S.avatars:H.avatars,workstreams:(We=S.workstreams)!=null&&We.length?S.workstreams:H.workstreams,description:S.description??H.description,rawStatus:H.rawStatus??S.rawStatus??null,targetDate:H.targetDate??S.targetDate??null,createdAt:H.createdAt??S.createdAt??null,updatedAt:H.updatedAt??S.updatedAt??null}},A=new Map;for(const S of Z)A.set(S.id,S);for(const S of[...cn??[],...kn??[]]){if(!ie&&js(S.id)){A.delete(S.id);continue}const H=S.rawStatus??S.status;if(!Io(H)){A.delete(S.id);continue}const Ie=A.get(S.id);A.set(S.id,Ie?p(Ie,S):S)}const $=new Set(Hn);return Array.from(A.values()).filter(S=>!$.has(S.id)).filter(S=>Io(S.rawStatus??S.status)).sort((S,H)=>{const Ie=N=>N==="blocked"?0:N==="active"?1:N==="paused"?2:3,We=Ie(S.status)-Ie(H.status);if(We!==0)return We;const Be=No(S.priority)-No(H.priority);if(Be!==0)return Be;const m=rn(H.updatedAt)-rn(S.updatedAt);if(m!==0)return m;const j=H.health-S.health;return j!==0?j:S.name.localeCompare(H.name)})},[Z,kn,ie,cn,Hn]),Kn=o.useMemo(()=>{if(!xt)return null;const p=xt.agentName,A=xt.title;if(p){const $=oe.find(S=>{var H;return S.runId===xt.runId&&((H=S.summary)==null?void 0:H.trim())});if($!=null&&$.summary){const S=$.summary.trim().length>40?$.summary.trim().slice(0,40)+"…":$.summary.trim();return`${p}: ${S}`}return p}if(A){const $=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if($.length>0)return $}return A??null},[oe,xt]),zs=o.useMemo(()=>{const p=new Map;for(const A of se){const $=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const H=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),Ie=rn(H),We=Ie?Math.max(0,Math.floor((Date.now()-Ie)/6e4)):0,Be=p.get($),m={id:$,name:S,role:"Agent",status:kf(A.status),task:A.title??null,progress:A.progress??null,lastActive:H,lastActiveMinutes:We};(!Be||rn(m.lastActive)>rn(Be.lastActive))&&p.set($,m)}return Array.from(p.values())},[se]),dr=o.useCallback(async()=>{if(se.length===0){M("No sessions available to continue.");return}const p=[...se].sort(Li)[0];if(Q(p.id),ce(p.id),J(null),V(null),["blocked","pending","queued"].includes(p.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}M(`Focused highest priority session: ${p.title}`),await g()},[se,g]),Ct=o.useCallback(async(p,A)=>{const $=await p.json().catch(()=>null),S=typeof($==null?void 0:$.error)=="string"&&$.error.trim()||typeof($==null?void 0:$.message)=="string"&&$.message.trim()||`${A} (${p.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:Cn(S)},[]),D=o.useCallback((p,A)=>!p||p.trim().length===0?A:Cn(p.trim())||A,[]),At=o.useCallback(async()=>{const p=jo(ht.items);if(!p){M("No startable Next Up workstream is available."),y("mission-control");return}await ht.playWorkstream({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId}),ce(null),J(p.workstreamId),V(p.workstreamTitle),te(null),M(`Dispatched Next Up: ${p.workstreamTitle}`),await Promise.all([ht.refetch(),g()])},[g,ht,y]),us=o.useCallback(async()=>{const p=jo(ht.items);if(!p){M("No startable initiative is ready for Autopilot yet."),y("mission-control");return}await Ot.move({initiativeId:p.initiativeId,workstreamId:p.workstreamId,placement:"top"}),await ht.startWorkstreamAutoContinue({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId,scope:"initiative"}),ce(null),J(p.workstreamId),V(p.workstreamTitle),te(null),M(`Autopilot started for ${p.initiativeTitle}; queued from ${p.workstreamTitle}.`),await Promise.all([ht.refetch(),g()])},[g,Ot,ht,y]),As=o.useCallback(async()=>{ne(!0);try{if(!on){await us();return}await ht.stopInitiativeAutoContinue({initiativeId:on.initiativeId}),M(`Autopilot stopped for ${on.initiativeTitle}.`),await Promise.all([ht.refetch(),g()])}finally{ne(!1)}},[on,g,ht,us]),Ss=o.useCallback(async p=>{const A=(p.initiativeId??"").trim(),$=(p.workstreamId??"").trim();if(!A||!$)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:$,agentId:p.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await Ct(S,"Failed to dispatch workstream from In Progress"));ce(null),J($),V(p.title),M(`Dispatched ${p.title}.`),await Promise.all([ht.refetch(),g()])},[Ct,g,ht]),Ws=o.useCallback(async p=>{const A=(p.initiativeId??"").trim(),$=(p.workstreamId??"").trim();if(!A||!$)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:$,placement:"bottom",resetToTodo:!1})});if(!S.ok){const H=await Ct(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(H))throw new Error(H);const Ie=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!Ie.ok)throw new Error(await Ct(Ie,"Failed to pause workstream using legacy fallback"))}M(`Paused ${p.title} and sent it to the bottom of queue.`),await Promise.all([ht.refetch(),g()])},[Ct,g,ht]),ur=o.useCallback(async p=>{const A=(p.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const $=p.text.trim();if(Af($)){qt("agents",{focusAgentDomain:"engineering"}),M("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:$,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!S.ok)throw new Error(await Ct(S,"Failed to submit intervention"));M(`Intervention sent for ${p.session.title}.`),await g()},[qt,Ct,g]),it=o.useCallback(async p=>{if(Q(p.id),ce(p.id),J(null),V(null),!["running","completed","archived"].includes(p.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}M(`Dispatch requested: ${p.title}`),await g()},[g]),Qt=o.useCallback(async(p,A,$={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!S.ok){const H=await S.json().catch(()=>null);throw new Error((H==null?void 0:H.error)??`${A} failed (${S.status})`)}},[]),gt=o.useCallback(async p=>{var H;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const Ie=await A.json().catch(()=>null);throw new Error((Ie==null?void 0:Ie.error)??`Checkpoint creation failed (${A.status})`)}const $=await A.json().catch(()=>null),S=$&&"data"in $&&((H=$.data)==null?void 0:H.id)||$&&"id"in $&&$.id||null;M(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await g()},[g]),Us=o.useCallback(async p=>{await Qt(p,"pause",{reason:"pause_from_dashboard"}),M(`Pause requested: ${p.title}`),await g()},[g,Qt]),mr=o.useCallback(async p=>{await Qt(p,"resume",{reason:"resume_from_dashboard"}),M(`Resume requested: ${p.title}`),await g()},[g,Qt]),Hs=o.useCallback(async p=>{await Qt(p,"cancel",{reason:"restart_from_in_progress"}),await Ss(p),M(`Restarted ${p.title}.`),await g()},[Ss,g,Qt]),ms=o.useCallback(async p=>{await Qt(p,"cancel",{reason:"cancel_from_dashboard"}),M(`Cancel requested: ${p.title}`),await g()},[g,Qt]),pr=o.useCallback(async p=>{var We;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Be=await A.json().catch(()=>null);throw new Error((Be==null?void 0:Be.error)??`Checkpoint list failed (${A.status})`)}const $=await A.json().catch(()=>null),Ie=(We=(Array.isArray($)?$:Array.isArray($==null?void 0:$.data)?$.data:[]).map(Be=>({id:typeof Be.id=="string"?Be.id:"",createdAt:typeof Be.createdAt=="string"?Be.createdAt:typeof Be.created_at=="string"?Be.created_at:""})).filter(Be=>Be.id.length>0).sort((Be,m)=>Date.parse(m.createdAt)-Date.parse(Be.createdAt))[0])==null?void 0:We.id;if(!Ie)throw new Error("No checkpoint available for rollback.");await Qt(p,"rollback",{checkpointId:Ie,reason:"rollback_from_dashboard"}),M(`Rollback requested for ${p.title}.`),await g()},[g,Qt]),_s=o.useCallback(async()=>{var $;if(!It||jn.trim().length===0||Tt)return;R(!0);const p=It.type,A=jn.trim();try{const S={type:p,title:A,status:"active"};if(p==="workstream"){const Ie=It.initiativeId??(vt==null?void 0:vt.initiativeId)??(($=Z[0])==null?void 0:$.id)??null;if(!Ie){M("Select an initiative first to start a workstream."),R(!1);return}S.initiative_id=Ie,S.parentId=Ie}const H=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!H.ok){const Ie=await H.json().catch(()=>null);throw new Error((Ie==null?void 0:Ie.error)??`Failed to create ${p}.`)}M(`Created ${p}: ${A}`),fe(),await g()}catch(S){M(D(S instanceof Error?S.message:"",`Failed to create ${p}.`)),R(!1)}},[fe,Tt,It,jn,Z,g,vt==null?void 0:vt.initiativeId]),ps=o.useCallback(()=>{X("initiative")},[X]),Ft=o.useCallback(p=>{X("workstream",p)},[X]);o.useCallback(()=>{var p;return Ft((vt==null?void 0:vt.initiativeId)??((p=Z[0])==null?void 0:p.id)??null)},[Z,vt==null?void 0:vt.initiativeId,Ft]);const Gn=o.useCallback(p=>{const A=[...se].filter($=>($.initiativeId??$.groupId)===p.id).sort(Li)[0];A&&(Q(A.id),ce(A.id),J(null),V(null),M(`Focused initiative: ${p.name}`))},[se]),fr=o.useCallback(p=>{const A=Z.find($=>$.id===p)??Is.find($=>$.id===p)??null;A&&Gn(A)},[Gn,Z,Is]),Xn=o.useCallback(p=>{const A=(p??"").trim();y("activity"),z("initiatives"),W("initiatives"),Ae("in_progress"),Oe("needs_attention"),P(A.length>0?A:null),M(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[y]),Nn=o.useCallback(p=>{const A=new Set,$=(p.runId??"").trim();$.length>0&&A.add($),A.add(p.sliceRunId);const S=new Map;for(const m of oe){const j=Di(m),N=vf(m);(j&&A.has(j)||N&&N===p.sliceRunId)&&S.set(m.id,m)}const H=Array.from(S.values()),Ie=m=>{const j=m.type.trim().toLowerCase();let N=0;return(j==="decision_requested"||j==="blocker_created")&&(N+=80),(j==="run_failed"||j==="autopilot_stopped")&&(N+=70),(j.includes("slice_completed")||j.includes("completed"))&&(N+=60),j.includes("artifact")&&(N+=55),(j.includes("progress")||j.includes("update"))&&(N+=35),N+=Math.floor(rn(m.timestamp)/1e3),N};H.sort((m,j)=>Ie(j)-Ie(m));const We=H[0]??null;y("activity"),W("activity"),z("initiatives");const Be=($?se.find(m=>m.runId===$||m.id===$)??null:null)??(p.initiativeId&&p.workstreamId?se.find(m=>m.initiativeId===p.initiativeId&&m.workstreamId===p.workstreamId)??null:null);if(Be?(Q(Be.id),ce(Be.id),J(null),V(null)):p.workstreamId&&(ce(null),J(p.workstreamId),V(p.workstreamTitle??"Work slice")),We!=null&&We.id){Se(We.id),M(`Reviewing activity for ${p.workstreamTitle??"work slice"}.`);return}if(p.primaryAction==="resolve_decision"){Xn();return}if($.length>0){un($),M("Opened the related work session. Timeline details were unavailable.");return}M("No activity details were found for this slice yet.")},[oe,un,Xn,se,y]);return o.useCallback(p=>{const A=new Set(p),$=[...se].filter(S=>A.has(S.status)).sort(Li)[0];if(!$){M("No matching sessions for that metric right now.");return}Ze($.id),W("activity")},[se,Ze]),o.useCallback(p=>{l==="activity"&&(p==="sessions"||p==="active"||p==="blocked"||p==="failed"||p==="decisions"||p==="outbox"||p==="handoffs")&&Xe(p)},[l]),_?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:L.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((p,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:L.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(Ff,{}),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(Td,{color:gf[x.connection],pulse:x.connection==="connected",title:[`Status: ${yo[x.connection]??x.connection}`,x.connection==="connected"?"Meaning: receiving live updates.":x.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${yf(x.lastSnapshotAt)}`,Vt?`Details: ${Vt.message}`:null].filter(Boolean).join(`
212
- `),children:yo[x.connection]??"Unknown"}),(zt>0||F>0)&&n.jsx(Ha,{className:"hidden md:flex",running:zt,blocked:F,decisionsCount:we?x.decisions.length:0,completedToday:cs,onDecisionsClick:()=>{y("activity"),z("initiatives"),W("initiatives"),Ae("in_progress"),Oe("needs_attention")},onBlockedClick:()=>{_e.length>0?(y("mission-control"),Ae("in_progress"),Oe("needs_attention")):Xe("blocked")},onNewInitiative:ps})]}),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:()=>y("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:()=>y("mission-control"),onMouseEnter:Un,onFocus:Un,"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:p=>{const A=p.target.value;h(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: ${f}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),k.map(p=>n.jsx("option",{value:p.id,children:p.title},p.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"})})]}),x.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",x.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Wn(!1),vn()},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:Ce,onClick:()=>Te(p=>!p),title:"Notifications","aria-haspopup":"dialog","aria-expanded":me,"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"})]}),Rn.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:Rn.length})]}),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"})]})}),n.jsx("button",{type:"button",onClick:()=>qt("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:g,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"})]}),me&&n.jsxs("div",{id:"header-notifications-panel",ref:Ye,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:[Rn.length>0&&n.jsx("button",{type:"button",onClick:Dn,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Te(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(Ha,{className:"max-w-full overflow-hidden",running:zt,blocked:F,decisionsCount:Ns,completedToday:cs,onDecisionsClick:()=>{y("activity"),W("initiatives"),z("initiatives"),Ae("in_progress"),Oe("needs_attention"),Te(!1)},onBlockedClick:()=>{_e.length>0?(y("mission-control"),Ae("in_progress"),Oe("needs_attention")):Xe("blocked"),Te(!1)}})}),Rn.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:ds>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:Rn.map(p=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:p.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:p.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:p.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(Sn,{type:p.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:p.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:p.message}),p.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=p.onAction)==null||A.call(p),Te(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:p.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>Ge(p.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"})]})},p.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:p=>{const A=p.target.value;h(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: ${f}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),k.map(p=>n.jsx("option",{value:p.id,children:p.title},p.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:()=>y("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:()=>y("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(tf,{initiatives:Is,activities:oe,agents:zs,runtimeInstances:x.runtimeInstances??[],workspaceInitiativeId:u,isLoading:_,authToken:null,embedMode:!1,connection:x.connection,lastSnapshotAt:x.lastSnapshotAt,error:v,hasApiKey:e.state.hasApiKey,onOpenSettings:()=>qt("orgx"),onRefresh:g,onCreateInitiative:ps,onPlayNextUp:At,onStartAutopilot:us,nextUpQueueModel:ht,nextUpActionsModel:Ot,snapshotVersion:x.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 ${ke!=="agents"?"hidden lg:flex":""}`,children:n.jsx(bm,{sessions:x.sessions,activity:oe,runtimeInstances:x.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:Ne,onSelectSession:Ze,onAgentFilter:te,agentFilter:K,timeFilterId:G,onReconnect:vn,onLaunched:g,connectionStatus:x.connection})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${ke!=="activity"?"hidden lg:flex":""}`,children:n.jsx(ef,{activity:Tn.items,sessions:se,sliceRuns:_e,initiatives:Z,timelineNarrative:x.timelineNarrative??[],workspaceId:u,chatSnapshot:x.chat,selectedRunIds:mn,selectedSessionLabel:Kn,selectedWorkstreamId:ge,selectedWorkstreamLabel:he,agentFilter:K,timeFilterId:G,onTimeFilterChange:Fn,customTimeRange:ae,onCustomTimeRangeChange:ve,hasMore:Tn.hasMore,isLoadingMore:Tn.isLoadingMore,onLoadMore:Tn.loadMore,onClearSelection:Fe,onClearWorkstreamFilter:Ke,onClearAgentFilter:wt,onFocusRunId:un,onOpenDecision:Xn,requestedActivityItemId:Pe,onActivityItemRequestHandled:()=>Se(null),onPlayNextUp:At,onStartAutopilot:us,onPauseWorkstream:Ws,onCreateInitiative:ps,onOpenMissionControl:()=>y("mission-control"),onOpenSettings:()=>qt("orgx"),onRefreshData:g,isLoading:_})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${ke!=="decisions"&&ke!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${$e==="initiatives"?"flex-1":"flex-shrink-0"} `,children:$e==="initiatives"?n.jsxs($s,{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 pt-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-4 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":Y==="in_progress",onClick:p=>{p.stopPropagation(),Ae("in_progress")},className:ue("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Y==="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:st}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Y==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":Y==="next_up",onClick:p=>{p.stopPropagation(),Ae("next_up")},className:ue("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Y==="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:as.total}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Y==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{As().catch(p=>{M(D(p instanceof Error?p.message:"","Autopilot action failed."))})},disabled:q,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":ln?"active":"idle",title:ln?"Stop autopilot":"Start autopilot","aria-label":ln?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:ue("h-3.5 w-3.5",ln?"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:ue("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",ln?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:ln?"On":"Off"})]})]}),Y==="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:()=>Oe("all"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Le==="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:st})]}),n.jsxs("button",{type:"button",onClick:()=>Oe("needs_attention"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Le==="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:Et})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Y==="in_progress"?Le==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[En.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(rf,{model:En,actions:Mn,onOpenDetail:an})})}),we?n.jsxs("section",{className:ue("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:x.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(sf,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:x.decisions,focusDecisionId:E,onFocusDecisionHandled:()=>P(null),onApproveDecision:C,onRejectDecision:U,onApproveAll:de,onBulkDecisionAction:ee,mutationState:pe})})})]}):n.jsx($s,{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:ue("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:we?"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(ju,{className:ue("h-full min-h-0"),title:we?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:_e,initiatives:Z,onOpenDecisions:()=>Xn(),onFocusRunId:un,onReviewActivity:Nn,onOpenSliceDetail:yn,onAcceptSlice:bn})})]})]}):n.jsx(hu,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:se,sliceRuns:_e,initiatives:Z,needsAttentionCount:Et,onSwitchToNeedsAttention:()=>Oe("needs_attention"),onOpenSession:Ze,onFocusRunId:un,onPlayWorkstream:Ss,onPauseWorkstream:Ws,onResumeWorkstream:Ss,onRestartSession:Hs,onIntervene:os,onOpenSliceDetail:Bt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(of,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:ht,queueActions:Ot,snapshotVersion:x.snapshotVersion,onOpenInitiative:fr,onOpenSliceDetail:Ut})})},`${Y}:${Le}`)]}):n.jsx($s,{className:"card-enter",children:n.jsxs("button",{onClick:()=>z("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(pt,{children:je&&vt&&n.jsxs(n.Fragment,{children:[n.jsx(ye.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:()=>Me(!1)},"session-drawer-backdrop"),n.jsxs(ye.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:L.cardBg},children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-subtle px-4 py-3",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Session Detail"}),n.jsx("button",{type:"button",onClick:()=>Me(!1),"aria-label":"Close session inspector",className:"inline-flex h-8 w-8 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:"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:"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(nf,{session:vt,activity:oe,initiatives:Z,sliceRuns:_e,initialInterventionDraft:B,onSubmitIntervention:ur,onOpenActivityItem:qs,onContinueHighestPriority:dr,onDispatchSession:it,onPauseSession:Us,onResumeSession:mr,onCancelSession:ms,onCreateCheckpoint:gt,onRollbackSession:pr,onStartInitiative:ps,onStartWorkstream:Ft})})})]},"session-drawer-panel")]})}),l==="activity"?n.jsx(Dd,{activeTab:ke,onTabChange:De,pendingDecisionCount:we?x.decisions.length:0}):null,n.jsx(ei,{open:It!==null,onClose:fe,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:(It==null?void 0:It.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(It==null?void 0:It.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:p=>Ht(p.target.value),onKeyDown:p=>{p.key==="Enter"&&_s()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(It==null?void 0:It.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:fe,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:_s,disabled:jn.trim().length===0||Tt,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:Tt?"Creating…":"Create"})]})]})}),ze.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(lf,{open:ze.open,onClose:()=>dt(p=>({...p,open:!1,focusAgentDomain:null})),activeTab:ze.tab,onChangeTab:p=>dt(A=>({...A,tab:p})),agentBehaviorInitialDomain:ze.focusAgentDomain,demoMode:t,onToggleDemoMode:p=>{Wn(p),p||vn()},devMode:a,onToggleDevMode:c,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:k,selectedWorkspaceId:u,onSelectWorkspace:h,onboarding:e,authToken:null,embedMode:!1})}),at&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(hf,{open:at,selectedWorkspaceId:u,onClose:()=>nt(!1)})}),(xe==="sessions"||xe==="active"||xe==="blocked"||xe==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(cf,{open:xe==="sessions"||xe==="active"||xe==="blocked"||xe==="failed",onClose:()=>Xe(null),mode:xe==="active"||xe==="blocked"||xe==="failed"?xe:"sessions",sessions:se,onOpenSession:p=>{Ze(p.id),Xe(null)},onRunAction:async(p,A)=>{await Qt(p,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>g(),onSetNotice:p=>M(p)})}),xe==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(df,{open:xe==="decisions",onClose:()=>Xe(null),decisions:we?x.decisions:[],onApproveDecision:C,onRejectDecision:U,onApproveAll:de,onBulkDecisionAction:ee})}),xe==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(uf,{open:xe==="outbox",onClose:()=>Xe(null),outbox:x.outbox,onOpenSettings:()=>{Xe(null),qt("orgx")},onRefresh:()=>{g()}})}),xe==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(mf,{open:xe==="handoffs",onClose:()=>Xe(null),handoffs:x.handoffs})}),n.jsx($f,{}),Gt&&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(af,{item:Gt,actions:Mn,onClose:()=>Lt(null),onNavigate:is,currentIndex:Zt,totalCount:ut.length,decisions:we?x.decisions:void 0,onApproveDecision:C,onRejectDecision:U})})})}),Je&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ff,{target:Je,onClose:()=>jt(null),onPlayWorkstream:async(p,A,$)=>{const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A,agentId:$??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const H=await S.json().catch(()=>null);M(D((H==null?void 0:H.error)??(H==null?void 0:H.message)??null,`Failed to dispatch workstream (${S.status})`));return}M("Dispatched workstream."),g()},onStartAutoContinue:async(p,A,$)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,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:p,agentId:$??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const H=await S.json().catch(()=>null);M(D((H==null?void 0:H.error)??(H==null?void 0:H.message)??null,`Failed to start auto-continue (${S.status})`));return}M("Auto-continue started."),g()},onMoveWorkstream:async(p,A,$)=>{const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A,placement:$})});if(!S.ok){const H=await S.json().catch(()=>null);M(D((H==null?void 0:H.error)??(H==null?void 0:H.message)??null,`Move failed (${S.status})`));return}M(`Moved workstream to ${$}.`),g()},onRemoveFromQueue:async(p,A)=>{const $=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A})});if(!$.ok){const S=await $.json().catch(()=>null);M(D((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${$.status})`));return}M("Removed workstream from queue."),g()},onOpenSession:Ze,onFocusRunId:un,onOpenInitiative:fr,onReviewActivity:Nn,onOpenDecisions:()=>Xn(),onAcceptSlice:bn,onRejectSlice:rs})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Rc();const Of=new kl({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});wl.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(vl,{client:Of,children:n.jsx(Rf,{})})}));export{Vf as $,Rt as A,ed as B,Xf as C,Qn as D,Sn as E,Zn as F,Mm as G,Kf as H,Yf as I,Fs as J,St as K,Ps as L,Vr as M,yd as N,bd as O,$s as P,Yt as Q,Nd as R,Qf as S,Sd as T,qc as U,Dl as V,Gf as W,Yd as X,Jf as Y,In as Z,qd as _,Au as a,Ks as a0,qr as a1,kt as b,bc as c,L as d,Ku as e,sh as f,ys as g,Cn as h,Mt as i,Zf as j,Xo as k,th as l,nh as m,Dt as n,eh as o,zc as p,Bn as q,ei as r,rh as s,Su as t,nd as u,ss as v,ue as w,$t as x,qn as y,Yn as z};