@useorgx/openclaw-plugin 0.7.2 → 0.7.4

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 (112) hide show
  1. package/dashboard/dist/assets/{CgaottFX.js → B1mDqDdy.js} +1 -1
  2. package/dashboard/dist/assets/B1mDqDdy.js.br +0 -0
  3. package/dashboard/dist/assets/B1mDqDdy.js.gz +0 -0
  4. package/dashboard/dist/assets/BDMstdfu.js +1 -0
  5. package/dashboard/dist/assets/BDMstdfu.js.br +0 -0
  6. package/dashboard/dist/assets/BDMstdfu.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/{8dksYiq4.js → BXapfumA.js} +1 -1
  11. package/dashboard/dist/assets/BXapfumA.js.br +0 -0
  12. package/dashboard/dist/assets/BXapfumA.js.gz +0 -0
  13. package/dashboard/dist/assets/BZZKPNDb.css +1 -0
  14. package/dashboard/dist/assets/BZZKPNDb.css.br +0 -0
  15. package/dashboard/dist/assets/BZZKPNDb.css.gz +0 -0
  16. package/dashboard/dist/assets/{rttbDbEx.js → BdusVDcP.js} +1 -1
  17. package/dashboard/dist/assets/BdusVDcP.js.br +0 -0
  18. package/dashboard/dist/assets/BdusVDcP.js.gz +0 -0
  19. package/dashboard/dist/assets/{D8JNX8kq.js → BwkNYH6r.js} +1 -1
  20. package/dashboard/dist/assets/BwkNYH6r.js.br +0 -0
  21. package/dashboard/dist/assets/BwkNYH6r.js.gz +0 -0
  22. package/dashboard/dist/assets/{CzCxAZlW.js → CRhvoVeH.js} +1 -1
  23. package/dashboard/dist/assets/CRhvoVeH.js.br +0 -0
  24. package/dashboard/dist/assets/CRhvoVeH.js.gz +0 -0
  25. package/dashboard/dist/assets/{B6wPWJ35.js → CYchPSem.js} +1 -1
  26. package/dashboard/dist/assets/CYchPSem.js.br +0 -0
  27. package/dashboard/dist/assets/CYchPSem.js.gz +0 -0
  28. package/dashboard/dist/assets/Cn07669c.js +212 -0
  29. package/dashboard/dist/assets/Cn07669c.js.br +0 -0
  30. package/dashboard/dist/assets/Cn07669c.js.gz +0 -0
  31. package/dashboard/dist/assets/{C8uM3AX8.js → DBG89Wsz.js} +1 -1
  32. package/dashboard/dist/assets/DBG89Wsz.js.br +0 -0
  33. package/dashboard/dist/assets/DBG89Wsz.js.gz +0 -0
  34. package/dashboard/dist/assets/{CZaT3ob_.js → DHoYGJ9i.js} +1 -1
  35. package/dashboard/dist/assets/DHoYGJ9i.js.br +0 -0
  36. package/dashboard/dist/assets/DHoYGJ9i.js.gz +0 -0
  37. package/dashboard/dist/assets/DHtZPEKd.js +1 -0
  38. package/dashboard/dist/assets/DHtZPEKd.js.br +0 -0
  39. package/dashboard/dist/assets/DHtZPEKd.js.gz +0 -0
  40. package/dashboard/dist/assets/{B5zYRHc3.js → DUaqjbT7.js} +1 -1
  41. package/dashboard/dist/assets/DUaqjbT7.js.br +0 -0
  42. package/dashboard/dist/assets/DUaqjbT7.js.gz +0 -0
  43. package/dashboard/dist/assets/{IUexzymk.js → Dlz0Cm_E.js} +1 -1
  44. package/dashboard/dist/assets/Dlz0Cm_E.js.br +0 -0
  45. package/dashboard/dist/assets/Dlz0Cm_E.js.gz +0 -0
  46. package/dashboard/dist/assets/{CC63EwFD.js → E8q3xNGK.js} +1 -1
  47. package/dashboard/dist/assets/E8q3xNGK.js.br +0 -0
  48. package/dashboard/dist/assets/E8q3xNGK.js.gz +0 -0
  49. package/dashboard/dist/assets/VH0fzk6I.js +1 -0
  50. package/dashboard/dist/assets/VH0fzk6I.js.br +0 -0
  51. package/dashboard/dist/assets/VH0fzk6I.js.gz +0 -0
  52. package/dashboard/dist/assets/bxgRC96y.js +1 -0
  53. package/dashboard/dist/assets/bxgRC96y.js.br +0 -0
  54. package/dashboard/dist/assets/bxgRC96y.js.gz +0 -0
  55. package/dashboard/dist/index.html +2 -2
  56. package/dashboard/dist/index.html.br +0 -0
  57. package/dashboard/dist/index.html.gz +0 -0
  58. package/dist/http/helpers/auto-continue-engine.js +29 -11
  59. package/dist/http/helpers/autopilot-slice-utils.js +7 -10
  60. package/dist/http/helpers/openclaw-cli.js +2 -2
  61. package/dist/http/index.js +160 -4
  62. package/dist/http/routes/live-legacy.d.ts +2 -0
  63. package/dist/http/routes/live-legacy.js +97 -0
  64. package/dist/http/routes/mission-control-read.js +106 -63
  65. package/dist/openclaw-settings.js +3 -2
  66. package/dist/openclaw.plugin.json +1 -1
  67. package/dist/sync/outbox-replay.js +17 -8
  68. package/openclaw.plugin.json +1 -1
  69. package/package.json +1 -1
  70. package/dashboard/dist/assets/6mILZQ2a.js +0 -1
  71. package/dashboard/dist/assets/6mILZQ2a.js.br +0 -0
  72. package/dashboard/dist/assets/6mILZQ2a.js.gz +0 -0
  73. package/dashboard/dist/assets/8dksYiq4.js.br +0 -0
  74. package/dashboard/dist/assets/8dksYiq4.js.gz +0 -0
  75. package/dashboard/dist/assets/B5zYRHc3.js.br +0 -0
  76. package/dashboard/dist/assets/B5zYRHc3.js.gz +0 -0
  77. package/dashboard/dist/assets/B6wPWJ35.js.br +0 -0
  78. package/dashboard/dist/assets/B6wPWJ35.js.gz +0 -0
  79. package/dashboard/dist/assets/BWEwjt1W.js +0 -1
  80. package/dashboard/dist/assets/BWEwjt1W.js.br +0 -0
  81. package/dashboard/dist/assets/BWEwjt1W.js.gz +0 -0
  82. package/dashboard/dist/assets/BzRbDCAD.css +0 -1
  83. package/dashboard/dist/assets/BzRbDCAD.css.br +0 -0
  84. package/dashboard/dist/assets/BzRbDCAD.css.gz +0 -0
  85. package/dashboard/dist/assets/C8uM3AX8.js.br +0 -0
  86. package/dashboard/dist/assets/C8uM3AX8.js.gz +0 -0
  87. package/dashboard/dist/assets/C9jy61eu.js +0 -212
  88. package/dashboard/dist/assets/C9jy61eu.js.br +0 -0
  89. package/dashboard/dist/assets/C9jy61eu.js.gz +0 -0
  90. package/dashboard/dist/assets/CC63EwFD.js.br +0 -0
  91. package/dashboard/dist/assets/CC63EwFD.js.gz +0 -0
  92. package/dashboard/dist/assets/CZaT3ob_.js.br +0 -0
  93. package/dashboard/dist/assets/CZaT3ob_.js.gz +0 -0
  94. package/dashboard/dist/assets/CgaottFX.js.br +0 -0
  95. package/dashboard/dist/assets/CgaottFX.js.gz +0 -0
  96. package/dashboard/dist/assets/CzCxAZlW.js.br +0 -0
  97. package/dashboard/dist/assets/CzCxAZlW.js.gz +0 -0
  98. package/dashboard/dist/assets/D3iMTYEj.js +0 -1
  99. package/dashboard/dist/assets/D3iMTYEj.js.br +0 -0
  100. package/dashboard/dist/assets/D3iMTYEj.js.gz +0 -0
  101. package/dashboard/dist/assets/D8JNX8kq.js.br +0 -0
  102. package/dashboard/dist/assets/D8JNX8kq.js.gz +0 -0
  103. package/dashboard/dist/assets/DnA8dpj6.js +0 -1
  104. package/dashboard/dist/assets/DnA8dpj6.js.br +0 -0
  105. package/dashboard/dist/assets/DnA8dpj6.js.gz +0 -0
  106. package/dashboard/dist/assets/IUexzymk.js.br +0 -0
  107. package/dashboard/dist/assets/IUexzymk.js.gz +0 -0
  108. package/dashboard/dist/assets/ic2FaMnh.js +0 -1
  109. package/dashboard/dist/assets/ic2FaMnh.js.br +0 -0
  110. package/dashboard/dist/assets/ic2FaMnh.js.gz +0 -0
  111. package/dashboard/dist/assets/rttbDbEx.js.br +0 -0
  112. package/dashboard/dist/assets/rttbDbEx.js.gz +0 -0
@@ -0,0 +1,212 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BDMstdfu.js","assets/cNrhgGc1.js","assets/C-KIc3Wc.js","assets/BJgZIVUQ.js","assets/qm8xLgv-.css","assets/bxgRC96y.js","assets/DHoYGJ9i.js","assets/CxQ08qFN.js","assets/DBG89Wsz.js","assets/Dlz0Cm_E.js","assets/CYchPSem.js","assets/BdusVDcP.js","assets/CL_wXqR7.js","assets/BTAEErUY.js","assets/DHtZPEKd.js","assets/BwkNYH6r.js","assets/DUaqjbT7.js","assets/B1mDqDdy.js","assets/BXapfumA.js","assets/CRhvoVeH.js","assets/VH0fzk6I.js","assets/E8q3xNGK.js"])))=>i.map(i=>d[i]);
2
+ var $l=Object.defineProperty;var Fl=(e,t,s)=>t in e?$l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var er=(e,t,s)=>Fl(e,typeof t!="symbol"?t+"":t,s);import{r as o,u as oa,a as fs,b as xn,j as n,c as Pl,d as Ol,D as Aa,e as Bl,Q as ql}from"./cNrhgGc1.js";import{b as zl}from"./C-KIc3Wc.js";import{m as ye,A as bt,u as Xn}from"./CxQ08qFN.js";import{F as Wl,T as Ul}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 Hl="modulepreload",Kl=function(e){return"/orgx/live/"+e},Sa={},zt=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(g=>Promise.resolve(g).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=Kl(u),u in Sa)return;Sa[u]=!0;const g=u.endsWith(".css"),y=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${y}`))return;const v=document.createElement("link");if(v.rel=g?"stylesheet":Hl,g||(v.as="script"),v.crossOrigin="",v.href=u,d&&v.setAttribute("nonce",d),document.head.appendChild(v),g)return new Promise((f,k)=>{v.addEventListener("load",f),v.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)})},_a=()=>{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()}}},hi="all";function Kn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Vl(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return Kn(e.get("workspace_id"))??Kn(e.get("workspaceId"))??Kn(e.get("command_center_id"))??Kn(e.get("commandCenterId"))??Kn(e.get("center"))??Kn(e.get("project_id"))??Kn(e.get("projectId"))}catch{return null}}function hs(e,t,s){const r=Kn(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",hi),e.set("command_center_id",hi),e.set("center",hi));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function Gl(e){const t=Kn(e);return t?{"x-orgx-workspace-id":t}:{}}function _t(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??Vl();return Object.assign(t,Gl(s)),t}const Xl=[[/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 gr(e){if(!e)return"";for(const[s,r]of Xl)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const Uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ho=/^[0-9a-f]{20,}$/i;function ds(e){return Uo.test(e)?`#${e.slice(0,4)}`:Ho.test(e)?`#${e.slice(0,4)}`:e}function Gn(e){return Uo.test(e)||Ho.test(e)}function _s(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=>gr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>_s(s)),t}function Bt(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=>_s(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 pr(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 In(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.":Bt(ot(e))}function Ql(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 Jl(e){const t=e.metadata??{},s=Ps(t,"task_title")??Ps(t,"workstream_title"),r=s?Bt(String(s)):e.title?Bt(e.title):null,i=Ps(t,"user_summary")??Ps(t,"summary"),a=i?Bt(String(i)):e.summary?Bt(e.summary):e.description?Bt(e.description):null,c=Ps(t,"next_step")??Ps(t,"nextStep"),l=c?Bt(String(c)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:l&&(l===r||l===a)?null:l}}function Ps(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const Yl={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 tr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Yl[t]??e.replace(/_/g," ")}const Zl={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function mh(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Zl[t]??e.replace(/_/g," ")}function ph(e,t){return e.toLowerCase().includes("path")?_s(t):Gn(t)?ds(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return Gn(i)?ds(i):i}).join(", "):Bt(t)}function ec(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 fh(e){const t=ec(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 Mt(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 tc=8e3,nc=320,sc=300,rc=80,ic=80,ac=120,Ca=6e4,oc=3500,lc=180,la={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Ir={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ms={threads:[],total:0,updatedAt:null},Ma={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},Ko=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Ar=10*6e4;function cc(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 dc(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=>In(a)).filter(a=>a.length>0).join(" ")}function uc(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 In(s.length>0?s:e.trim())}function mc(e){const t=e.map(s=>uc(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function pt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Jr(e,t){const s=Ma[e.status]??99,r=Ma[t.status]??99;if(s!==r)return s-r;const i=pt(e.updatedAt??e.lastEventAt??e.startedAt),a=pt(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function pc(e){return(e??"").trim().toLowerCase()}function Ta(e){return Ko.has(pc(e.status))}function gi(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Ea(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const f=Date.now(),k=e.nodes.filter(w=>{const b=pt(w.updatedAt??w.lastEventAt??w.startedAt);if(Ta(w))return!0;const _=["completed","archived","failed"].includes((w.status??"").toLowerCase())?Ar/3:Ar;return f-b<=_});if(!k.length)return t;const x=new Set(k.map(w=>w.id)),j=new Set(k.map(w=>w.groupId));return{nodes:k.sort(Jr),edges:e.edges.filter(w=>x.has(w.parentId)&&x.has(w.childId)),groups:e.groups.filter(w=>j.has(w.id))}}const s=new Set,r=[...t.nodes];for(const f of t.nodes)for(const k of gi(f))s.add(k);const i=Date.now(),a=[];for(const f of e.nodes){if(gi(f).some(h=>s.has(h)))continue;const x=pt(f.updatedAt??f.lastEventAt??f.startedAt),w=["completed","archived","failed"].includes((f.status??"").toLowerCase())?Ar/3:Ar,b=i-x<=w;if(Ta(f)||b){a.push(f),r.push(f);for(const h of gi(f))s.add(h)}}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 g=f=>`${f.parentId}->${f.childId}`,y=new Set,v=[];for(const f of t.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=g(f);y.has(k)||(y.add(k),v.push(f))}for(const f of e.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=g(f);y.has(k)||(y.add(k),v.push(f))}return{nodes:r.sort(Jr),edges:v,groups:u}}function nr(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Jr).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 La(e,t){return e.length<=t?e:[...e].sort((s,r)=>pt(r.updatedAt)-pt(s.updatedAt)).slice(0,t)}function fc(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()-pt(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 Vo(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 Da(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 Ra(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 $a(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 Go(e){if(!e||typeof e!="object")return la;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 hc(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 gc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function js(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 xc=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 yc(e){const t=gc(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"";if(!r||!xc.has(r))return null;const i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??js(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=js(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??js(t,["initiative_id","initiativeId"]),l=js(t,["workstream_id","workstreamId"]),d=js(t,["task_id","taskId"]),u=js(t,["stop_reason","stopReason"]),g=js(t,["parsed_status","parsedStatus"]),y=(e.title??"").trim().toLowerCase();return!i&&!a&&!l&&!d?null:[r,c??"",l??"",d??"",i??"",a??"",u??"",g??"",y].join("|")}function Xo(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=yc(a);if(!(c&&r.has(c))&&(c&&r.add(c),i.push(a),i.length>=t))break}return i}function bc(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=pt(d.timestamp)-pt(l.timestamp);return u!==0?u:d.id.localeCompare(l.id)}),c=Xo(a,s);return Vo(e,c)?e:c}function xi(e,t){const s=[...e].sort((r,i)=>{const a=pt(i.timestamp)-pt(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Xo(s,t)}function Fa(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(fc).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:pt(c.requestedAt??c.updatedAt)-pt(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 Pa(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 wc(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 vc(e,t){return!!(Ko.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function Sr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function yi(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 kc(e,t,s){const r=new Map,i=[...e].sort((l,d)=>pt(d.timestamp)-pt(l.timestamp));for(const l of i){if(!l.runId)continue;const d=l.runId,u=r.get(d),g=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:Pa(l.type),progress:null,initiativeId:y,workstreamId:null,groupId:y??"unscoped",groupLabel:Sr(y),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:l.title,blockers:l.type==="blocker_created"&&l.description?[l.description]:[]});continue}(!u.startedAt||pt(g)<pt(u.startedAt))&&(u.startedAt=g),pt(g)>=pt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=g,u.lastEventAt=g,u.lastEventSummary=l.title,u.status=Pa(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=Sr(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),g=wc(l.status),y=new Date().toISOString(),v=vc(l,g),f=l.startedAt??(v?y:null),k=l.initiativeId??null,x=l.currentTask&&l.currentTask.trim().length>0?l.currentTask.trim():`${l.name??l.id} ${g==="archived"?"idle":g}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:x,agentId:l.id,agentName:l.name??l.id,status:g,progress:null,initiativeId:k,workstreamId:null,groupId:k??"unscoped",groupLabel:Sr(k),startedAt:f,updatedAt:f,lastEventAt:f,lastEventSummary:l.currentTask,blockers:yi(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=x),v&&(u.updatedAt=f??u.updatedAt??y,u.lastEventAt=f??u.lastEventAt??y),u.status==="archived"&&g!=="archived"&&(u.status=g),yi(l.blockers).length>0&&(u.blockers=yi(l.blockers)),k&&!u.initiativeId&&(u.initiativeId=k,u.groupId=k,u.groupLabel=Sr(k))}const a=Array.from(r.values()).sort(Jr).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 jc(e,t,s){var g;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=(((g=y.headers.get("content-type"))==null?void 0:g.toLowerCase())??"").includes("application/json");if(!y.ok){let k=`${y.status} ${y.statusText}`;if(f){const x=await y.json().catch(()=>null);x!=null&&x.error&&(k=`${y.status} ${x.error}`)}else{const x=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);x.length>0&&(k=`${y.status} ${x}`)}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 v=y instanceof Error?y.message:"Network error",f=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return y instanceof DOMException&&y.name==="AbortError"||cc(v)?{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:v}}finally{d&&clearTimeout(d),u&&u()}}function Nc(e,t,s,r,i=[],a=la,c=null,l=1,d=[],u=Ms,g){var k,x,j;const y=((k=t[0])==null?void 0:k.timestamp)??null,v=((x=r[0])==null?void 0:x.requestedAt)??((j=r[0])==null?void 0:j.updatedAt)??null,f=pt(y)>=pt(v)?y:v;return{connection:"connected",lastActivity:f?Mt(f):null,lastSnapshotAt:c,snapshotVersion:l,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:Go(a),chat:zr(u),runtimeInstances:d,workSliceProjections:(g==null?void 0:g.workSliceProjections)??[],timelineNarrative:(g==null?void 0:g.timelineNarrative)??[],nextUpByInitiative:(g==null?void 0:g.nextUpByInitiative)??[],runningWorkSlices:(g==null?void 0:g.runningWorkSlices)??0,needsInputTotal:(g==null?void 0:g.needsInputTotal)??0,failedActionableTotal:(g==null?void 0:g.failedActionableTotal)??0,completedTodayTotal:(g==null?void 0:g.completedTodayTotal)??0,consistencyFlags:(g==null?void 0:g.consistencyFlags)??[],dataHealth:g==null?void 0:g.dataHealth}}function Oa(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)=>pt(r.lastEventAt??r.lastHeartbeatAt)-pt(s.lastEventAt??s.lastHeartbeatAt))}function Ba(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)=>pt(r.lastActivityAt??r.updatedAt)-pt(s.lastActivityAt??s.updatedAt))}function zr(e){if(!e||typeof e!="object")return Ms;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??Ms,r=t??Ms;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 Wr(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,g=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:g,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)=>pt(i.updatedAt??i.lastEventAt)-pt(r.updatedAt??r.lastEventAt))}function _r(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)=>pt(r.updatedAt??r.completedAt??r.failedAt)-pt(s.updatedAt??s.completedAt??s.failedAt))}function bi(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;r&&t.set(r,{...s,sliceRunId:r,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,r)=>pt(r.occurredAt)-pt(s.occurredAt))}function wi(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 qa(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(g=>({id:g.artifactId,type:g.type,title:g.title,url:g.url,createdAt:g.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 Wr(t)}function Sc(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 _c(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 Mc(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 Tc(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 Ec(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 Lc(e={}){const{enabled:t=!0,pollInterval:s=tc,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=nc,maxActivityItems:d=sc,maxHandoffs:u=rc,maxDecisions:g=ic,batchWindowMs:y=ac}=e,v=typeof a=="string"&&a.trim().length>0?a.trim():null,f=typeof c=="string"&&c.trim().length>0?c.trim():null,[k,x]=o.useState(_a()),[j,w]=o.useState(Ir),[b,h]=o.useState(!r),[_,U]=o.useState(null),le=o.useRef(),V=o.useRef(null),be=o.useRef(null),[H,Z]=o.useState(!1),ce=o.useRef(0),xe=o.useRef(!1),we=o.useRef(`${v??"__all__"}::${f??"__all__"}`),K=o.useRef(!1),Ie=o.useRef(null),Ee=o.useCallback((P,Y)=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null),w(P),Y!=null&&Y.autoResetMs&&Y.autoResetMs>0&&(Ie.current=setTimeout(()=>{Ie.current=null,w(Ir)},Y.autoResetMs))},[]);o.useEffect(()=>()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]),o.useEffect(()=>{const P=`${v??"__all__"}::${f??"__all__"}`;we.current!==P&&(we.current=P,K.current=!0,Ee(Ir),x(Y=>({...Y,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ms,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(Y.snapshotVersion??0)+1})),h(!0),U(null))},[v,f,Ee]);const fe=o.useCallback((P,Y,oe,ve=null,je=null,te=null,Te=null,pe=null,C=null,O=null)=>{ce.current=Date.now(),xe.current=!1,x(W=>{const se=K.current;se&&(K.current=!1);const De=Y===null?se?[]:W.activity:xi(Y,d),qe=oe===null?se?[]:W.handoffs:La(oe,u),Me=nr(P===null?se?{nodes:[],edges:[],groups:[]}:W.sessions:se?nr(P,l):Ea(W.sessions,nr(P,l)),l),M=ve===null?se?[]:W.decisions:Fa(ve,g),q=je===null?se?[]:W.sliceRuns:Wr(je),ie=te===null?se?la:W.outbox:Go(te),de=pe===null?se?[]:W.runtimeInstances??[]:Oa(pe),Ce=C===null?se?Ms:W.chat??Ms:zr(C),Ze=(O==null?void 0:O.workSliceProjections)==null?se?[]:W.workSliceProjections??[]:_r(O.workSliceProjections),Je=(O==null?void 0:O.timelineNarrative)==null?se?[]:W.timelineNarrative??[]:bi(O.timelineNarrative),Fe=(O==null?void 0:O.nextUpByInitiative)==null?se?[]:W.nextUpByInitiative??[]:wi(O.nextUpByInitiative),Ge=typeof(O==null?void 0:O.runningWorkSlices)=="number"&&Number.isFinite(O.runningWorkSlices)?Math.max(0,Math.floor(O.runningWorkSlices)):W.runningWorkSlices??0,He=typeof(O==null?void 0:O.needsInputTotal)=="number"&&Number.isFinite(O.needsInputTotal)?Math.max(0,Math.floor(O.needsInputTotal)):W.needsInputTotal??0,ft=typeof(O==null?void 0:O.failedActionableTotal)=="number"&&Number.isFinite(O.failedActionableTotal)?Math.max(0,Math.floor(O.failedActionableTotal)):W.failedActionableTotal??0,it=typeof(O==null?void 0:O.completedTodayTotal)=="number"&&Number.isFinite(O.completedTodayTotal)?Math.max(0,Math.floor(O.completedTodayTotal)):W.completedTodayTotal??0,at=(O==null?void 0:O.consistencyFlags)==null?W.consistencyFlags??[]:O.consistencyFlags.filter(Ae=>typeof Ae=="string"),he=(O==null?void 0:O.dataHealth)===void 0||(O==null?void 0:O.dataHealth)===null?W.dataHealth:O.dataHealth,Ke=(W.snapshotVersion??0)+1;return Da(W.sessions,Me)&&Vo(W.activity,De)&&Ra(W.handoffs,qe)&&$a(W.decisions,M)&&Sc(W.sliceRuns,q)&&hc(W.outbox,ie)&&Ac(W.chat,Ce)&&Ba(W.runtimeInstances,de)&&_c(W.workSliceProjections??[],Ze)&&Cc(W.timelineNarrative??[],Je)&&Mc(W.nextUpByInitiative??[],Fe)&&(W.runningWorkSlices??0)===Ge&&(W.needsInputTotal??0)===He&&(W.failedActionableTotal??0)===ft&&(W.completedTodayTotal??0)===it&&Tc(W.consistencyFlags??[],at)&&Ec(W.dataHealth,he)&&W.lastSnapshotAt===Te&&W.connection==="connected"?W:Nc(Me,De,qe,M,q,ie,Te,Ke,de,Ce,{workSliceProjections:Ze,timelineNarrative:Je,nextUpByInitiative:Fe,runningWorkSlices:Ge,needsInputTotal:He,failedActionableTotal:ft,completedTodayTotal:it,consistencyFlags:at,dataHealth:he})}),h(!1)},[d,g,u,l]),ee=o.useCallback(async()=>{if(!t){x(oe=>oe.connection==="disconnected"?oe:{...oe,connection:"disconnected"}),h(!1),U(null);return}const P=`${v??"__all__"}::${f??"__all__"}`;if(V.current&&be.current===P)return V.current;if(r){x(_a()),h(!1);return}const Y=(async()=>{try{const oe=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(g),include_idle:"true"});f&&hs(oe,f),v&&oe.set("initiative",v);const ve=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${oe.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${oe.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${oe.toString()}`}],je=[];let te=null,Te=!1;for(let Q=0;Q<ve.length;Q+=1){const Ne=ve[Q];Q>0&&await new Promise($e=>{setTimeout($e,lc)});const Re=await jc(Ne.url,{headers:_t({workspaceId:f})},{timeoutMs:oc});if(Re.ok&&Re.data){te=Re.data;break}(Re.status===401||Re.status===403)&&(Te=!0),je.push(`${Ne.label}: ${Re.error??"unavailable"}`)}if(!te){if(Te){const Q=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw Q.code="ORGX_AUTH",Q}throw new Error(dc(je))}if(we.current!==P)return;const pe=Array.isArray(te.degraded)?te.degraded.filter(Q=>typeof Q=="string"):[],C=pe.map(Q=>Q.toLowerCase()),O=(...Q)=>C.some(Ne=>Q.some(Re=>Ne.includes(Re))),W=Array.isArray(te.activity)?te.activity:[],se=Array.isArray(te.handoffs)?te.handoffs:[],De=Array.isArray(te.decisions)?te.decisions:[],qe=W.length===0&&O("activity unavailable","activity local fallback failed"),Me=O("sessions unavailable","sessions local fallback failed"),M=se.length===0&&O("handoffs unavailable"),q=De.length===0&&O("decisions unavailable"),ie=_r(Array.isArray(te.projections)?te.projections:[]),de=zr(te.chat??null),Ce=bi(Array.isArray(te.timelineNarrative)?te.timelineNarrative:[]),Ze=wi(Array.isArray(te.nextUpByInitiative)?te.nextUpByInitiative:[]),Je=ie.length>0?qa(ie):Wr(Array.isArray(te.sliceRuns)?te.sliceRuns:[]),Fe=te.sessions&&Array.isArray(te.sessions.nodes)&&Array.isArray(te.sessions.edges)&&Array.isArray(te.sessions.groups)?te.sessions:kc(W,te.agents,l),Ge=Je.length===0&&ie.length===0&&O("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),He=Ze.length===0&&O("next-up unavailable","next-up queue"),ft=qe?null:W,it=M?null:se,at=q?null:De,he=Me&&Fe.nodes.length===0?null:Fe,Ke=Ge?null:ie,Ae=Ge?null:Ce,B=Ge?null:Je,Pe=He?null:Ze;fe(he,ft,it,at,B,te.outbox??null,te.generatedAt??null,te.runtimeInstances??null,de,{workSliceProjections:Ke,timelineNarrative:Ae,nextUpByInitiative:Pe,runningWorkSlices:Ge?null:te.runningWorkSlices??null,needsInputTotal:Ge?null:te.needsInput??null,failedActionableTotal:Ge?null:te.failedActionable??null,completedTodayTotal:Ge?null:te.completedToday??null,consistencyFlags:Array.isArray(te.consistencyFlags)?te.consistencyFlags:null,dataHealth:te.dataHealth??null});const z=pe.length>0?mc(pe):[];z.length>0?(U(`Partial live data: ${z.join("; ")}`),x(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}),Z(!1)):(U(null),x(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}))}catch(oe){if(we.current!==P)return;const ve=oe instanceof Error?oe.message:"Unknown error",je=!!(oe&&typeof oe=="object"&&"code"in oe&&oe.code==="ORGX_AUTH");je&&(xe.current=!0);const te=ce.current>0&&Date.now()-ce.current>Ca;U(ve),x(Te=>{const pe=je||te?"disconnected":"reconnecting";return Te.connection===pe?Te:{...Te,connection:pe}}),Z(!je),h(!1)}finally{be.current===P&&(V.current=null,be.current=null)}})();return V.current=Y,be.current=P,Y},[fe,t,i,d,g,u,l,f,v,r]),re=o.useCallback(async(P,Y,oe)=>{var C,O,W;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const ve=Array.from(new Set(P.filter(Boolean)));if(ve.length===0)return{updated:0,failed:0};const je=((C=oe==null?void 0:oe.note)==null?void 0:C.trim())||void 0,te=((O=oe==null?void 0:oe.optionId)==null?void 0:O.trim())||void 0;if(r){const se=new Set(ve);return x(De=>{const qe=De.decisions.filter(ie=>se.has(ie.id));if(qe.length===0)return De;const Me=new Date().toISOString(),M=qe.map(ie=>({id:`decision:${Y}:${ie.id}:${Date.now()}`,type:"decision_resolved",title:Y==="approve"?`Approved: ${ie.title}`:`Rejected: ${ie.title}`,description:ie.context,agentId:null,agentName:ie.agentName,requesterAgentId:null,requesterAgentName:ie.agentName??null,executorAgentId:null,executorAgentName:ie.agentName??null,runId:null,initiativeId:null,timestamp:Me,metadata:{decisionId:ie.id,action:Y}})),q=xi(M.concat(De.activity),d);return{...De,decisions:De.decisions.filter(ie=>!se.has(ie.id)),activity:q,lastActivity:Mt(Me)}}),{updated:se.size,failed:0,firstError:void 0}}const Te=new Date().toISOString(),pe=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:_t({contentTypeJson:!0,workspaceId:f}),body:JSON.stringify({ids:ve,action:Y,...je?{note:je}:{},...te?{option_id:te}:{}})});try{const se=await pe.json().catch(()=>null),De=Array.isArray(se==null?void 0:se.results)?se.results:[],qe=new Set(De.filter(de=>de.ok).map(de=>de.id)),M=((W=De.filter(de=>!de.ok).find(de=>typeof de.error=="string"&&de.error.trim().length>0))==null?void 0:W.error)??(typeof(se==null?void 0:se.error)=="string"&&se.error.trim().length>0?se.error:void 0);if(!pe.ok&&pe.status!==207){const de=M??`Decision action failed (${pe.status})`;throw new Error(de)}if(qe.size===0&&pe.ok&&((se==null?void 0:se.failed)??0)===0)for(const de of ve)qe.add(de);qe.size>0?x(de=>{const Ce=de.decisions.filter(He=>qe.has(He.id));if(Ce.length===0)return de;const Ze=new Date().toISOString(),Je=Ce.map(He=>({id:`decision:${Y}:${He.id}:${Date.now()}`,type:"decision_resolved",title:Y==="approve"?`Approved: ${He.title}`:`Rejected: ${He.title}`,description:He.context,agentId:null,agentName:He.agentName,requesterAgentId:null,requesterAgentName:He.agentName??null,executorAgentId:null,executorAgentName:He.agentName??null,runId:null,initiativeId:null,timestamp:Ze,metadata:{decisionId:He.id,action:Y}})),Fe=xi(Je.concat(de.activity),d);return{...de,decisions:de.decisions.filter(He=>!qe.has(He.id)),activity:Fe,lastActivity:Mt(Ze)}}):pe.ok&&ve.length>0&&x(de=>({...de,decisions:de.decisions.filter(Ce=>!ve.includes(Ce.id))})),ee();const q=(se==null?void 0:se.updated)??qe.size,ie=(se==null?void 0:se.failed)??Math.max(0,ve.length-qe.size);return Ee({phase:ie>0?"error":"success",action:Y,targetCount:ve.length,message:ie>0?`${Y==="approve"?"Approve":"Reject"} completed with ${ie} failure${ie===1?"":"s"}.`:Y==="approve"?`Approved ${q} decision${q===1?"":"s"}.`:`Rejected ${q} decision${q===1?"":"s"}.`,startedAt:Te,completedAt:new Date().toISOString()},{autoResetMs:ie>0?8e3:4e3}),{updated:q,failed:ie,firstError:M}}catch(se){throw Ee({phase:"error",action:Y,targetCount:ve.length,message:se instanceof Error?se.message:"Decision update failed.",startedAt:Te,completedAt:new Date().toISOString()}),se}},[i,ee,d,f,Ee,r]),Le=o.useCallback(async(P,Y)=>re([P],"approve",Y),[re]),ne=o.useCallback(async(P,Y)=>re([P],"reject",Y),[re]),R=o.useCallback(async()=>{let P=[];return x(Y=>(P=Y.decisions.map(oe=>oe.id),Y)),P.length===0?{updated:0,failed:0}:re(P,"approve")},[re]),J=o.useCallback(async(P,Y,oe)=>re(P,Y,oe?{note:oe}:void 0),[re]);return o.useEffect(()=>{i||Ee(Ir)},[i,Ee]),o.useEffect(()=>{if(!t){Z(!1),h(!1),U(null);return}if(r){ee();return}if(ee(),f){Z(!0);return}const P=new URLSearchParams;f&&hs(P,f),v&&P.set("initiative",v);const Y=P.toString()?`/orgx/api/live/stream?${P.toString()}`:"/orgx/api/live/stream",oe=new EventSource(Y),ve=new EventSource("/orgx/api/hooks/runtime/stream");let je=null,te=null,Te=null,pe=null,C=[],O=null,W;const se=()=>{if(W=void 0,je){ce.current=Date.now(),xe.current=!1;const Me=je;je=null,Te=null,pe=null,C=[],O=null,te=null,fe(Me.sessions,Me.activity,Me.handoffs,Me.decisions,Me.sliceRuns,Me.outbox,Me.generatedAt,Me.runtimeInstances,Me.chat,Me.v2);return}!Te&&!pe&&!O&&!te&&C.length===0||(ce.current=Date.now(),xe.current=!1,x(Me=>{var q;let M=Me;if(Te){const ie=nr(Te,l),de=nr(Ea(M.sessions,ie),l);Te=null,Da(M.sessions,de)||(M={...M,sessions:de})}if(pe){const ie=La(pe,u);pe=null,Ra(M.handoffs,ie)||(M={...M,handoffs:ie})}if(O){const ie=Fa(O,g);O=null,$a(M.decisions,ie)||(M={...M,decisions:ie})}if(te){const ie=Oa(te);te=null,Ba(M.runtimeInstances,ie)||(M={...M,runtimeInstances:ie})}if(C.length>0){const ie=bc(M.activity,C,d);C=[],ie!==M.activity&&(M={...M,activity:ie,lastActivity:(q=ie[0])!=null&&q.timestamp?Mt(ie[0].timestamp):M.lastActivity})}return M===Me?Me:M.connection==="connected"?M:{...M,connection:"connected"}}),U(null),h(!1))},De=()=>{W||(W=setTimeout(se,y))};oe.onopen=()=>{ce.current=Date.now(),xe.current=!1,Z(!1),x(Me=>Me.connection==="connected"?Me:{...Me,connection:"connected"}),U(null)},oe.onerror=()=>{if(xe.current){x(M=>M.connection==="disconnected"?M:{...M,connection:"disconnected"}),Z(!1);return}const Me=ce.current>0&&Date.now()-ce.current>Ca;x(M=>M.connection===(Me?"disconnected":"reconnecting")?M:{...M,connection:Me?"disconnected":"reconnecting"}),Z(!0)},oe.addEventListener("snapshot",Me=>{try{const M=JSON.parse(Me.data),q=typeof M.generatedAt=="string"&&M.generatedAt.length>0?M.generatedAt:new Date().toISOString();je={sessions:M.sessions,activity:M.activity??[],handoffs:M.handoffs??[],decisions:M.decisions??null,sliceRuns:Array.isArray(M.sliceRuns)?Wr(M.sliceRuns):Array.isArray(M.projections)?qa(_r(M.projections)):null,outbox:M.outbox??null,generatedAt:q,runtimeInstances:Array.isArray(M.runtimeInstances)?M.runtimeInstances:null,chat:zr(M.chat??null),v2:{workSliceProjections:Array.isArray(M.projections)?_r(M.projections):null,timelineNarrative:Array.isArray(M.timelineNarrative)?bi(M.timelineNarrative):null,nextUpByInitiative:Array.isArray(M.nextUpByInitiative)?wi(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}},De()}catch(M){U(M instanceof Error?M.message:"Invalid snapshot")}}),oe.addEventListener("activity.appended",Me=>{try{const M=JSON.parse(Me.data);if(M.length===0)return;C=C.concat(M),De()}catch{}}),oe.addEventListener("session.updated",Me=>{try{Te=JSON.parse(Me.data),De()}catch{}});const qe=Me=>{try{const M=JSON.parse(Me.data);te=Array.isArray(M)?M:[M],De()}catch{}};return oe.addEventListener("runtime.updated",qe),ve.addEventListener("runtime.updated",qe),oe.addEventListener("handoff.updated",Me=>{try{pe=JSON.parse(Me.data),De()}catch{}}),oe.addEventListener("decision.updated",Me=>{try{O=JSON.parse(Me.data),De()}catch{}}),()=>{W&&clearTimeout(W),oe.close(),ve.close()}},[fe,y,t,i,ee,d,g,u,l,v,f,r]),o.useEffect(()=>{if(!(!t||r||(le.current&&clearInterval(le.current),!H&&!!!f)))return le.current=setInterval(ee,s),()=>{le.current&&clearInterval(le.current)}},[t,ee,f,s,H,r]),{data:k,isLoading:b,error:_,refetch:ee,approveDecision:Le,rejectDecision:ne,approveAllDecisions:R,bulkDecisionAction:J,decisionMutation:j}}const xr=[{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 Qo(e){return xr.find(t=>t.id===e)??xr[0]}function yr(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=xr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Dc(e,t=Date.now()){const s=yr(e,t);return s?new Date(s).toISOString():null}const Rc=new Set(["ungrouped","unscoped","unknown"]),$c="orgx.demo_mode",Fc="orgx.show_synthetic_entities";function Es(e){const t=(e??"").trim().toLowerCase();return!!(!t||Rc.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Pt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem($c)==="1"}catch{return!1}}function Pc(){if(typeof window>"u")return!1;if(Pt())return!0;try{return window.localStorage.getItem(Fc)==="1"}catch{return!1}}function Oc(e){return Pt()?!0:!Es(e)}function Qi(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Jo(e,t){const s=Qi(t.timestamp)-Qi(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function Bc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function qc(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 Yo(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=Bc(e.metadata);return qc(s,["initiative_id","initiativeId"])}function vi(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ji(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(!Ji(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]||!Ji(s[l],r[l]))return!1}return!0}const zc=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function Ws(e,...t){}function Wc(e,t,s,r){const i=new Map,a=t.sinceEpoch,c=t.untilEpoch;let l=0,d=0,u=0;for(const g of e??[]){if(!g||typeof g.id!="string")continue;if(s&&g.runId!==s){l++;continue}if(r&&Yo(g)!==r){d++;continue}const y=Qi(g.timestamp);if(y){if(a!==null&&y<a){u++;continue}if(c!==null&&y>c){u++;continue}i.set(g.id,g)}}return Ws("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(Jo)}function za(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||!Ji(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return Ws("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Jo):e}function Uc(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=Pt()}=e,g=o.useMemo(()=>vi(a),[a]),y=o.useMemo(()=>vi(c),[c]),v=o.useMemo(()=>vi(l),[l]),f=o.useMemo(()=>yr(s),[s]),k=o.useMemo(()=>Dc(s),[s]),x=o.useMemo(()=>{if(s==="custom"){const R=(r==null?void 0:r.trim())??"";return R.length>0?R:null}return k},[r,k,s]),j=o.useMemo(()=>{if(s!=="custom")return null;const R=(i==null?void 0:i.trim())??"";return R.length>0?R:null},[i,s]),w=o.useMemo(()=>{if(x){const R=Date.parse(x);if(Number.isFinite(R))return R}return f},[f,x]),b=o.useMemo(()=>{if(!j)return null;const R=Date.parse(j);return Number.isFinite(R)?R:null},[j]),h=o.useMemo(()=>Wc(t,{sinceEpoch:w,untilEpoch:b},g,y),[t,w,b,g,y]),_=u?null:"",[U,le]=o.useState(h),[V,be]=o.useState(()=>_),[H,Z]=o.useState(!1),[ce,xe]=o.useState(null),[we,K]=o.useState(null),Ie=o.useRef(null),Ee=o.useRef(!1),fe=o.useRef(h);fe.current=h;const ee=o.useMemo(()=>`${g??""}|${y??""}|${s}|${x??""}|${j??""}|${v??""}|${u?"demo":"live"}`,[g,y,s,x,j,v,u]),re=o.useRef(ee);o.useEffect(()=>{re.current!==ee&&(re.current=ee,Ws("RESET",{reason:"filter/run change",runId:g,initiativeId:y,projectId:v,timeFilterId:s,sinceIso:x,untilIso:j,seedCount:fe.current.length}),le(fe.current),be(_),xe(null),K(null),Ee.current=!1)},[ee,_,g,y,v,s,x,j]),o.useEffect(()=>{le(R=>{const J=za(R,h);return J!==R&&Ws("SSE_MERGE",{prevCount:R.length,seedCount:h.length,nextCount:J.length,delta:J.length-R.length}),J})},[h]);const Le=o.useCallback(async()=>{if(u){be(null),xe(null);return}if(V===null)return;if(Ie.current)return Ie.current;Z(!0);const R=(async()=>{try{const J=new URLSearchParams;J.set("limit",String(Math.max(1,Math.min(500,d)))),V.trim().length>0&&J.set("cursor",V),x&&J.set("since",x),j&&J.set("until",j),g&&J.set("run",g),y&&J.set("initiative",y),v&&hs(J,v);const P=await fetch(`/orgx/api/live/activity/page?${J.toString()}`,{headers:_t({workspaceId:v})}),Y=await P.json().catch(()=>null);if(!P.ok||!Y){const je=typeof(Y==null?void 0:Y.error)=="string"&&Y.error.trim()||typeof(Y==null?void 0:Y.message)=="string"&&Y.message.trim()||`Activity paging failed (${P.status})`;throw new Error(je)}const oe=Array.isArray(Y.activities)?Y.activities:[],ve=oe.filter(je=>!y||Yo(je)===y);Ws("PAGE_FETCH",{cursor:V,rawCount:oe.length,afterFilter:ve.length,filteredOut:oe.length-ve.length,initiativeId:y,runId:g,nextCursor:Y.nextCursor??null}),le(je=>{const te=za(je,ve);return Ws("PAGE_MERGE",{prevCount:je.length,pageCount:ve.length,nextCount:te.length,added:te.length-je.length}),te}),be(Y.nextCursor??null),K(Y.storeUpdatedAt??null),xe(null)}catch(J){const P=J instanceof Error?J.message:"";xe(P?In(P):"Activity paging failed"),be(Y=>Y===""?null:Y)}finally{Z(!1),Ie.current=null}})();return Ie.current=R,R},[V,u,y,d,v,g,x,j]);return o.useEffect(()=>{V===""&&(Ee.current||(Ee.current=!0,Le()))},[V,Le]),{items:U,hasMore:V!==null,isLoadingMore:H,error:ce,storeUpdatedAt:we,loadMore:Le,cutoffEpoch:w,sinceIso:x,untilIso:j}}const Hc="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Kc="".trim().toLowerCase()==="true"||"".trim()==="1",Vc="".trim().toLowerCase()==="true"||"".trim()==="1",Gc={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let ki=null,Wa=!1,Ua=!1,ca=!1;function Xc(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function oi(){return ca||!Kc?!1:Vc?!0:!Xc()}function Qc(){return oi()?(ki||(ki=zt(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ca=!0,null))),ki):Promise.resolve(null)}function Jc(e){if(Wa)return!0;try{return e.init(Hc,Gc),Wa=!0,!0}catch{return ca=!0,!1}}async function da(){const e=await Qc();return!e||!Jc(e)?null:e}function Yc(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 Zc(){!oi()||typeof window>"u"||Ua||(Ua=!0,Yc(()=>{da()}))}function ed(e){if(!oi())return;const t=e.trim();t&&da().then(s=>{if(s)try{s.identify(t)}catch{}})}function ls(e,t){oi()&&e.trim()&&da().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const td="https://orgx.mintlify.site/guides/openclaw-plugin-setup",nd=1500,ji="orgx.onboarding.skip",sd=680,rd=`<!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>`,Ur={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:td,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Os(){return{...Ur,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function id(e){if(typeof e=="string")return e;if(e&&typeof e=="object")return JSON.stringify(e)}async function sr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:id(s==null?void 0:s.error)??`Request failed (${t.status})`}}function Cr(e){if(e)try{ed(e)}catch{}}function ad(){const[e,t]=o.useState(()=>Pt()?Os():Ur),[s,r]=o.useState(()=>!Pt()),[i,a]=o.useState(!1),[c,l]=o.useState(!1),d=o.useRef(null),[u,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(ji)==="1"),y=o.useCallback(async()=>{if(Pt()){const h=Os();return t(h),h}const b=await sr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!b.ok||!b.data){const h=b.error??"Failed to load onboarding state",_={...Ur,status:"error",lastError:h,nextAction:"retry"};return t(_),_}return Cr(b.data.installationId??null),t(b.data),b.data},[]);o.useEffect(()=>{if(Pt()){t(Os()),r(!1);return}let b=!1;return(async()=>{r(!0);const h=await y();b||(t(h),r(!1))})(),()=>{b=!0}},[y]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const h=Math.max(900,e.pollIntervalMs??nd),_=window.setInterval(async()=>{const U=await sr(fetch("/orgx/api/onboarding/status",{method:"GET"}));U.ok&&U.data&&(Cr(U.data.installationId??null),t(U.data))},h);return()=>{window.clearInterval(_)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(ji,"1");return}window.localStorage.removeItem(ji)}},[u]);const v=o.useCallback(()=>{if(typeof window>"u")return null;try{const b=window.open("","_blank");return b?(b.opener=null,b.document.title="Connecting to OrgX…",b.document.open(),b.document.write(rd),b.document.close(),b):null}catch{return null}},[]),f=o.useCallback(async()=>{if(Pt()){const h=Os();t(h);return}const b=v();d.current=b,a(!0);try{const h=await sr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),_=h.data;if(!h.ok||!(_!=null&&_.state)){b&&!b.closed&&b.close();const le=h.error??"Could not start pairing";t(V=>({...V,status:"error",lastError:le,nextAction:"enter_manual_key"}));return}t(_.state);const U=_.connectUrl;if(U){const le=d.current;let V=!1;if(le&&!le.closed)try{window.setTimeout(()=>{if(!le.closed)try{le.location.href=U}catch{}},sd),V=!0}catch{V=!1}V||(V=!!window.open(U,"_blank","noopener,noreferrer")),V||t(be=>({...be,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[v]),k=o.useCallback(async b=>{if(Pt()){const h=Os();return t(h),h}l(!0);try{const h=b.trim(),_=h.replace(/^[a-z]+_/i,""),U=Array.from(new Set([h,_?`oxk_${_}`:"",_?`orgx_${_}`:""].map(V=>V.trim()).filter(V=>V.length>0)));let le="Manual key validation failed";for(const V of U){const be={"Content-Type":"application/json","X-OrgX-Api-Key":V,Authorization:`Bearer ${V}`},H=await sr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:be,body:JSON.stringify({apiKey:V})}));if(H.ok&&H.data)return Cr(H.data.installationId??null),t(H.data),H.data;le=H.error??le}throw t(V=>({...V,status:"manual_key",lastError:le,nextAction:"enter_manual_key"})),new Error(le)}finally{l(!1)}},[]),x=o.useCallback(async()=>{if(Pt()){const _=Os();return t(_),_}const b=await sr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(b.ok&&b.data)return Cr(b.data.installationId??null),t(b.data),b.data;const h={...Ur,status:"idle"};return t(h),h},[]),j=o.useCallback(()=>{t(b=>({...b,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),w=o.useMemo(()=>Pt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:w,isLoading:s,isStarting:i,isSubmittingManual:c,refreshStatus:y,startPairing:f,submitManualKey:k,disconnect:x,skipGate:()=>g(!0),resumeGate:()=>g(!1),backToPairing:j,setManualMode:()=>t(b=>({...b,status:"manual_key",nextAction:"enter_manual_key"}))}}const Vn={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 od extends Error{constructor(s,r){super(s);er(this,"code","upgrade_required");er(this,"currentPlan");er(this,"requiredPlan");er(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 ld(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 od(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 hh(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 cd=750;async function rr(e){return await e.json().catch(()=>null)}function dd(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 Mr(e,t,s){if(dd(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 In(r)}function ud(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?In(s):t}function md(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 Hr({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 pd(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 fd(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 ua(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 ma(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 Zo(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=ua(typeof c.id=="string"?c.id:null),d=ma(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 hd(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function gd(e){const t=ua(e.runnerAgentId),s=ma(e.runnerAgentName,t),r=Zo(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=hd(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(g=>typeof g=="string"&&g.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:fd(e),autoRuntimeState:pd(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 Hr(e){const t=e.items.map(u=>gd(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 xd(e){const t=(e.queueState??"").trim().toLowerCase();if(t==="queued"||t==="running"||t==="blocked"||t==="idle"||t==="completed")return t;const s=e.status.trim().toLowerCase();return s==="running"||s==="in_progress"||s==="dispatching"?"running":s==="active"?"queued":e.runnable===!1||s==="blocked"||s==="failed"||s==="error"?"blocked":s==="completed"||s==="done"||s==="resolved"?"completed":"queued"}function yd(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 bd(e){var y,v,f,k,x,j,w,b,h,_,U,le,V,be,H,Z;const t=((v=(y=e.lineage)==null?void 0:y.initiativeIds)==null?void 0:v.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],s=((k=(f=e.lineage)==null?void 0:f.workstreamIds)==null?void 0:k.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],r=((x=e.initiativeId)==null?void 0:x.trim())||t[0]||null,i=((j=e.workstreamId)==null?void 0:j.trim())||((b=(w=e.sourceWorkstreamIds)==null?void 0:w.find(ce=>typeof ce=="string"&&ce.trim().length>0))==null?void 0:b.trim())||s[0]||null;if(!r||!i)return null;const a=((_=(h=e.lineage)==null?void 0:h.taskIds)==null?void 0:_.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,l=ua(e.runnerAgentId??null),d=ma(e.runnerAgentName??null,l),u=Zo(e.runnerAgents??null,l,d),g=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:((le=e.workstreamTitle)==null?void 0:le.trim())||((V=e.title)==null?void 0:V.trim())||((be=e.milestoneTitle)==null?void 0:be.trim())||((H=e.taskTitle)==null?void 0:H.trim())||yd(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((Z=e.taskTitle)==null?void 0:Z.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(g==null?void 0:g.id)??l,runnerAgentName:(g==null?void 0:g.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(g?"inferred":"fallback"),queueState:xd(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 wd(e){const t=new Map;for(const s of e){const r=t.get(s.initiativeId);if(r){r.workstreamCount+=1,r.workstreamIds.push(s.workstreamId),r.items.push(s);for(const a of s.runnerAgents??[])r.runnerAgents.some(c=>c.id===a.id)||r.runnerAgents.push(a);const i=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;i(s.queueState)>i(r.queueState)&&(r.queueState=s.queueState)}else t.set(s.initiativeId,{initiativeId:s.initiativeId,initiativeTitle:s.initiativeTitle??s.initiativeId,initiativeStatus:s.initiativeStatus??"active",initiativePriority:typeof s.initiativePriority=="string"?s.initiativePriority:null,initiativePriorityNum:typeof s.initiativePriorityNum=="number"?s.initiativePriorityNum:null,workstreamCount:1,workstreamIds:[s.workstreamId],runnerAgents:[...s.runnerAgents??[]],queueState:s.queueState,items:[s]})}return Array.from(t.values())}function vd(e){return e.map(t=>({milestoneId:t.sliceMilestoneId??null,milestoneTitle:t.sliceMilestoneId?`Milestone ${t.sliceMilestoneId.slice(0,8)}`:t.workstreamTitle??"Workstream",workstreamId:t.workstreamId,workstreamTitle:t.workstreamTitle??t.workstreamId,initiativeId:t.initiativeId,initiativeTitle:t.initiativeTitle??t.initiativeId,taskCount:t.sliceTaskCount??0,queueState:t.queueState,item:t}))}function el({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=20,authToken:i=null,embedMode:a=!1,enabled:c=!0,snapshotVersion:l=null,zoomLevel:d="workstream"}){var ce,xe,we,K,Ie,Ee,fe,ee,re,Le;const u=oa(),g=Pt(),y=Math.max(0,s),v=Math.max(1,Math.min(300,r)),f=o.useRef(null);o.useEffect(()=>()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]);const k=o.useMemo(()=>Vn.nextUpQueue({initiativeId:e,projectId:t,offset:y,limit:v,authToken:i,embedMode:a}),[e,t,y,v,i,a]),x=o.useRef(l);o.useEffect(()=>{l!==null&&x.current!==null&&l!==x.current&&u.invalidateQueries({queryKey:k}),x.current=l},[l,u,k]);const j=()=>{f.current&&(clearTimeout(f.current),f.current=null),f.current=setTimeout(()=>{f.current=null,u.invalidateQueries({queryKey:Vn.liveData({authToken:i,embedMode:a,projectId:t})})},cd)},w=async()=>{await Promise.all([u.invalidateQueries({queryKey:k}),u.invalidateQueries({queryKey:Vn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})}),u.invalidateQueries({queryKey:Vn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})]),j()},b=async(ne,R)=>{if(g)return md(e);const J=new URLSearchParams;e&&J.set("initiative_id",e),hs(J,t,{allTokenWhenMissing:!0}),J.set("offset",String(ne)),J.set("limit",String(R));let P;try{P=await fetch(`/orgx/api/mission-control/next-up?${J.toString()}`,{headers:_t({authToken:i,embedMode:a})})}catch(Te){throw new Error(ud(Te,"Failed to load next up queue"))}const Y=await rr(P);if(!P.ok){const Te=Mr(P,Y,"Failed to load next up queue");throw new Error(Te)}const oe=Y??null;if(!oe||oe.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:ne,limit:R,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(Pc())return Hr(oe);const ve=oe.items.filter(Te=>!Es(Te.initiativeId));let je=Hr({...oe,items:ve});if(je.items.length>0)return je;const te=new URLSearchParams;e&&te.set("initiative_id",e),hs(te,t,{allTokenWhenMissing:!0}),te.set("level","workstream"),te.set("include_completed","0"),te.set("offset",String(ne)),te.set("limit",String(Math.max(R,24)));try{const Te=await fetch(`/orgx/api/mission-control/slices?${te.toString()}`,{headers:_t({authToken:i,embedMode:a})}),pe=await rr(Te);if(Te.ok&&(pe!=null&&pe.ok)&&Array.isArray(pe.items)){const C=pe.items.map(O=>bd(O)).filter(O=>!!O).filter(O=>!Es(O.initiativeId));C.length>0&&(je=Hr({ok:!0,generatedAt:new Date().toISOString(),total:typeof pe.total=="number"&&Number.isFinite(pe.total)?Math.max(pe.total,C.length):C.length,items:C,pagination:pe.pagination&&typeof pe.pagination=="object"?{offset:typeof pe.pagination.offset=="number"?Math.max(0,Math.floor(pe.pagination.offset)):ne,limit:typeof pe.pagination.limit=="number"?Math.max(1,Math.floor(pe.pagination.limit)):Math.max(R,24),total:typeof pe.pagination.total=="number"?Math.max(0,Math.floor(pe.pagination.total)):C.length,nextCursor:typeof pe.pagination.nextCursor=="string"?pe.pagination.nextCursor:null,hasMore:typeof pe.pagination.hasMore=="boolean"?pe.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...oe.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return je},h=fs({queryKey:k,enabled:c,queryFn:async()=>b(y,v),refetchInterval:ne=>{const R=ne.state.data;return!R||!Array.isArray(R.items)||R.items.length===0?1e4:R.items.some(P=>P.queueState==="running")?2500:8e3}}),_=o.useRef(null);o.useEffect(()=>{var J;const ne=(J=h.data)==null?void 0:J.pagination;if(!c||!(ne!=null&&ne.hasMore)||!ne.nextCursor||_.current===ne.nextCursor)return;const R=Number.parseInt(ne.nextCursor,10);Number.isFinite(R)&&(_.current=ne.nextCursor,u.prefetchQuery({queryKey:Vn.nextUpQueue({initiativeId:e,projectId:t,offset:R,limit:v,authToken:i,embedMode:a}),queryFn:()=>b(R,v),staleTime:15e3}))},[c,(xe=(ce=h.data)==null?void 0:ce.pagination)==null?void 0:xe.hasMore,(K=(we=h.data)==null?void 0:we.pagination)==null?void 0:K.nextCursor,e,t,v,i,a,u]);const U=xn({mutationFn:async ne=>{if(g)return{ok:!0,initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,dispatchMode:"slice",sessionId:null};const R=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,agentId:ne.agentId??void 0,scope:ne.scope??void 0,maxParallelSlices:typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)?Math.max(1,Math.floor(ne.maxParallelSlices)):void 0,parallelMode:ne.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),J=await rr(R);if(!R.ok)throw new Error(Mr(R,J,"Failed to dispatch queued workstream"));return J},onMutate:async ne=>{await u.cancelQueries({queryKey:k});const R=u.getQueryData(k);return R?(u.setQueryData(k,{...R,items:R.items.map(J=>J.initiativeId===ne.initiativeId&&J.workstreamId===ne.workstreamId?{...J,queueState:"running",playbackState:"running"}:J.queueState==="running"?{...J,queueState:"idle",playbackState:"idle"}:J)}),{previous:R}):{previous:R}},onError:(ne,R,J)=>{J!=null&&J.previous&&u.setQueryData(k,J.previous)},onSuccess:()=>{w()}}),le=xn({mutationFn:async ne=>{if(g)return;const R={initiativeId:ne.initiativeId,agentId:ne.agentId??void 0,tokenBudgetTokens:ne.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};ne.scope==="workstream"&&ne.workstreamId&&(R.workstreamIds=[ne.workstreamId]),typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)&&(R.maxParallelSlices=ne.maxParallelSlices),ne.parallelMode==="iwmt"&&(R.parallelMode=ne.parallelMode);const J=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(R)}),P=await rr(J);if(!J.ok){const Y=ld(P);throw Y||new Error(Mr(J,P,"Failed to start auto-continue"))}},onSuccess:()=>{w()}}),V=xn({mutationFn:async ne=>{if(g)return;const R=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId})}),J=await rr(R);if(!R.ok)throw new Error(Mr(R,J,"Failed to stop auto-continue"))},onSuccess:()=>{w()}}),be=((Ie=h.data)==null?void 0:Ie.items)??[],H=o.useMemo(()=>d==="initiative"?wd(be):[],[be,d]),Z=o.useMemo(()=>d==="milestone"?vd(be):[],[be,d]);return{items:be,total:((Ee=h.data)==null?void 0:Ee.total)??0,pagination:((fe=h.data)==null?void 0:fe.pagination)??null,generatedAt:((ee=h.data)==null?void 0:ee.generatedAt)??null,degraded:((re=h.data)==null?void 0:re.degraded)??[],isLoading:h.isLoading,isFetching:h.isFetching,error:((Le=h.error)==null?void 0:Le.message)??null,refetch:h.refetch,playWorkstream:U.mutateAsync,startWorkstreamAutoContinue:le.mutateAsync,stopInitiativeAutoContinue:V.mutateAsync,isPlaying:U.isPending,isStartingAutoContinue:le.isPending,isStoppingAutoContinue:V.isPending,zoomLevel:d,initiativeGroups:H,milestoneGroups:Z}}const kd=750;async function an(e){return await e.json().catch(()=>null)}function zs(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 on(e,t,s){if(zs(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 In(r)}function jd(e){const t=e.authToken??null,s=e.embedMode??!1,r=Pt(),i=oa(),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"]})},kd)},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 b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId,placement:b.placement??"top"};const h=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(h.ok)return _;if(!zs(h,_))throw new Error(on(h,_,"Failed to move Next Up item"));const U=await fetch("/orgx/api/mission-control/next-up",{headers:_t({authToken:t,embedMode:s})}),le=await an(U);if(!U.ok)throw new Error(on(U,le,"Failed to read queue for move fallback"));const be=(Array.isArray(le==null?void 0:le.items)?le.items:[]).map(we=>{const K=typeof(we==null?void 0:we.initiativeId)=="string"?we.initiativeId:null,Ie=typeof(we==null?void 0:we.workstreamId)=="string"?we.workstreamId:null;return!K||!Ie?null:{initiativeId:K,workstreamId:Ie}}).filter(we=>!!we);if(be.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const H=be.findIndex(we=>we.initiativeId===b.initiativeId&&we.workstreamId===b.workstreamId);if(H===-1)return{ok:!0,fallback:"reorder-move-skip"};const[Z]=be.splice(H,1);(b.placement??"top")==="bottom"?be.push(Z):be.unshift(Z);const ce=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:be})}),xe=await an(ce);if(!ce.ok)throw new Error(on(ce,xe,"Failed to move Next Up item with reorder fallback"));return xe??{ok:!0,fallback:"reorder-move"}},u=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(h.ok)return _;if(zs(h,_)){const U=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),le=await an(U);if(!U.ok)throw new Error(on(U,le,"Failed to remove item from queue with legacy fallback"));return le??{ok:!0,fallback:"next-up-unpin"}}throw new Error(on(h,_,"Failed to remove item from queue"))},g=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok)throw new Error(on(h,_,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),y=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok)throw new Error(on(h,_,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),v=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.order.length};const h=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok)throw new Error(on(h,_,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),f=xn({mutationFn:d,onSuccess:()=>{l()}}),k=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok){if(zs(h,_)){const U=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),le=await an(U);if(!U.ok)throw new Error(on(U,le,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(on(h,_,"Failed to stop triage"))}return _},onSuccess:()=>{l()}}),x=xn({mutationFn:u,onSuccess:()=>{l()}}),j=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,cleared:!0};const h=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok){if(zs(h,_)&&b.initiativeId){const U=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),le=await an(U);if(!U.ok)throw new Error(on(U,le,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(on(h,_,"Failed to clear Next Up lifecycle state"))}return _},onSuccess:()=>{l()}}),w=xn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.items.length,failed:0,errors:[],fallback:"demo"};const h=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await an(h);if(!h.ok){if(!zs(h,_))throw new Error(on(h,_,"Failed to apply bulk queue action"));const U=await Promise.all(b.items.map(async H=>{try{return b.action==="remove"?await u(H):await d({initiativeId:H.initiativeId,workstreamId:H.workstreamId,placement:b.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(Z){return{ok:!1,error:Z instanceof Error?Z.message:"Queue action failed"}}})),le=U.filter(H=>H.ok).length,V=U.length-le,be=U.filter(H=>!H.ok&&H.error).map(H=>H.error);return{ok:V===0,updated:le,failed:V,errors:be,fallback:"sequential"}}return _},onSuccess:()=>{l()}});return{pin:g.mutateAsync,unpin:y.mutateAsync,reorder:v.mutateAsync,move:f.mutateAsync,remove:x.mutateAsync,stopTriage:k.mutateAsync,clear:j.mutateAsync,bulk:w.mutateAsync,isPinning:g.isPending,isUnpinning:y.isPending,isReordering:v.isPending,isMoving:f.isPending,isRemoving:x.isPending,isStoppingTriage:k.isPending,isClearing:j.isPending,isBulking:w.isPending}}function tl(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Nd(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:tl(s,r)});if(!c.ok)throw new Error(`Triage fetch failed: ${c.status}`);return c.json()}async function Id(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:tl(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 Ad(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,c=oa(),l=Vn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=fs({queryKey:l,queryFn:()=>Nd(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=xn({mutationFn:async({itemId:f,payload:k})=>Id(f,k,i,a),onSuccess:()=>{c.invalidateQueries({queryKey:l})}}),g=o.useCallback(async(f,k,x)=>u.mutateAsync({itemId:f,payload:{action:k,note:x==null?void 0:x.note,optionId:x==null?void 0:x.optionId,snoozeDurationMinutes:x==null?void 0:x.snoozeDurationMinutes}}),[u]),y=o.useMemo(()=>{var f,k,x;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:((x=d.data)==null?void 0:x.degraded)??[],refetch:d.refetch}},[d]),v=o.useMemo(()=>({performAction:g,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[g,u.isPending,u.error]);return{model:y,actions:v}}function me(...e){return e.filter(Boolean).join(" ")}const E={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"},gh={active:{text:"rgba(223, 255, 156, 0.9)"},done:{text:"rgba(135, 255, 233, 0.9)"},blocked:{text:"rgba(255, 195, 208, 0.9)"},planned:{text:"rgba(236, 241, 255, 0.74)"}},Sd={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},_d={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function Cd(e){return Sd[e]??"rgba(255, 255, 255, 0.4)"}function nl(e){return _d[e]??null}function Md(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function qt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const sn={durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},xh={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},li="/orgx/live/assets/Fm0FhtnV.png";function sl({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 yn({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??E.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??E.lime;return n.jsx(sl,{size:s,className:t,stroke:c,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${c}1A`})}if(e==="milestone"){const c=r??E.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??E.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??E.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??E.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??E.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??E.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??E.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??E.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??E.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 Td=[{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"}],Kr=[{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."}],Ed=[{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."}],Ha="openclaw plugins install @useorgx/openclaw-plugin",Ka="orgx.demo_mode",Ld=6500;function Dd(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 Rd={hidden:{},visible:{transition:{staggerChildren:.07}}},cs={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},$d={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 Ni(e){const t=Kr.length;return(e+t)%t}function Fd({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,[c,l]=o.useState("idle"),[d,u]=o.useState("idle"),[g,y]=o.useState(0),[v,f]=o.useState(!1),k=e.hasApiKey&&e.keySource&&e.keySource!=="none",x=Kr[g];o.useEffect(()=>{if(c==="idle")return;const b=window.setTimeout(()=>l("idle"),2e3);return()=>window.clearTimeout(b)},[c]),o.useEffect(()=>{if(d==="idle")return;const b=window.setTimeout(()=>u("idle"),2e3);return()=>window.clearTimeout(b)},[d]),o.useEffect(()=>{if(v)return;const b=window.setInterval(()=>{y(h=>Ni(h+1))},Ld);return()=>window.clearInterval(b)},[v]);const j=async()=>{try{await navigator.clipboard.writeText(Ha),l("ok")}catch{l("error")}},w=async()=>{try{const b={at:new Date().toISOString(),onboarding:{status:e.status,nextAction:e.nextAction,hasApiKey:e.hasApiKey,keySource:e.keySource,installationId:e.installationId,lastError:e.lastError},page:typeof window<"u"?window.location.href:null,userAgent:typeof navigator<"u"?navigator.userAgent:null};await navigator.clipboard.writeText(JSON.stringify(b,null,2)),u("ok")}catch{u("error")}};return n.jsxs(ye.section,{variants:Rd,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:cs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:li,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:cs,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(yn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ye.p,{variants:cs,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:cs,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(yn,{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:[g+1,"/",Kr.length]})]}),n.jsx(bt,{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:x.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:x.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:x.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:x.highlights.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:b.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},`${x.id}-${b.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:x.footnote})]},x.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:Kr.map((b,h)=>{const _=h===g;return n.jsx("button",{type:"button",onClick:()=>y(h),"aria-label":`View slide ${h+1}`,className:`h-1.5 rounded-full transition-all ${_?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},b.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(b=>Ni(b-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>y(b=>Ni(b+1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Next"})]})]})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:Td.map(b=>n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.025] px-3 py-2.5",children:[n.jsx("div",{className:`mb-1.5 ${$d[b.iconType]}`,children:n.jsx(yn,{type:b.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:b.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:b.desc})]},b.label))}),n.jsxs(ye.div,{variants:cs,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:cs,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(yn,{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(yn,{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:Ha}),n.jsx("button",{type:"button",onClick:()=>{j()},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: ",Dd(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:Ed.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:b.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},b.label))})]})]})]}),n.jsx(ye.div,{variants:cs,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 w(),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:cs,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(Ka,"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(Ka)}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 Pd={hidden:{},visible:{transition:{staggerChildren:.06}}},Ns={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Od({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 g=r.trim();if(!g){c("API key is required.");return}const y=/^[a-z]+_/i.test(g)?g:`oxk_${g}`;try{await t(y),i("")}catch(v){c(v instanceof Error?v.message:"Failed to validate API key.")}},u=a!==null;return n.jsxs(ye.section,{variants:Pd,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:Ns,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:li,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:Ns,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ye.p,{variants:Ns,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:Ns,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:Ns,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:Ns,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:g=>{i(g.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:Ns,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 Va="orgx.user.display-name",Ga="orgx.user.avatar-seed-suffix";function Xa(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Qa(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function Bd(){const[e,t]=o.useState(()=>Xa(Va)),[s,r]=o.useState(()=>Xa(Ga)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();Qa(Va,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());Qa(Ga,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function qd(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function zd(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 Ja=[E.lime,E.teal,E.iris,E.cyan];function Wd(e,t,s,r,i,a){const c=_=>_*Math.PI/180,l=Math.cos,d=Math.sin,u=c(i),g=c(a),y=a-i>180?1:0,v=e+r*l(u),f=t+r*d(u),k=e+r*l(g),x=t+r*d(g),j=e+s*l(g),w=t+s*d(g),b=e+s*l(u),h=t+s*d(u);return[`M ${v} ${f}`,`A ${r} ${r} 0 ${y} 1 ${k} ${x}`,`L ${j} ${w}`,`A ${s} ${s} 0 ${y} 0 ${b} ${h}`,"Z"].join(" ")}function Ud(e){const t=zd(qd(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),g=360/u,y=1.5+t()*2;for(let v=0;v<u;v++){if(t()<.15)continue;const f=v*g+y/2,k=(v+1)*g-y/2,x=Ja[Math.floor(t()*Ja.length)],j=.25+t()*.55;r.push({d:Wd(i,a,l,d,f,k),fill:x,opacity:j})}}return r}function Hd({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>Ud(e),[e]);return n.jsxs(ye.svg,{viewBox:"0 0 100 100",width:t,height:t,className:me("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:sn.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:E.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:E.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:E.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:sn.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 Kd({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:sn.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(Hd,{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 Vd=[{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 Gd({className:e,compact:t=!1}){return n.jsxs("div",{className:me("flex flex-wrap items-center gap-x-3 gap-y-1 text-muted",t?"text-micro":"text-caption",e),children:[n.jsxs("span",{className:"text-faint",children:["© ",new Date().getFullYear()," OrgX"]}),Vd.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 Ya="orgx.user.name-asked";function Xd(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 Qd(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 Jd(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Za={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Ii="orgx.onboarding.mc_hint.dismissed",Ai={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 Yd({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:c,onBackToPairing:l,onUseManualKey:d,onSkip:u}){const[g,y]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ii)==="1"),[v,f]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ya)!=="1"),k=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Ya,"1"),f(!1)},[]);o.useEffect(()=>{typeof window>"u"||(g?window.localStorage.setItem(Ii,"1"):window.localStorage.removeItem(Ii))},[g]);const x=e.status==="manual_key",j=e.status==="awaiting_browser_auth"||e.status==="pairing",w=Jd(e.status),b=w==="active"&&e.status!=="connected",h=e.status==="connected"&&!g;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 ${x?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(bt,{mode:"wait",children:e.status==="connected"&&v?n.jsx(ye.div,{...Ai,children:n.jsx(Kd,{onComplete:k})},"welcome-name"):x?n.jsx(ye.div,{...Ai,children:n.jsx(Od,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(ye.div,{...Ai,children:n.jsx(Fd,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(j||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:[b&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Za[w]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Za[w]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:Xd(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Qd(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&&j&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-[#BFFF00]/25 bg-[#BFFF00]/[0.05] px-3 py-1 text-caption font-medium text-[#D8FFA1] transition hover:bg-[#BFFF00]/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full border border-white/[0.08] px-2.5 py-1 text-caption text-muted transition hover:bg-white/[0.04] hover:text-secondary",children:"Refresh"})]})]}),h&&n.jsxs(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(Gd,{compact:!0})})]})})}function Zd({children:e,color:t,pulse:s,title:r}){const i=t??E.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 ci({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 x=k.querySelector('[data-modal-autofocus="true"]');if(x){x.focus();return}const j=k.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');j.length>0?j[0].focus():k.focus()})();const v=k=>{if(k.key==="Escape"){if(!c)return;if(!l){const _=k.target;if(_&&(_.tagName==="INPUT"||_.tagName==="TEXTAREA"||_.tagName==="SELECT"||_.isContentEditable))return}k.preventDefault(),t();return}if(k.key!=="Tab")return;const x=d.current;if(!x)return;const j=x.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(j.length===0){k.preventDefault(),x.focus();return}const w=j[0],b=j[j.length-1],h=document.activeElement;!k.shiftKey&&h===b?(k.preventDefault(),w.focus()):k.shiftKey&&h===w&&(k.preventDefault(),b.focus())},f=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",v),()=>{var k;document.body.style.overflow=f,document.removeEventListener("keydown",v),(k=u.current)==null||k.focus()}},[e,t,c,l]);const g=n.jsx(bt,{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:E.cardBgElevated,borderColor:E.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"?g:Pl.createPortal(g,document.body)}const eu=[{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 tu({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:eu.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:me("relative flex min-w-[76px] flex-1 flex-col items-center gap-1 overflow-hidden rounded-[18px] px-2 pb-1.5 pt-2.5 transition-colors",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:E.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:me("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",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:E.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:me("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function Hs({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:me("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const nu={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"},su="/orgx/live/",ln=e=>`${su.replace(/\/+$/,"/")}${e}`,ru={pace:ln("brand/product-orchestrator.png"),eli:ln("brand/engineering-autopilot.png"),mark:ln("brand/launch-captain.png"),sage:ln("brand/pipeline-intelligence.png"),orion:ln("brand/control-tower.png"),dana:ln("brand/design-codex.png"),xandy:ln("brand/xandy-orchestrator.png"),nova:ln("brand/xandy-orchestrator.png"),openclaw:ln("brand/openclaw-mark.svg"),codex:ln("brand/openai-mark.svg"),openai:ln("brand/openai-mark.svg"),anthropic:ln("brand/anthropic-mark.svg"),orgx:ln("brand/orgx-logo.png")},iu=[{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 au(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of iu)if(s.test.test(t))return ru[s.key];return null}function $t({name:e,size:t="xs",hint:s,src:r}){const i=Cd(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:au(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${nu[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"}):Md(e)})}$t.displayName="AgentAvatar";const ou={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 kn({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:me("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",ou[t],s),...r,children:e})}function lu(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=rl(e.status),c={id:e.workstreamId,label:e.workstreamTitle||Cs(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||Cs(l.id,"Milestone"),type:"milestone",status:d,progress:{done:l.done,total:l.total}};l.total>0&&(u.children=Array.from({length:l.total},(g,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:Cs(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function yh(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Cs(e.workstreamId,"Workstream"),type:"workstream",status:rl(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||Cs(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 Cs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function rl(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 il(e){switch(e){case"done":return E.lime;case"active":return E.teal;case"blocked":return E.amber;case"failed":return E.red;default:return"rgba(255,255,255,0.15)"}}function cu(e){const t=il(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const du=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]}})})}),uu=16,mu=14,eo=8,pu=8,fu=28,hu=24,gu=24,xu=20,Si="rgba(255,255,255,0.07)";function yu(e){const t=e?mu:uu,s=t+pu+4;return{iconSz:t,colW:s,rowH:e?gu:fu,rowHTask:e?xu:hu}}function al({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,g=e.progress&&e.progress.total>0,y=e.type==="task",{iconSz:v,colW:f,rowH:k,rowHTask:x}=yu(i),j=y?x:k,w=e.children??[],b=w.filter(H=>H.type==="task"),h=w.filter(H=>H.type!=="task"),_=b.length>c&&!l,U=_?b.slice(0,c):b,le=b.length-U.length,V=[...h,...U],be=V.length>0||_;return n.jsxs("div",{className:"relative",style:{minHeight:j},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Si,left:(t-1)*f+f/2,top:0,bottom:s?void 0:0,height:s?j/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:Si,left:(t-1)*f+f/2,top:j/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:j,paddingLeft:t*f},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:f,height:j},children:y?n.jsx("span",{className:"inline-block rounded-full",style:{...cu(e.status),width:eo,height:eo}}):n.jsx(yn,{type:e.type,size:v,accent:u?E.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}),g&&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})]}),g&&!y&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(du,{done:e.progress.done,total:e.progress.total,color:il(e.status)})})]})]}),be&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Si,left:t*f+f/2,top:j/2,height:j/2}}),be&&n.jsxs("div",{children:[V.map((H,Z)=>n.jsx(al,{node:H,depth:t+1,isLast:Z===V.length-1&&!_,activeId:r,compact:i,index:a+Z+1,taskLimit:c,expanded:l,onToggleExpand:d},H.id)),_&&n.jsxs(ye.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+V.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:x,paddingLeft:(t+1)*f+f},children:["+",le," more · see all"]}),n.jsx(bt,{children:l&&b.length>c&&n.jsx(ye.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:x},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 bu=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(al,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:c,onToggleExpand:()=>l(g=>!g)},d.id))})}),Yi={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"}},wu=Object.keys(Yi);function to(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of wu)if(t.includes(s))return s;return"engineering"}function no(e){return Yi[e]??Yi.engineering}const Bs={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},ir={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},so={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},ro={eli:"Eli",pace:"Pace",dana:"Dana",mark:"Mark",sage:"Sage",orion:"Orion",xandy:"Xandy",nova:"Nova","engineering-agent":"Eli","product-agent":"Pace","design-agent":"Dana","marketing-agent":"Mark","strategy-agent":"Sage","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","dev-delivery":"Eli","launch-captain":"Mark","pipeline-intelligence":"Sage","control-tower":"Orion","design-codex":"Dana","router-all-agents":"Xandy","ops-orbit":"Orion","sales-sage":"Sage"};function ol(e,t){const s={name:(t==null?void 0:t.trim())||"OrgX",domain:"",color:"rgba(255,255,255,0.4)",displayLabel:(t==null?void 0:t.trim())||"OrgX"};if(e){const r=e.trim().toLowerCase(),i=ro[r];if(i){const a=ir[i]??"";return{name:i,domain:a,color:Bs[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,c]of Object.entries(so))if(r.includes(a)){const l=ir[c]??"";return{name:c,domain:l,color:Bs[c]??s.color,displayLabel:l?`${c} (${l})`:c}}}if(t){const r=t.trim();if(Bs[r]){const c=ir[r]??"";return{name:r,domain:c,color:Bs[r],displayLabel:c?`${r} (${c})`:r}}const i=r.toLowerCase(),a=ro[i];if(a){const c=ir[a]??"";return{name:a,domain:c,color:Bs[a]??s.color,displayLabel:c?`${a} (${c})`:a}}for(const[c,l]of Object.entries(so))if(i.includes(c)){const d=ir[l]??"";return{name:l,domain:d,color:Bs[l]??s.color,displayLabel:d?`${l} (${d})`:l}}}return s}function bh({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($t,{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 vu=new Set(["running","active","in_progress","working","planning","dispatching"]),ku=new Set(["running","dispatching"]),ju=3*6e4;function Nu(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=ju:!1}function Iu(e){const t=qt(e.status??""),s=qt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:vu.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Nu(e.lastHeartbeatAt):!1}function ll(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function Au(e){const t=qt(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 Su(e){const t=qt(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 cl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Tr(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Is(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 Yr(e,t){if(!e)return t;const s=e.trim();return s?Gn(s)?`${t} ${ds(s)}`:s:t}const _u=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),Cu=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function Mu(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?_u.has(t)||t.startsWith("telegram:"):!1}function Tu(e){if(!e)return!1;const t=e.trim();return t?Cu.some(s=>s.test(t)):!1}function dl({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var y,v,f,k,x,j;const r=new Map;for(const w of s)w.id&&r.set(w.id,w.name??w.id);const i=new Map;for(const w of e){const b=(y=w.runId)==null?void 0:y.trim();!b||i.has(b)||i.set(b,w)}const a=new Map;for(const w of e){const b=((v=w.initiativeId)==null?void 0:v.trim())??"",h=((f=w.workstreamId)==null?void 0:f.trim())??"";if(!b||!h)continue;const _=`${b}:${h}`;a.has(_)||a.set(_,w)}const c=new Set;for(const w of e){const b=(k=w.runId)==null?void 0:k.trim();b&&c.add(b)}const l=[];for(const w of t){if(!ku.has(w.status))continue;const b=(w.runId??w.sliceRunId??"").trim();if(!b)continue;const h=Is(w.initiativeIds,w.initiativeId),_=Is(w.workstreamIds,w.workstreamId),U=h[0]??null,le=_[0]??null,V=[];for(const xe of h)for(const we of _)!xe||!we||V.push(`${xe}:${we}`);if(!(c.has(b)||V.some(xe=>a.has(xe))))continue;const H=i.get(b)??(V.length>0?V.map(xe=>a.get(xe)??null).find(xe=>!!xe)??null:null),Z=U?r.get(U)??U:null,ce=w.scopeProgress&&typeof w.scopeProgress.totalTasks=="number"&&w.scopeProgress.totalTasks>0?Math.round(w.scopeProgress.completedTasks/w.scopeProgress.totalTasks*100):null;l.push({key:`slice:${w.sliceRunId}`,source:"slice",session:H??null,runId:b,status:qt(w.status),title:w.workstreamTitle??(H==null?void 0:H.title)??`Work slice ${w.sliceRunId.slice(0,8)}`,subtitle:w.statusExplainer??w.lastEventSummary??(H==null?void 0:H.lastEventSummary)??null,progress:ce??(H==null?void 0:H.progress)??null,initiativeId:U,initiativeIds:h,initiativeTitle:Z,workstreamId:le,workstreamIds:_,iwmtId:w.iwmtId??null,iwmtIds:Is(w.iwmtIds,w.iwmtId),workstreamTitle:w.workstreamTitle??(H==null?void 0:H.title)??null,taskIds:Array.isArray(w.taskIds)?w.taskIds:[],milestoneIds:Array.isArray(w.milestoneIds)?w.milestoneIds:[],artifactCount:w.artifactCount??0,decisionCount:w.blockingDecisionCount??w.decisionCount??0,updatedAt:w.updatedAt??w.lastEventAt??(H==null?void 0:H.updatedAt)??null,scope:w.scope,milestoneProgress:(x=w.scopeProgress)==null?void 0:x.milestones})}if(l.sort((w,b)=>Tr(b.updatedAt)-Tr(w.updatedAt)),l.length>0){const w=[],b=new Set;for(const h of l){const _=h.initiativeId??((j=h.initiativeIds)==null?void 0:j[0])??"none",le=(h.workstreamId?`scope:${_}:${h.workstreamId}`:null)??(h.runId?`run:${h.runId}`:h.key);b.has(le)||(b.add(le),w.push(h))}return w}const d=e.filter(Iu);d.sort((w,b)=>{const h=Tr(w.updatedAt??w.lastEventAt??w.startedAt);return Tr(b.updatedAt??b.lastEventAt??b.startedAt)-h});const u=[],g=new Set;for(const w of d){const b=w.workstreamId&&w.workstreamId.trim().length>0?`${w.initiativeId??"none"}:${w.workstreamId}`:w.runId;g.has(b)||(g.add(b),u.push(w))}return u.map(w=>{var b;return{key:`session:${w.id}`,source:"session",session:w,runId:w.runId,status:qt(w.status??""),title:w.title,subtitle:(b=w.lastEventSummary)!=null&&b.trim()?w.lastEventSummary.trim():null,progress:w.progress,initiativeId:w.initiativeId,initiativeIds:Is(void 0,w.initiativeId),initiativeTitle:w.initiativeId?r.get(w.initiativeId)??w.groupLabel??null:w.groupLabel??null,workstreamId:w.workstreamId,workstreamIds:Is(void 0,w.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:w.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:w.updatedAt??w.lastEventAt??w.startedAt??null}})}const Eu=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:g,onFocusRunId:y,onPlayWorkstream:v,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onIntervene:j,onOpenSliceDetail:w}){const[b,h]=o.useState(null),[_,U]=o.useState(null),[le,V]=o.useState(null),[be,H]=o.useState(null),Z=o.useMemo(()=>{const ee=new Map;if(!Array.isArray(s))return ee;for(const re of s){const Le=Is(re.initiativeIds,re.initiativeId),ne=Is(re.workstreamIds,re.workstreamId);for(const J of Le)for(const P of ne){if(!J||!P)continue;const Y=`${J}:${P}`;ee.has(Y)||ee.set(Y,re)}const R=(re.runId??re.sliceRunId??"").trim();R&&!ee.has(`run:${R}`)&&ee.set(`run:${R}`,re)}return ee},[s]),ce=o.useMemo(()=>dl({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),xe=o.useMemo(()=>{const ee=new Map;for(const re of ce){const Le=qt(re.status);ee.set(Le,(ee.get(Le)??0)+1)}return Array.from(ee.entries()).sort((re,Le)=>Le[1]-re[1]).map(([re,Le])=>({status:re,count:Le}))},[ce]),we=o.useMemo(()=>b?ce.filter(ee=>qt(ee.status)===b):ce,[b,ce]),K=o.useMemo(()=>{var ne,R;const ee=new Map,re=[];for(const J of we){const P=(((ne=J.initiativeIds)==null?void 0:ne[0])??J.initiativeId??"").trim(),Y=(((R=J.workstreamIds)==null?void 0:R[0])??J.workstreamId??"").trim();if(!P){re.push(J);continue}let oe=ee.get(P);oe||(oe={title:J.initiativeTitle??P,wsMap:new Map},ee.set(P,oe));const ve=Y||"__none__";let je=oe.wsMap.get(ve);je||(je={title:J.workstreamTitle??(Y||"Unassigned"),rows:[],completedCount:0,lastActivity:null},oe.wsMap.set(ve,je));const te=qt(J.status);if(te==="completed"||te==="done"?je.completedCount+=1:je.rows.push(J),J.updatedAt){const Te=Date.parse(J.updatedAt),pe=je.lastActivity?Date.parse(je.lastActivity):0;Number.isFinite(Te)&&Te>pe&&(je.lastActivity=J.updatedAt)}}const Le=[];for(const[J,P]of ee){const Y=[];for(const[oe,ve]of P.wsMap)Y.push({workstreamId:oe,workstreamTitle:ve.title,rows:ve.rows,completedCount:ve.completedCount,lastActivityAt:ve.lastActivity});Y.sort((oe,ve)=>{const je=oe.lastActivityAt?Date.parse(oe.lastActivityAt):0;return(ve.lastActivityAt?Date.parse(ve.lastActivityAt):0)-je}),Le.push({initiativeId:J,initiativeTitle:P.title,workstreams:Y})}return Le.sort((J,P)=>{const Y=Math.max(0,...J.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0));return Math.max(0,...P.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0))-Y}),{groups:Le,ungrouped:re}},[we]),[Ie,Ee]=o.useState(new Set),fe=async(ee,re,Le)=>{if(ee.session){H(null),U(ee.session.id);try{await re(ee.session),H(Le)}catch(ne){const R=ne instanceof Error?ne.message:"";H(R?In(R):"Workstream action failed")}finally{U(null)}}};return n.jsxs(Hs,{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:ce.length})]})}):null,xe.length>1&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-subtle px-3 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>h(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${b===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:ce.length})]}),xe.map(({status:ee,count:re})=>n.jsxs("button",{type:"button",onClick:()=>h(Le=>Le===ee?null:ee),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${b===ee?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[ll(ee),n.jsx("span",{className:"tabular-nums opacity-70",children:re})]},ee))]}),be&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:be}),we.length===0?ce.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:ce.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:[K.groups.map(ee=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Bt(ee.initiativeTitle&&!Gn(ee.initiativeTitle)?ee.initiativeTitle:Yr(ee.initiativeId,"Initiative"))}),ee.workstreams.map(re=>{var te,Te;const Le=`${ee.initiativeId}:${re.workstreamId}`,ne=Ie.has(Le),R=re.rows[0]??null,J=R?ol((te=R.session)==null?void 0:te.agentId,(Te=R.session)==null?void 0:Te.agentName):null,P=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((pe,C)=>pe+C.total,0):null,Y=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((pe,C)=>pe+C.done,0):null,oe=P&&P>0?`Task ${(Y??0)+1} of ${P}`:null,ve=P&&P>0?Math.round((Y??0)/P*100):(R==null?void 0:R.progress)!=null?cl(R.progress):null,je=Bt(R!=null&&R.workstreamTitle&&!Gn(R.workstreamTitle)?R.workstreamTitle:Yr(re.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:[J&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${J.color}20`,color:J.color},children:J.name.charAt(0).toUpperCase()}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-[13px] font-semibold text-white/88",title:je,children:je}),J?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:J.color},title:J.displayLabel,children:J.displayLabel}):null]})]}),oe&&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:oe}),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,ve??0)}%`,backgroundColor:(J==null?void 0:J.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:re.rows.map((pe,C)=>n.jsx(io,{row:pe,index:C,sliceRunByScope:Z,busySessionId:_,expandedRowKey:le,setExpandedRowKey:V,onOpenSession:g,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onPlayWorkstream:v,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:fe,showInitiativeLabel:!1},pe.key))}),re.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>Ee(pe=>{const C=new Set(pe);return C.has(Le)?C.delete(Le):C.add(Le),C}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:ne?`Hide ${re.completedCount} completed`:`${re.completedCount} completed`})})]},re.workstreamId)})]},ee.initiativeId)),K.ungrouped.length>0&&n.jsxs("div",{children:[K.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:K.ungrouped.map((ee,re)=>n.jsx(io,{row:ee,index:re,sliceRunByScope:Z,busySessionId:_,expandedRowKey:le,setExpandedRowKey:V,onOpenSession:g,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onPlayWorkstream:v,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:fe,showInitiativeLabel:!0},ee.key))})]})]})})]})});function io({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:c,onFocusRunId:l,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:g,onPlayWorkstream:y,onIntervene:v,onOpenSliceDetail:f,runWorkstreamAction:k,showInitiativeLabel:x=!0}){var re,Le,ne,R,J,P,Y,oe,ve,je;const j=qt(e.status??""),w=e.updatedAt,b=e.subtitle?e.subtitle:w?`Updated ${Mt(w)}`:null,h=x&&(e.initiativeTitle||e.initiativeId)?Bt(e.initiativeTitle&&!Gn(e.initiativeTitle)?e.initiativeTitle:Yr(e.initiativeId,"Initiative")):null,_=(re=e.title)!=null&&re.trim()?e.title:"",U=Mu(_)&&((Le=e.workstreamTitle)!=null&&Le.trim())?e.workstreamTitle:_||e.workstreamTitle||"",le=Yr(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),V=Bt(U&&!Gn(U)?U:le),be=b&&!Tu(b)?Bt(b):null,H=cl(e.progress),Z=["running","active","in_progress","working","planning","dispatching"].includes(j),ce=["paused","blocked","queued","pending"].includes(j),xe=g??y,we=H===null&&["running","active","in_progress","working","planning","dispatching"].includes(j),K=e.session?r===e.session.id:!1,Ie=i===e.key,Ee=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),fe=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),ee=ol((ne=e.session)==null?void 0:ne.agentId,(R=e.session)==null?void 0:R.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,fe),role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),f==null||f(e,fe))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Su(j)}`,"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":ee.color}:void 0,children:n.jsx($t,{name:((J=e.session)==null?void 0:J.agentName)??"OrgX",hint:((P=e.session)==null?void 0:P.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[h?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:h}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(yn,{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:V,children:V})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(kn,{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] ${Au(j)}`,children:ll(j)}),w&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:Wl(new Date(w),{addSuffix:!0})})]}),be?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:be,children:be}):null,null,(H!==null||we)&&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:H===null?"Live":`${H}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${H===100?" shimmer-on-complete":""}`,children:H===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,H)}%`,background:`linear-gradient(90deg, ${no(to((Y=e.session)==null?void 0:Y.agentId)).gradient[0]}, ${no(to((oe=e.session)==null?void 0:oe.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(bu,{nodes:lu({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((te,Te)=>te+Te.total,0),completedTasks:e.milestoneProgress.reduce((te,Te)=>te+Te.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ve=e.session)==null?void 0:ve.agentName)??null,agentId:((je=e.session)==null?void 0:je.agentId)??null}),activeId:e.workstreamId,compact:!0})}),Ee?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:te=>{te.stopPropagation(),a(Te=>Te===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:Ie?"Hide details":"Slice details"}),Ie?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:te=>te.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&&Z&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:K,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&&ce&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:K,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&&xe&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:K,onClick:()=>void k(e,xe,`Restarted ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Restart this workstream",children:"Restart"}),e.session&&v&&n.jsx("button",{type:"button",disabled:K,onClick:()=>void k(e,v,`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 Lu=new Set(["awaiting_input","needs_review","failed"]);function ao(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Du(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 ul(e){const t=e.filter(r=>Lu.has(r.status)).sort((r,i)=>ao(i.updatedAt??i.lastEventAt??"")-ao(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=Du(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function Ru(e){return e==="failed"?"border-red-400/30 bg-red-500/[0.10] text-red-100":e==="needs_review"?"border-amber-300/30 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]"}function $u(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function Fu(e){return e==="failed"?"from-red-300/0 via-red-300/65 to-red-300/0":e==="needs_review"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Pu(e){return e.primaryAction==="resolve_decision"?"Review choices":e.primaryAction==="open_artifact"?"Open result":e.primaryAction==="retry_slice"?"Review and retry":e.primaryAction==="review_output"?"Review activity":"Open details"}function Ou(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready to review.`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} need${t===1?"s":""} your input.`}return e.status==="failed"?"Execution stopped before finishing.":e.status==="needs_review"?"Output is available and needs a quick review.":"This work needs your attention to continue."}function Zi(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Gn(s)?`${t} ${ds(s)}`:s}function Bu(e){if(!e)return null;const t=Bt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function qu(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!Gn(r)){const a=Bt(r);if(a!=="Untitled session")return a}const i=Bu(e.statusExplainer);return i||(s?Zi(s,"Workstream"):Zi(e.sliceRunId,"Slice"))}const zu=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:g}){const y=o.useMemo(()=>ul(t),[t]),v=o.useMemo(()=>{const x=new Map;for(const j of s)j.id&&x.set(j.id,j.name??j.id);return x},[s]),f=o.useMemo(()=>{const x=new Map;for(const j of s)for(const w of j.workstreams??[])w.id&&(x.has(w.id)||x.set(w.id,w.name??w.id));return x},[s]),k=x=>{var j;if(x.primaryAction==="resolve_decision"){l==null||l();return}if(x.primaryAction==="review_output"||x.primaryAction==="retry_slice"){u==null||u(x);return}if(x.primaryAction==="open_artifact"){const w=(j=x.artifacts.find(b=>b.url))==null?void 0:j.url;if(w&&typeof window<"u"){window.open(w,"_blank","noopener,noreferrer");return}u==null||u(x);return}if(x.runId){d==null||d(x.runId);return}x.sliceRunId&&(d==null||d(x.sliceRunId))};return n.jsxs(Hs,{surface:c==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${c==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${i??""}`,children:[a?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:r}),n.jsx("span",{className:"chip text-micro",children:y.length})]})}):null,y.length===0?n.jsx("div",{className:"px-4 py-4 text-body text-secondary",children:"No slices need intervention right now."}):n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-3 py-2",children:y.map(({item:x,duplicateCount:j},w)=>{var we;const b=(Array.isArray(x.initiativeIds)&&x.initiativeIds.length>0?x.initiativeIds[0]:x.initiativeId)??null,h=(Array.isArray(x.workstreamIds)&&x.workstreamIds.length>0?x.workstreamIds[0]:x.workstreamId)??null,_=(b?v.get(b):null)??Zi(b,"Initiative"),U=x.workstreamTitle??(h?f.get(h)??null:null),le=qu(x,U,h),V=(we=x.statusExplainer)!=null&&we.trim().length?x.statusExplainer:"Review this slice to continue execution.",be=Bt(Ou(x)),H=Bt(V),Z=Bt(_),ce=x.scope?x.scope.replace(/_/g," "):null,xe=x.updatedAt??x.lastEventAt??null;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(w,7)*.022,ease:[.22,1,.36,1]},className:`group hover-lift relative overflow-visible rounded-2xl border bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14] ${x.status==="failed"?"border-red-400/20":x.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>g==null?void 0:g(x),onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),g==null||g(x))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Fu(x.status)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex min-w-0 items-center gap-1 text-micro uppercase tracking-[0.08em] text-muted",children:[n.jsx(yn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:Z})]}),n.jsxs("p",{className:"mt-0.5 inline-flex min-w-0 items-start gap-1.5 text-body font-semibold leading-snug text-white",title:le,children:[n.jsx(yn,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:le})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:be,children:be}),H!==be&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:H,children:H})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-1.5",children:[n.jsx("span",{className:`inline-flex h-6 items-center rounded-full border px-2 text-micro font-semibold uppercase tracking-[0.08em] ${Ru(x.status)}`,children:$u(x.status)}),ce?n.jsx("span",{className:"chip text-micro capitalize",children:ce}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[j>1&&n.jsxs("span",{className:"chip text-micro",children:[j," similar updates"]}),typeof x.decisionCount=="number"&&x.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[x.decisionCount," decision",x.decisionCount===1?"":"s"]}),typeof x.artifactCount=="number"&&x.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[x.artifactCount," artifact",x.artifactCount===1?"":"s"]}),xe&&n.jsxs("span",{children:["Updated ",Mt(xe)]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:K=>K.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>g==null?void 0:g(x),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>k(x),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":x.status==="failed"?"teal":void 0,children:Pu(x)})]})]},x.sliceRunId)})})]})});function Wu(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Uu(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 Hu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Ku(e){return{id:e.id,name:e.title,status:Wu(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Uu(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 oo=150,Vu=12;function lo(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Gu(){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 ml(e,t=null){return fs({queryKey:Vn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if(Pt())return Gu();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<Vu;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(oo),offset:String(i)});r&&hs(u,r);const g=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:_t({workspaceId:r})});if(!g.ok)break;const y=await g.json(),v=y.data??[];if(s.push(...v),!!!((l=y.pagination)!=null&&l.has_more)||v.length===0)break;i+=oo}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}lo(d.updated_at??d.created_at)>lo(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=>Hu(d.status)).sort((d,u)=>{const g=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-g}).map(Ku)},enabled:e,staleTime:6e4})}const Er=50,co=8;function Xu(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Qu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Ju(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Yu(e){const t=Ju(e.sequence);return{id:e.id,name:e.title,status:Xu(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,sequenceIndex:t,hierarchyLabel:typeof t=="number"?`I${t+1}`:void 0,activeAgents:0,totalAgents:0,description:void 0}}function Zu(e,t=null){return fs({queryKey:Vn.liveInitiatives({limit:Er*co,projectId:t}),queryFn:async()=>{var c;if(Pt())return[];const s=[];let r=0;for(let l=0;l<co;l+=1){const d=new URLSearchParams({limit:String(Er),offset:String(r)});t&&t.trim().length>0&&hs(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:_t({workspaceId:t})});if(!u.ok)break;const g=await u.json(),y=g.initiatives??[];s.push(...y);const v=typeof g.total=="number"?g.total:null,f=(c=g.pagination)==null?void 0:c.has_more;if(!(typeof f=="boolean"?f:v!==null?r+y.length<v:y.length===Er)||y.length===0)break;r+=Er}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=>Qu(l.status)).map(Yu)},enabled:e,staleTime:3e4})}const pl=o.createContext(null);function em({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(pl.Provider,{value:{state:t,open:r,close:i},children:e})}function fl(){const e=o.useContext(pl);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function tm(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:E.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]}:t===0&&d===0?{key:"idle-done",segments:[{text:`${i} done today`,color:E.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:E.red,clickable:!0,onClick:c},{text:" · "},{text:`${r} need your input`,color:E.amber,clickable:!0,onClick:a}]}:s>0?{key:`blocked-${s}-${t}`,segments:[{text:`${s} blocked`,color:E.red,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}:r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:E.lime},{text:" · "}]:[],{text:`${r} need your input`,color:E.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:E.lime},{text:" · all systems go"}]}}function uo(e){const{className:t}=e,{key:s,segments:r}=tm(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(bt,{mode:"wait",children:n.jsx(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 wh={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"},nm={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"},vh=e=>nm[qt(e)]??"text-white/60 bg-white/5 border-white/10",kh=e=>{const t=qt(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"},jh=e=>{const t=qt(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"},Nh=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Ih=e=>{const t=qt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},As=e=>{const t=qt(e);return t==="blocked"||t==="failed"||t==="cancelled"?E.red:t==="active"||t==="in_progress"||t==="running"?E.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?E.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?E.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Zr={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:E.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:E.teal,tint:"rgba(20, 184, 166, 0.18)"}},sm=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Vr(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)Vr(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"?(sm.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&Vr(a,t,s+1,r):typeof a=="object"&&a!==null&&Vr(a,t,s+1,r)}}}}function rm(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 us(...e){const t=[],s=new Set;for(const r of e)Vr(r,t,0,s);for(const r of t){const i=rm(r);if(i)return Zr[i]}return Zr.unknown}function im(e){return Zr[e]??Zr.unknown}const am={xs:18,sm:24,md:30};function om({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:li,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 Ks({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=im(e),a=am[t];return n.jsx("span",{className:me("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(om,{provider:e})})})}function lm({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=Xn(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const f=[];return e>0&&f.push({color:E.lime,fraction:e/c}),t>0&&f.push({color:E.red,fraction:t/c}),s>0&&f.push({color:E.amber,fraction:s/c}),f},[e,t,s,c]),d=2.5,u=(r-d)/2,g=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 v=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 x=f.fraction*g,j=-v;return v+=x,n.jsx(ye.circle,{cx:y,cy:y,r:u,fill:"none",stroke:f.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${x} ${g-x}`,strokeDashoffset:j,initial:a?!1:{strokeDasharray:`0 ${g}`},animate:{strokeDasharray:`${x} ${g-x}`},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 Lr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function pa(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function fa(e,t){if(typeof t=="number")return`${e}${t+1}`}const cm=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("W",s)}},dm=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("M",s)}},um=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("T",s)}};function _i(e){return[...e].sort((t,s)=>{const r=typeof t.sequenceIndex=="number"?t.sequenceIndex:Number.POSITIVE_INFINITY,i=typeof s.sequenceIndex=="number"?s.sequenceIndex:Number.POSITIVE_INFINITY;if(r!==i)return r-i;const a=t.createdAt?Date.parse(t.createdAt):0,c=s.createdAt?Date.parse(s.createdAt):0;return a!==c?a-c:0})}function mm(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 pm({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var l;const i=Oc(e),a=o.useMemo(()=>Vn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=fs({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Lr;if(Pt())return mm(e);if(!i)return{...Lr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,g=async w=>{try{const b=new URLSearchParams({type:w,initiative_id:e,limit:"100"}),h=await fetch(`/orgx/api/entities?${b.toString()}`,{headers:u});return h.ok?await h.json():{data:[]}}catch{return{data:[]}}},[y,v,f]=await Promise.all([g("workstream"),g("milestone"),g("task")]),k=Array.isArray(y.data)?_i(y.data.map(w=>cm(w,e))):[],x=Array.isArray(v.data)?_i(v.data.map(w=>dm(w,e))):[],j=Array.isArray(f.data)?_i(f.data.map(w=>um(w,e))):[];return{initiativeId:e,workstreams:k,milestones:x,tasks:j}}});return{details:(i?c.data:null)??(e?{...Lr,initiativeId:e}:Lr),isLoading:i?c.isLoading:!1,error:i?((l=c.error)==null?void 0:l.message)??null:null,refetch:c.refetch}}function fm(){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 ha({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return fs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Pt())return fm();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 ar(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:E.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:E.iris,bg:"rgba(124,124,255,0.10)"}}function hm(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function gm(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function xm({open:e,onClose:t,onLaunched:s}){var oe,ve,je,te,Te,pe;const r=ha({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=ml(e),[a,c]=o.useState(""),[l,d]=o.useState(""),[u,g]=o.useState(""),[y,v]=o.useState(""),[f,k]=o.useState("auto"),[x,j]=o.useState(""),[w,b]=o.useState(null),[h,_]=o.useState(null),[U,le]=o.useState("starter"),[V,be]=o.useState(!1),[H,Z]=o.useState(1),ce=Pt(),xe=o.useMemo(()=>{const C=l.trim();return C?(i==null?void 0:i.find(O=>O.id===C))??null:null},[i,l]),{details:we}=pm({initiativeId:xe?xe.id:null,enabled:e&&!!xe}),K=o.useMemo(()=>hm(we),[we]),Ie=o.useMemo(()=>gm(we,u||null),[we,u]),Ee=((oe=r.data)==null?void 0:oe.agents)??[],fe=o.useMemo(()=>{const C=a.trim();return C?Ee.find(O=>O.id===C)??null:null},[Ee,a]);o.useEffect(()=>{var O,W;if(!e)return;const C=((O=Ee.find(se=>se.isDefault))==null?void 0:O.id)??((W=Ee[0])==null?void 0:W.id)??"";!a&&C&&c(C)},[Ee,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const C=i??[],O=C.length===1?C[0]:null;O&&d(O.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const C=(fe==null?void 0:fe.model)??"",O=C.includes("openrouter")?"openrouter":C.includes("anthropic")?"anthropic":C.includes("openai")?"openai":"auto";k(O)},[e,fe==null?void 0:fe.model,a]),o.useEffect(()=>{e&&(b(null),_(null),le("starter"),Z(1))},[e]),o.useEffect(()=>{g(""),v("")},[l]),o.useEffect(()=>{v("")},[u]),o.useEffect(()=>{e&&(x.trim().length>0||xe&&j(`Kick off: ${xe.name}`))},[x,e,xe]);const ee=!!a.trim()&&!!l.trim(),re=H===1?!!a.trim():H===2?!!l.trim():ee,Le=async()=>{var qe;const C=(h==null?void 0:h.checkout)??"/orgx/api/billing/checkout",O=U&&U.trim().length>0?U.trim():"starter",se=await(await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:O,billingCycle:"monthly"})})).json().catch(()=>null),De=((qe=se==null?void 0:se.data)==null?void 0:qe.url)??(se==null?void 0:se.url)??null;if(!De)throw new Error((se==null?void 0:se.error)??"Checkout unavailable");window.open(De,"_blank","noopener,noreferrer")},ne=async()=>{var De;const C=(h==null?void 0:h.portal)??"/orgx/api/billing/portal",W=await(await fetch(C,{method:"POST"})).json().catch(()=>null),se=((De=W==null?void 0:W.data)==null?void 0:De.url)??(W==null?void 0:W.url)??null;if(!se)throw new Error((W==null?void 0:W.error)??"Billing portal unavailable");window.open(se,"_blank","noopener,noreferrer")},R=async()=>{if(!(!ee||V)){if(ce){t(),s==null||s();return}b(null),_(null),be(!0);try{const C={agentId:a.trim(),message:x.trim()?x.trim():void 0,initiativeId:l.trim(),initiativeTitle:(xe==null?void 0:xe.name)??null,workstreamId:u.trim()?u.trim():null,taskId:y.trim()?y.trim():null,provider:f!=="auto"?f:null},O=new URLSearchParams;O.set("agentId",C.agentId),O.set("initiativeId",C.initiativeId),C.initiativeTitle&&O.set("initiativeTitle",C.initiativeTitle),C.workstreamId&&O.set("workstreamId",C.workstreamId),C.taskId&&O.set("taskId",C.taskId),C.message&&O.set("message",C.message),C.provider&&O.set("provider",C.provider);const W=await fetch(`/orgx/api/agents/launch?${O.toString()}`,{method:"POST"}),se=await W.json().catch(()=>null);if(!W.ok||!(se!=null&&se.ok))throw(se==null?void 0:se.code)==="upgrade_required"&&(_(se.actions??null),le(se.requiredPlan??"starter")),new Error((se==null?void 0:se.error)??`Launch failed (${W.status})`);t(),s==null||s()}catch(C){b(C instanceof Error?C.message:"Launch failed")}finally{be(!1)}}},J=!!((ve=fe==null?void 0:fe.run)!=null&&ve.runId)&&!!((je=fe==null?void 0:fe.run)!=null&&je.pid),P=async()=>{var C;if(!(!((C=fe==null?void 0:fe.run)!=null&&C.runId)||!J||V)&&!ce){b(null),be(!0);try{const O=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(fe.run.runId)}`,{method:"POST"}),W=await O.json().catch(()=>null);if(!O.ok||!(W!=null&&W.ok))throw new Error((W==null?void 0:W.error)??`Stop failed (${O.status})`);await r.refetch()}catch(O){b(O instanceof Error?O.message:"Stop failed")}finally{be(!1)}}},Y=async()=>{var C;if(!(!((C=fe==null?void 0:fe.run)!=null&&C.runId)||V)){if(ce){t(),s==null||s();return}b(null),be(!0);try{const O=new URLSearchParams;O.set("runId",fe.run.runId),x.trim()&&O.set("message",x.trim()),f&&f!=="auto"&&O.set("provider",f);const W=await fetch(`/orgx/api/agents/restart?${O.toString()}`,{method:"POST"}),se=await W.json().catch(()=>null);if(!W.ok||!(se!=null&&se.ok))throw new Error((se==null?void 0:se.error)??`Restart failed (${W.status})`);t(),s==null||s()}catch(O){b(O instanceof Error?O.message:"Restart failed")}finally{be(!1)}}};return e?n.jsx(ci,{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(([C,O])=>n.jsxs("button",{type:"button",onClick:()=>Z(C),className:me("rounded-full px-3 py-1 transition-colors",H===C?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[C,". ",O]},C))})]}),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(bt,{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:[H===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:C=>c(C.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:Ee.map(C=>{const O=ar(C.status);return n.jsxs("option",{value:C.id,children:[C.name," (",C.id,") · ",O.label]},C.id)})})]}),fe&&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:fe.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${ar(fe.status).color}55`,color:ar(fe.status).color,backgroundColor:ar(fe.status).bg},children:ar(fe.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:"})," ",fe.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",fe.workspace??"unknown"]}),((te=fe.context)==null?void 0:te.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",fe.context.initiativeTitle??fe.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:C=>k(C.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."})]}),fe.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",fe.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",fe.run.status,")"]})]}),fe.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:P,disabled:!J||V,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:Y,disabled:V,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"})]})]})]})]}),H===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:C=>d(C.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(C=>n.jsx("option",{value:C.id,children:C.name},C.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:C=>g(C.target.value),disabled:!xe,className:me("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!xe&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),K.map(C=>n.jsx("option",{value:C.id,children:C.name},C.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:C=>v(C.target.value),disabled:!xe,className:me("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!xe&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),Ie.slice(0,80).map(C=>n.jsx("option",{value:C.id,children:C.title},C.id))]}),Ie.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),H===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:x,onChange:C=>j(C.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:((fe==null?void 0:fe.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((xe==null?void 0:xe.name)??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()?((Te=K.find(C=>C.id===u))==null?void 0:Te.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()?((pe=Ie.find(C=>C.id===y))==null?void 0:pe.title)??y:"Any"})]})]})]})]})]},H)}),w&&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:w}),h&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Le().catch(C=>b(C instanceof Error?C.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 ne().catch(C=>b(C instanceof Error?C.message:"Portal failed")),className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08]",children:"Billing portal"}),h.pricing&&n.jsx("a",{href:h.pricing,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary underline decoration-white/20 hover:text-primary",children:"View pricing"})]})]})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-subtle px-5 py-3.5 sm:px-6",children:[n.jsx("div",{className:"text-caption text-secondary",children:H===1?"Pick an agent to configure.":H===2?"Select an initiative scope (required).":ee?"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:[H>1&&n.jsx("button",{type:"button",onClick:()=>Z(C=>C>1?C-1:C),disabled:V,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"}),H<3?n.jsx("button",{type:"button",onClick:()=>Z(C=>C<3?C+1:C),disabled:!re||V,className:me("rounded-xl px-4 py-2 text-body font-semibold transition-colors",re&&!V?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:re&&!V?{backgroundColor:E.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:R,disabled:!ee||V,className:me("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ee&&!V?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ee&&!V?{backgroundColor:E.lime}:void 0,children:V?"Launching…":"Launch"})]})]})]})}):null}const Ci=10,ym=20;function bm(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:E.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:E.iris,bg:"rgba(124,124,255,0.10)"}}function wm(e){return e?e.includes("error")||e.includes("fail")?E.red:e.includes("decision")||e.includes("block")?E.amber:e.includes("complete")||e.includes("success")?E.teal:e.includes("start")||e.includes("launch")?E.lime:E.iris:E.iris}function vm({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var be,H,Z,ce,xe,we;const[d,u]=o.useState(!1),[g,y]=o.useState(!1),[v,f]=o.useState(null),k=nl(s),x=bm((r==null?void 0:r.status)??null),j=o.useMemo(()=>{let K=0,Ie=0,Ee=0,fe=0;for(const ee of i)ee.status==="running"||ee.status==="queued"||ee.status==="pending"?K++:ee.status==="blocked"?Ie++:ee.status==="failed"||ee.status==="cancelled"?Ee++:(ee.status==="completed"||ee.status==="archived")&&fe++;return{running:K,blocked:Ie,failed:Ee,completed:fe}},[i]),w=o.useMemo(()=>[...i].sort((K,Ie)=>Date.parse(Ie.updatedAt??Ie.lastEventAt??Ie.startedAt??"")-Date.parse(K.updatedAt??K.lastEventAt??K.startedAt??"")),[i]),b=d?w:w.slice(0,Ci),h=w.length>Ci,_=o.useMemo(()=>[...a].sort((K,Ie)=>Date.parse(Ie.timestamp)-Date.parse(K.timestamp)).slice(0,ym),[a]),U=!!((be=r==null?void 0:r.run)!=null&&be.runId)&&!!((H=r==null?void 0:r.run)!=null&&H.pid),le=async()=>{var K;if(!(!((K=r==null?void 0:r.run)!=null&&K.runId)||!U||g)){f(null),y(!0);try{const Ie=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),Ee=await Ie.json().catch(()=>null);if(!Ie.ok||!(Ee!=null&&Ee.ok))throw new Error((Ee==null?void 0:Ee.error)??`Stop failed (${Ie.status})`);l==null||l()}catch(Ie){f(Ie instanceof Error?Ie.message:"Stop failed")}finally{y(!1)}}},V=async()=>{var K;if(!(!((K=r==null?void 0:r.run)!=null&&K.runId)||g)){f(null),y(!0);try{const Ie=new URLSearchParams;Ie.set("runId",r.run.runId);const Ee=await fetch(`/orgx/api/agents/restart?${Ie.toString()}`,{method:"POST"}),fe=await Ee.json().catch(()=>null);if(!Ee.ok||!(fe!=null&&fe.ok))throw new Error((fe==null?void 0:fe.error)??`Restart failed (${Ee.status})`);l==null||l()}catch(Ie){f(Ie instanceof Error?Ie.message:"Restart failed")}finally{y(!1)}}};return e?n.jsx(ci,{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($t,{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:x.color,backgroundColor:x.bg},children:x.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:j.running,color:E.lime},{label:"Blocked",value:j.blocked,color:E.red},{label:"Failed",value:j.failed,color:E.amber},{label:"Completed",value:j.completed,color:E.teal}].map(K=>n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:K.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:K.value>0?K.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:K.value})]},K.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:[b.map(K=>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:As(K.status)}}),n.jsxs("button",{onClick:()=>{c(K.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:K.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:Mt(K.updatedAt??K.lastEventAt??K.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:K.status}),K.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(K.progress),"%"]})]})]})]})]},K.id)),h&&n.jsx("button",{type:"button",onClick:()=>u(K=>!K),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${w.length-Ci} older sessions`})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Live Activity"}),_.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:_.map((K,Ie)=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[27px] top-1.5 h-1.5 w-1.5 rounded-full ring-4 ring-black",style:{backgroundColor:wm(K.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:K.title??K.summary??K.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:Mt(K.timestamp)})]})]},K.id??Ie))})]})]}),(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:le,disabled:!U||g,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:g?"Stopping…":"Stop Run"}),n.jsx("button",{type:"button",onClick:V,disabled:g,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:g?"Restarting…":"Restart"})]}),v&&n.jsx("p",{className:"w-full text-caption text-rose-400",children:v})]})]}),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:(Z=r.model)!=null&&Z.includes("openrouter")?"OpenRouter":(ce=r.model)!=null&&ce.includes("anthropic")?"Anthropic":(xe=r.model)!=null&&xe.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Model"}),n.jsx("p",{className:me("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})]}),((we=r.context)==null?void 0:we.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 Dr=120,mo=10,km=24,po=520,jm=58,Nm=56,Im=20,Am=8,ga=new Set(["running","active","in_progress","working","planning","handoff","review"]),Sm=new Set(["blocked","failed"]),_m=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"}],Mm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ea=[{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 ea)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Tm(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 Em(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 hl(e){const t=Tm(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=Em(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 Lm(e){const t=hl(e),s=rt(t.agentId);if(s)return`id:${s}`;const r=rt(t.agentName);return r?`name:${r}`:"unassigned"}function Dm(e){const t=e.trim();return t?Mm.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function ei(e){const t=(e??"").trim();return t?Es(t):!1}function Rm(e){var t,s;return!!(ei((t=e.context)==null?void 0:t.initiativeId)||ei(((s=e.run)==null?void 0:s.initiativeId)??null))}function Mi(e){if(gn(e.agentId,e.agentName))return!0;const s=rt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function cn(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":ga.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function ta(e){const t=rt(e);return t?ga.has(t)||Sm.has(t):!1}function fo(e){const t=rt(e);return t?ga.has(t):!1}function Rr(e){return e?!!(ta(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function $m(e){return e?e.state==="active":!1}function Fm(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function jn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ti(e,t){return jn(t.updatedAt??t.lastEventAt??t.startedAt)-jn(e.updatedAt??e.lastEventAt??e.startedAt)}function Pm({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=As(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(bt,{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 g=r===d.id,y=us(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:me("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",g?"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(Ks,{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:Mt(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const Om=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:c,agentFilter:l,onReconnect:d,onLaunched:u,connectionStatus:g,runtimeInstances:y=[],showSyntheticEntities:v=!1}){var M;const[f,k]=o.useState(new Set),[x,j]=o.useState(!1),[w,b]=o.useState(!1),[h,_]=o.useState(0),[U,le]=o.useState(null),V=ha({enabled:!0}),be=((M=V.data)==null?void 0:M.agents)??[],H=o.useMemo(()=>yr(a),[a]),Z=o.useMemo(()=>H===null?s:s.filter(q=>jn(q.timestamp)>=H),[s,H]);o.useMemo(()=>{var de,Ce,Ze;const q=new Map,ie=[...Z].sort((Je,Fe)=>jn(Fe.timestamp)-jn(Je.timestamp));for(const Je of ie){const Fe=Je.runId;if(!Fe||q.has(Fe))continue;const Ge=((de=Je.summary)==null?void 0:de.trim())??((Ce=Je.description)==null?void 0:Ce.trim())??((Ze=Je.title)==null?void 0:Ze.trim())??"";Ge.length>0&&q.set(Fe,Ge)}return q},[Z]);const{agents:ce,hiddenGroupCount:xe,filteredOutGroupsByDate:we,filteredOutSessionsByDate:K,visibleSessionCount:Ie,archivedGroups:Ee,sessionCountInScope:fe}=o.useMemo(()=>{var Pe;const q=v?t.nodes:t.nodes.filter(z=>!ei(z.initiativeId)),ie=v?be:be.filter(z=>!Rm(z)),de=v?y:y.filter(z=>!ei(z.initiativeId)),Ce=new Map,Ze=new Map,Je=[...de].sort((z,Q)=>jn(Q.lastEventAt??Q.lastHeartbeatAt)-jn(z.lastEventAt??z.lastHeartbeatAt));for(const z of Je){z.runId&&!Ce.has(z.runId)&&Ce.set(z.runId,z);const Q=gn(z.agentId,z.agentName??z.displayName),Ne=rt((Q==null?void 0:Q.agentId)??z.agentId);if(Ne){const Re=Ze.get(Ne)??[];Re.push(z),Ze.set(Ne,Re)}}const Fe=new Map;for(const z of q){const Q=hl(z),Ne=Lm(z),Re=rt(Q.agentId),$e=rt(Q.agentName);let Oe=Fe.get(Ne)??null;if(!Oe&&Re&&$e){const Se=`name:${$e}`,Ve=Fe.get(Se);Ve&&(Fe.delete(Se),Ve.groupKey=Ne,Fe.set(Ne,Ve),Oe=Ve)}if(!Oe&&$e){const Se=Array.from(Fe.values()).find(Ve=>rt(Ve.agentName)===$e);Se&&(Oe=Se)}Oe?(Oe.nodes.push(z),!Oe.agentId&&Q.agentId&&(Oe.agentId=Q.agentId),(Oe.agentName==="OrgX"||!Oe.agentName)&&Q.agentName&&(Oe.agentName=Q.agentName)):Fe.set(Ne,{groupKey:Ne,agentId:Q.agentId,agentName:Q.agentName??Q.agentId??"OrgX",nodes:[z],latest:z,runtime:null,runtimeActiveCount:0})}for(const z of ie){const Q=gn(z.id,z.name),Ne=(Q==null?void 0:Q.agentId)??z.id,Re=(Q==null?void 0:Q.agentName)??z.name,$e=rt(Ne),Oe=rt(Re),Se=$e?`id:${$e}`:null,Ve=Oe?`name:${Oe}`:null;let lt=null;if(Se&&Fe.has(Se))lt=Se;else if(Ve&&Fe.has(Ve))lt=Ve;else{const ze=Array.from(Fe.entries()).find(([,Tt])=>$e&&rt(Tt.agentId)===$e||Oe&&rt(Tt.agentName)===Oe);lt=(ze==null?void 0:ze[0])??null}if(lt){const ze=Fe.get(lt);ze.catalogAgent=z,!ze.agentId&&Ne&&(ze.agentId=Ne),(ze.agentName==="OrgX"||!ze.agentName)&&Re&&(ze.agentName=Re),Se&&ze.groupKey!==Se&&!Fe.has(Se)&&(Fe.delete(ze.groupKey),ze.groupKey=Se,Fe.set(Se,ze))}else{const ze=Se??Ve??`catalog:${Re.toLowerCase()}`;Fe.set(ze,{groupKey:ze,agentId:Ne,agentName:Re,nodes:[],latest:null,catalogAgent:z,runtime:null,runtimeActiveCount:0})}}for(const z of ea){const Q=`orgx:${z.id}`,Ne=`id:${Q}`;let Re=Fe.get(Ne)??null;if(!Re){const $e=Array.from(Fe.entries()).find(([,Oe])=>{const Se=gn(Oe.agentId,Oe.agentName);return rt(Se==null?void 0:Se.agentId)===rt(Q)});$e&&(Fe.delete($e[0]),Re=$e[1],Re.groupKey=Ne,Fe.set(Ne,Re))}if(Re||(Re={groupKey:Ne,agentId:Q,agentName:z.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Fe.set(Ne,Re)),Re.agentId=Q,Re.agentName=z.name,!Re.catalogAgent){const $e=ie.find(Oe=>{const Se=gn(Oe.id,Oe.name);return rt(Se==null?void 0:Se.agentId)===rt(Q)});$e&&(Re.catalogAgent=$e)}}const Ge=new Map(ea.map((z,Q)=>[rt(`orgx:${z.id}`),Q]));for(const z of Fe.values()){z.nodes.length>0&&(z.nodes.sort(Ti),z.latest=z.nodes[0]);const Q=[],Ne=new Set;if((Pe=z.latest)!=null&&Pe.runId){const $e=Ce.get(z.latest.runId);$e&&!Ne.has($e.id)&&(Q.push($e),Ne.add($e.id))}for(const $e of z.nodes){if(!$e.runId)continue;const Oe=Ce.get($e.runId);Oe&&!Ne.has(Oe.id)&&(Q.push(Oe),Ne.add(Oe.id))}const Re=rt(z.agentId);if(Re)for(const $e of Ze.get(Re)??[])Ne.has($e.id)||(Q.push($e),Ne.add($e.id));Q.sort(($e,Oe)=>jn(Oe.lastEventAt??Oe.lastHeartbeatAt)-jn($e.lastEventAt??$e.lastHeartbeatAt)),z.runtime=Q[0]??null,z.runtimeActiveCount=Q.filter($e=>$m($e)).length}const He=Array.from(Fe.values()).sort((z,Q)=>{const Ne=Mi(z),Re=Mi(Q);if(Ne!==Re)return Ne?-1:1;if(Ne&&Re){const $e=gn(z.agentId,z.agentName),Oe=gn(Q.agentId,Q.agentName),Se=Ge.get(rt(($e==null?void 0:$e.agentId)??z.agentId))??999,Ve=Ge.get(rt((Oe==null?void 0:Oe.agentId)??Q.agentId))??999;if(Se!==Ve)return Se-Ve}return z.latest&&Q.latest?Ti(z.latest,Q.latest):z.latest&&!Q.latest?-1:!z.latest&&Q.latest?1:z.agentName.localeCompare(Q.agentName)}),ft=Qo(a),it=ft.id==="live",at=ft.minutes===null||it?null:Date.now()-ft.minutes*6e4,he=[],Ke=[];let Ae=0,B=0;for(const z of He){const Q=(z.runtimeActiveCount??0)>0,Ne=Mi(z);if(z.nodes.length===0){const Se=Rr(z.catalogAgent);(Ne||it&&(Se||Q))&&he.push(z);continue}if(it){const Se=z.nodes.filter(ze=>ta(cn(ze))),Ve=z.nodes.filter(ze=>!ta(cn(ze))),lt=Rr(z.catalogAgent);if(Se.length===0){Ne||lt||Q?he.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,Ke.push(z));continue}B+=Ve.length,Ve.length>0&&Ke.push({...z,nodes:Ve,latest:Ve[0]??null}),he.push({...z,nodes:Se,latest:Se[0]??null});continue}if(at===null){he.push(z);continue}const Re=z.nodes.filter(Se=>fo(cn(Se))?!0:jn(Se.updatedAt??Se.lastEventAt??Se.startedAt)>=at),$e=Rr(z.catalogAgent);if(Re.length===0){Ne||$e||Q?he.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,Ke.push(z));continue}const Oe=z.nodes.filter(Se=>fo(cn(Se))?!1:jn(Se.updatedAt??Se.lastEventAt??Se.startedAt)<at);B+=Oe.length,Oe.length>0&&Ke.push({...z,nodes:Oe,latest:Oe[0]}),he.push({...z,nodes:Re,latest:Re[0]})}return{agents:he.slice(0,Dr),hiddenGroupCount:Math.max(0,he.length-Dr),filteredOutGroupsByDate:Ae,filteredOutSessionsByDate:B,visibleSessionCount:he.slice(0,Dr).reduce((z,Q)=>z+Q.nodes.length,0),archivedGroups:Ke,sessionCountInScope:q.length}},[a,t.nodes,be,y,v]);o.useEffect(()=>{b(!1),_(0)},[a]);const ee=o.useMemo(()=>Ee.reduce((q,ie)=>q+ie.nodes.length,0),[Ee]),re=o.useMemo(()=>ce.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[ce]),Le=o.useMemo(()=>{if(re.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const ie of re)f.has(ie)&&(q+=1);return{allCollapsed:q===re.length,allExpanded:q===0}},[f,re]),ne=o.useMemo(()=>{const q=[];for(const ie of Ee)for(const de of ie.nodes)q.push({node:de,agentName:ie.agentName});return q.sort((ie,de)=>Ti(ie.node,de.node)),q.slice(0,(h+1)*_m)},[Ee,h]),R=q=>{k(ie=>{const de=new Set(ie);return de.has(q)?de.delete(q):de.add(q),de})},J=()=>{k(()=>Le.allCollapsed?new Set:new Set(re))},P=o.useMemo(()=>U?ce.find(q=>q.groupKey===U)??null:null,[ce,U]),Y=o.useMemo(()=>(P==null?void 0:P.nodes)??[],[P]),oe=o.useMemo(()=>{if(!P)return[];const q=rt(P.agentName),ie=rt(P.agentId),de=gn(P.agentId,P.agentName);return Z.filter(Ce=>{const Ze=rt(Ce.agentName),Je=rt(Ce.agentId),Fe=gn(Ce.agentId,Ce.agentName);return q!==null&&Ze===q||ie!==null&&Je===ie||de!==null&&Fe!==null&&rt(de.agentId)===rt(Fe.agentId)})},[Z,P]),ve=fe===0,je=be.length>0,te=o.useRef(null),[Te,pe]=o.useState(0),[C,O]=o.useState(0),W=o.useCallback(q=>{const ie=q.currentTarget.scrollTop;pe(de=>Math.abs(de-ie)<1?de:ie)},[]);o.useEffect(()=>{const q=te.current;if(!q)return;const ie=()=>{const de=q.clientHeight,Ce=q.scrollTop;O(Ze=>Ze===de?Ze:de),pe(Ze=>Math.abs(Ze-Ce)<1?Ze:Ce)};if(ie(),typeof ResizeObserver<"u"){const de=new ResizeObserver(()=>ie());return de.observe(q),()=>de.disconnect()}return window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[ce.length]);const{visibleAgentGroups:se,topVirtualSpacerPx:De,bottomVirtualSpacerPx:qe,virtualizationEnabled:Me}=o.useMemo(()=>{if(!(ce.length>km&&C>0))return{visibleAgentGroups:ce,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const ie=ce.map(He=>{const it=f.has(He.groupKey)?0:Math.min(He.nodes.length,mo);let at=jm;return it>0&&(at+=Im+it*Nm,He.nodes.length>it&&(at+=20)),at+Am}),de=new Array(ie.length+1).fill(0);for(let He=0;He<ie.length;He+=1)de[He+1]=de[He]+ie[He];const Ce=de[de.length-1],Ze=Math.max(0,Te-po),Je=Te+C+po;let Fe=0;for(;Fe<ce.length&&de[Fe+1]<Ze;)Fe+=1;let Ge=Fe;for(;Ge<ce.length&&de[Ge]<Je;)Ge+=1;return Ge<=Fe&&(Ge=Math.min(ce.length,Fe+1)),{visibleAgentGroups:ce.slice(Fe,Ge),topVirtualSpacerPx:de[Fe],bottomVirtualSpacerPx:Math.max(0,Ce-de[Ge]),virtualizationEnabled:!0}},[ce,f,Te,C]);return n.jsxs(Hs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(xm,{open:x,onClose:()=>j(!1),onLaunched:()=>{V.refetch(),u==null||u()}}),n.jsx(vm,{open:U!==null,onClose:()=>le(null),agentName:(P==null?void 0:P.agentName)??"",catalogAgent:(P==null?void 0:P.catalogAgent)??null,sessions:Y,activity:oe,onSelectSession:i,onRefresh:()=>V.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:[Ie," of ",fe]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:J,disabled:re.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Le.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Le.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>j(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:te,onScroll:W,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[ce.length===0&&!ve&&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."})]}),ce.length===0&&ve&&!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:[Me&&De>0&&n.jsx("div",{"aria-hidden":"true",style:{height:De}}),se.map(q=>{var Se;const ie=q.groupKey,de=f.has(ie),Ce=q.latest,Ze=Ce?cn(Ce):null,Je=q.nodes.length>0,Fe=q.nodes.length===1,Ge=Rr(q.catalogAgent),He=q.runtime??null,ft=(q.runtimeActiveCount??0)>0,it=!Je&&ft&&He!==null,at=Je||it,he=Ce?r===Ce.id:!1,Ke=q.agentName||((Se=q.catalogAgent)==null?void 0:Se.name)||q.agentId||"OrgX",Ae=gn(q.agentId,Ke),B=(Ae==null?void 0:Ae.agentName)??Dm(Ke),Pe=(Ae==null?void 0:Ae.role)??nl(B),z=us(q.agentId,B,He==null?void 0:He.displayName,Ce==null?void 0:Ce.runtimeProvider,Ce==null?void 0:Ce.runtimeClient),Q=Ae===null&&(z.id==="codex"||z.id==="openai"||z.id==="anthropic"||z.id==="openclaw"),Ne=Pe?`${Ke} — ${Pe}`:Ke,Re=de?[]:Je?q.nodes.slice(0,mo):[],$e=Math.max(0,Je?q.nodes.length-Re.length:0),Oe=rt(l)===rt(B)||rt(l)===rt(Ne);return n.jsxs(ye.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:me("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",he&&"border-white/20 bg-white/[0.05]",Oe&&"border-[#0AD4C4]/30",!Je&&!Ge&&!ft&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Fe?i(q.nodes[0].id):it?R(ie):!Je&&Ge?le(ie):c?c(Oe?null:B):Ce&&i(Ce.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:[Q?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(Ks,{provider:z.id,size:"sm",showRing:!1})}):n.jsx(lm,{running:q.nodes.filter(Ve=>{const lt=cn(Ve);return lt==="running"||lt==="handoff"||lt==="review"}).length,blocked:q.nodes.filter(Ve=>{const lt=cn(Ve);return lt==="blocked"||lt==="failed"}).length,paused:q.nodes.filter(Ve=>{const lt=cn(Ve);return lt==="paused"||lt==="cancelled"}).length,size:36,children:n.jsx($t,{name:B,size:"sm",hint:`${q.agentId??""} ${B}`})}),Ae&&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"})}),Ce&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:As(Ze??Ce.status),borderColor:E.cardBg}}),!Ce&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ge?As("running"):"rgba(255,255,255,0.2)",borderColor:E.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:Pe?`${Ke} — ${Pe}`:Ke,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[B,Pe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Pe]})]})}),n.jsx("div",{className:"flex items-center gap-1.5",children:Je?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const Ve={};for(const lt of q.nodes){const ze=cn(lt);Ve[ze]=(Ve[ze]??0)+1}return Object.entries(Ve).map(([lt,ze])=>`${ze} ${lt}`).join(" · ")})(),children:(()=>{const Ve={};for(const ze of q.nodes){const Tt=cn(ze);Ve[Tt]=(Ve[Tt]??0)+1}const lt=q.nodes.length;return Object.entries(Ve).map(([ze,Tt])=>n.jsx("span",{style:{width:`${Tt/lt*100}%`,backgroundColor:As(ze)}},ze))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:q.nodes.length})]}):Ge||ft?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:As("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:()=>le(ie),"aria-label":`View ${B} 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:()=>{at&&R(ie)},disabled:!at,"aria-label":at?de?"Expand sessions":"Collapse sessions":"No sessions to expand",className:me("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",at?"hover:bg-white/[0.05] hover:text-primary":"cursor-default opacity-35"),children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:me("transition-transform",at&&!de?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(bt,{initial:!1,children:at&&!de&&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 Ve=new Map,lt=[];for(const et of Re){const kt=cn(et);if(kt==="blocked"||kt==="paused"||kt==="failed"){const Jt=`${kt}:${et.blockerReason??""}`,Gt=Ve.get(Jt)??[];Gt.push(et),Ve.set(Jt,Gt)}else lt.push(et)}const ze=[];for(const[et,kt]of Ve)kt.length>3?ze.push({status:et.split(":")[0],nodes:kt}):lt.push(...kt);const Tt=(et,kt)=>{const Jt=r===et.id,Gt=cn(et),un=us(et.agentName,et.title,et.lastEventSummary,et);return n.jsx(ye.button,{onClick:()=>i(et.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(kt*.015,.12)},className:me("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Jt?"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(Ks,{provider:un.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:et.title,children:et.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:un.accent},children:un.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Gt}),n.jsx("span",{title:Qr(et.updatedAt??et.lastEventAt??et.startedAt??Date.now()),children:Mt(et.updatedAt??et.lastEventAt??et.startedAt??Date.now())})]}),et.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(et.progress)}%`,background:`linear-gradient(90deg, ${E.lime}, ${E.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:As(Gt)},"aria-label":Gt,title:Gt})]})},et.id)};return n.jsxs(n.Fragment,{children:[lt.map((et,kt)=>Tt(et,kt)),ze.map(et=>n.jsx(Pm,{status:et.status,nodes:et.nodes,onSelectSession:i,selectedSessionId:r},`cg-${et.status}-${et.nodes.length}`))]})})(),$e>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",$e," older sessions hidden"]})]})})})]},ie)}),Me&&qe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:qe}})]}),xe>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Dr," most recent agent groups (",xe," older groups omitted)."]}),d&&g!=="connected"&&!je&&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))})]}),K>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{b(q=>!q),w&&_(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:me("transition-transform",w?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[ee," archived session",ee===1?"":"s",we>0?` across ${we} agent${we===1?"":"s"}`:""]})]}),n.jsx(bt,{initial:!1,children:w&&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:[ne.map(({node:q,agentName:ie})=>{const de=cn(q),Ce=q.runtimeProvider?{id:Fm(q.runtimeProvider)}:us(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(Ks,{provider:Ce.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:ie}),n.jsx("span",{className:"text-micro text-muted",title:Qr(q.updatedAt??q.lastEventAt??q.startedAt??Date.now()),children:Mt(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:de})]})]},q.id)}),ne.length<ee&&n.jsxs("button",{onClick:()=>_(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 (",ee-ne.length," remaining)"]})]})})})]})]})]})}),Bm=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),qm=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),zm=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),Wm=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Um=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function qs(e){return e?qt(e):""}function Ei(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Hm(e){return e.some(t=>Bm.has(t))}function Km(e){return e.some(t=>qm.has(t))}function Vm(e){return e.some(t=>zm.has(t))}function Gm(e){return e.some(t=>Wm.has(t))}function Xm(e){return e.some(t=>Um.has(t))}function Un(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 Qm(e){const t=qs(e.sessionStatus),s=qs(e.sessionPhase),r=qs(e.sessionState),i=qs(e.sliceStatus),a=qs(e.activityStatus),c=qs(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(_=>_.length>0),u=Ei(e.blockingDecisionCount),g=Ei(e.nonBlockingDecisionCount),y=Ei(e.blockerCount),v=l==="run_failed",f=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",k=v||Hm(d),x=Km(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,j=Vm(d)||y>0,w=f||Gm(d),b=Xm(d)||l==="run_started";if(k)return Un("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(w&&!x&&!k&&y===0&&!e.blockerReason)return g>0?Un("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Un("completed","Execution completed successfully.",{tone:"positive"});if(x||j)return u>0||e.decisionRequired===!0||l==="decision_requested"?Un("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Un("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:j?"critical":"warning"});if(w)return g>0?Un("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Un("completed","Execution completed successfully.",{tone:"positive"});if(b){const _=g>0?`Running with ${g} optional decision${g===1?"":"s"} available.`:"Running.";return Un("in_progress",_,{tone:"neutral"})}return Un("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const Li=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Jm(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ss(e,t){const s=[];let r=0,i=0;Li.lastIndex=0;for(let a=Li.exec(e);a;a=Li.exec(e)){const[c]=a,l=a.index;l>r&&s.push(e.slice(r,l));const d=`${t}-${i++}`,u=a[1],g=a[2],y=a[3],v=a[4],f=a[5],k=a[6],x=a[7];u&&g&&Jm(g)?s.push(n.jsx("a",{href:g,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)):v||f?s.push(n.jsx("strong",{className:"font-semibold text-white",children:v??f},d)):k||x?s.push(n.jsx("em",{className:"italic text-bright",children:k??x},d)):s.push(c),r=l+c.length}return r<e.length&&s.push(e.slice(r)),s}function Ym(e,t){const s=e.split(`
204
+ `),r=[];return s.forEach((i,a)=>{r.push(...Ss(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function Gr(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Zm(e){const t=Gr(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function ep(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function tp(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("|")&&Zm(l)){const v=Gr(i),k=Gr(l).map(j=>ep(j));r+=2;const x=[];for(;r<t.length;){const j=t[r]??"";if(!j.trim()||!j.includes("|"))break;x.push(Gr(j)),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:v.map((j,w)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:k[w]??"left"},children:Ss(j,`tbl-h-${r}-${w}`)},`tbl-h-${w}`))})}),n.jsx("tbody",{children:x.map((j,w)=>n.jsx("tr",{className:w<x.length-1?"border-b border-subtle":void 0,children:v.map((b,h)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:k[h]??"left"},children:Ss(j[h]??"",`tbl-r-${r}-${w}-${h}`)},`tbl-r-${w}-c-${h}`))},`tbl-r-${w}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const v=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:[v&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:v}),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 v=d[1].length,f=d[2],k=v===1?"text-title font-semibold":v===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:me("tracking-[-0.01em] text-white",k),children:Ss(f,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const v=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!k)break;v.push(k[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:v.map((f,k)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Ss(f,`ul-${r}-${k}`)},`ul-${r}-${k}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const v=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!k)break;v.push(k[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:v.map((f,k)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Ss(f,`ol-${r}-${k}`)},`ol-${r}-${k}`))},`ol-${r}`));continue}const y=[];for(;r<t.length;){const v=t[r]??"",f=v.trim();if(!f||/^(#{1,3})\s+/.test(f)||/^\s*[-*]\s+/.test(v)||/^\s*\d+\.\s+/.test(v)||f.startsWith("```"))break;y.push(v),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Ym(y.join(`
208
+ `),`p-${r}`)},`p-${r}`))}return s}function ti({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:Ss(r,"inline")}):n.jsx("div",{className:me("space-y-2",s),children:tp(r)}):null}function gl(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function np(e){if(!e)return;const t=gl(e.metadata);return t?{...e,...t}:e}const xl={run_started:{icon:"play",label:"Run started",color:E.teal},run_completed:{icon:"check_circle",label:"Run completed",color:E.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:E.red},artifact_created:{icon:"file",label:"Artifact",color:E.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:E.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:E.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:E.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:E.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:E.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:E.red},milestone_completed:{icon:"flag",label:"Milestone",color:E.cyan},delegation:{icon:"workflow",label:"Delegation",color:E.iris}};function Fn(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 na(e){return e?e.toLowerCase():""}function sp(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Fn(t,["source","event","eventType","artifact_type","action","kind"]),Fn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function rp(e,t){const s=na(Fn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:E.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:E.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:E.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:E.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:E.cyan}:xl.artifact_created}function ip(e){const t=np(gl(e.metadata)),s=sp(e,t),r=na(Fn(t,["source"])),i=na(Fn(t,["action"])),a=Fn(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"&&Fn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:E.teal};if(a==="auto_continue_stopped"){const l=Fn(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Autopilot blocked",color:E.red}:l==="budget_exhausted"?{icon:"infinity",label:"Budget exhausted",color:E.amber}:{icon:"infinity",label:"Autopilot stopped",color:E.amber}}if(a==="autopilot_transition"){const l=Fn(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Autopilot blocked",color:E.red}:{icon:"infinity",label:"Autopilot transition",color:E.teal}}const c=Fn(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Slice completed",color:E.lime}:{icon:"infinity",label:"Autopilot slice",color:E.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:E.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:E.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:E.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:E.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:E.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:E.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:E.teal};if(e.type==="artifact_created")return rp(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:E.red}:{icon:"shield_check",label:"Decision approved",color:E.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Dispatch",color:E.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:E.teal}}return xl[e.type]??{icon:"message",label:"Activity",color:E.textMuted}}function ap({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(sl,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...r,children:[n.jsx("ellipse",{cx:"12",cy:"5.5",rx:"6.5",ry:"2.5"}),n.jsx("path",{d:"M5.5 5.5v6c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-6"}),n.jsx("path",{d:"m8 17-2 2 2 2"}),n.jsx("path",{d:"M16 17l2 2-2 2"})]});case"heartbeat":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3v6"}),n.jsx("path",{d:"M8 5h8"}),n.jsx("path",{d:"M7 11h10v10H7z"}),n.jsx("path",{d:"M9 14h6"})]});case"quality_gate":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"route":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"6",cy:"6",r:"2"}),n.jsx("circle",{cx:"18",cy:"18",r:"2"}),n.jsx("path",{d:"M8 6h4a4 4 0 0 1 4 4v6"}),n.jsx("path",{d:"M16 6h2"})]});case"terminal":return n.jsxs("svg",{...r,children:[n.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),n.jsx("path",{d:"m7 9 3 3-3 3"}),n.jsx("path",{d:"M13 15h4"})]});case"compass":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m10 10 6-2-2 6-6 2z"})]});case"infinity":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.739-8-4.585 0-4.585 8 0 8 5.606 0 7.644-8 12.74-8z"})});case"message":default:return n.jsx("svg",{...r,children:n.jsx("path",{d:"M21 12a8 8 0 0 1-8 8H7l-4 2 1.5-4A8 8 0 1 1 21 12z"})})}}function ni(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function sa(e){if(!e)return;const t=ni(e.metadata);return t?{...e,...t}:e}function op(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function lp(e){let t=0;for(const s of e){const r=sa(ni(s.metadata)),i=r==null?void 0:r.costTotal;typeof i=="number"&&(t+=i)}return t<=0?null:t<.01?"<$0.01":`$${t.toFixed(2)}`}const cp=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(()=>lp(d),[d]),g=o.useMemo(()=>{if(d.length<2)return null;const f=Date.parse(d[0].timestamp),x=Date.parse(d[d.length-1].timestamp)-f;return x<6e4?`${Math.round(x/1e3)}s`:x<36e5?`${Math.round(x/6e4)}m`:`${(x/36e5).toFixed(1)}h`},[d]),y=o.useMemo(()=>{let f=null,k=null,x=null,j=null,w=null;for(const h of d){const _=sa(ni(h.metadata));if(_&&(!f&&typeof _.domain=="string"&&(f=_.domain),!k&&typeof _.provider=="string"&&(k=_.provider),!x&&typeof _.model=="string"&&(x=_.model),!j&&typeof _.spawn_guard_model_tier=="string"&&(j=_.spawn_guard_model_tier),!w&&typeof _.kickoff_context_hash=="string"&&(w=_.kickoff_context_hash),f&&(k||x)&&j&&w))break}return!(f||k||x||j||w)?null:{domain:f,provider:k,model:x,modelTier:j,kickoffContextHash:w}},[d]),v=(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:E.lime,boxShadow:`0 0 12px ${E.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:ot(v)})]}),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($t,{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":""]}),g&&n.jsx("span",{children:g}),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"?`${E.lime}20`:s.status==="failed"?`${E.red}20`:`${E.teal}20`,color:s.status==="running"?E.lime:s.status==="failed"?E.red:E.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?gr(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(bt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${E.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((f,k)=>{var V;const x=ip(f),j=x.color,w=(V=sa(ni(f.metadata)))==null?void 0:V.model,b=typeof w=="string"?gr(w):null,h=ot(f.title??""),_=f.type==="run_failed",U=f.type==="artifact_created",le=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:`${j}20`,color:j,border:`1px solid ${j}40`},children:n.jsx(ap,{icon:x.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${_?"text-red-400":le?"text-amber-300":U?"text-cyan-300":"text-bright"}`,children:h}),f.summary&&f.summary!==h&&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:op(f.timestamp)}),b&&n.jsx("span",{className:"text-micro text-faint",children:b})]})]},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":"",g?` over ${g}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:Qr(d[d.length-1].timestamp),children:Mt(d[d.length-1].timestamp)})]})]})]})});function dp({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(bt,{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:`${E.teal}08`,border:`1px solid ${E.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 up={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function mp({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,userStateLabel:l,userStateWhy:d,relativeTime:u,timeLabel:g,isRecent:y,enableMotion:v,onOpen:f,ariaLabel:k,artifactSnippet:x}){const j="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",w=n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx($t,{name:a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:me("absolute inset-y-0 left-0 w-[2px] rounded-full",y&&"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:g}),n.jsx("span",{className:"text-micro text-muted",children:u})]})]}),x?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:x.label}),x.preview&&n.jsx("span",{className:"ml-1.5 text-cyan-200/60",children:x.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(ti,{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 v?n.jsx(ye.button,{type:"button",variants:up,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:f,className:j,"aria-label":k,children:w},e):n.jsx("button",{type:"button",onClick:f,className:me(j,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":k,children:w},e)}function pp({open:e,onClose:t,children:s}){return n.jsx(ci,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function fp(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 hp={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 gp({item:e,className:t}){const s=o.useMemo(()=>Jl(e),[e]),r=fp(e),i=hp[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(Di,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(Di,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(Di,{label:"Next step",value:s.nextStep,styles:i})]})}function Di({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 ho=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),xp=[{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"}],or=[{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"}],go={type:"spring",stiffness:400,damping:25},xo={scale:.985};function Qt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function yp(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 lr(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?Bt(In(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function bp(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function wp(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 si(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Vs(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 yl(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function vp(e){return e==="agent"?"assistant":e}function kp(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function jp(e,t){return t.map(s=>({id:s.id,role:vp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function bl(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function Gs(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Xr(e){const t=Gs(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=Gs(t.latestMessage),i=Gs(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 Np(e){const t=Gs(e);if(!t)return null;const s=Xr({...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=>Gs(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=>Gs(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)=>Qt(a.createdAt)-Qt(c.createdAt)),launches:i.sort((a,c)=>Qt(c.requestedAt)-Qt(a.requestedAt))}}function Ip(e,t,s){const r=Qt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Qt(s.startIso),c=Qt(s.endIso);return!(a&&r<a||c&&r>c)}const i=yr(t,Date.now());return i?r>=i:!0}async function cr(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 Ri(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)=>Qt(i.lastActivityAt??i.updatedAt)-Qt(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)=>Qt(i.lastActivityAt??i.updatedAt)-Qt(r.lastActivityAt??r.updatedAt))}const wl=o.createContext(null),vl=o.createContext(null);function xa(){const e=o.useContext(wl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function ya(){const e=o.useContext(vl);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function Sp({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:c,timeFilterId:l,customTimeRange:d,snapshot:u,onRequestRefresh:g}){const[y,v]=o.useState((u==null?void 0:u.threads)??[]),[f,k]=o.useState(null),[x,j]=o.useState(null),[w,b]=o.useState(!1),[h,_]=o.useState(null),[U,le]=o.useState("resting"),[V,be]=o.useState(""),[H,Z]=o.useState(!1),[ce,xe]=o.useState(!1),[we,K]=o.useState(null),[Ie,Ee]=o.useState(null),[fe,ee]=o.useState([]),[re,Le]=o.useState(""),[ne,R]=o.useState([]),[J,P]=o.useState(""),[Y,oe]=o.useState(null),[ve,je]=o.useState(""),[te,Te]=o.useState(!1),[pe,C]=o.useState(""),[O,W]=o.useState([]),[se,De]=o.useState(!1),[qe,Me]=o.useState("auto"),[M,q]=o.useState(!1),[ie,de]=o.useState(!1),[Ce,Ze]=o.useState(!1),Je=o.useRef(null),Fe=o.useRef(null),Ge=o.useRef(null),He=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&v(T=>Ap(T,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{f&&v(T=>T.sort((ue,X)=>Qt(X.lastActivityAt)-Qt(ue.lastActivityAt)))},[f]);const{data:ft}=ha({enabled:!0,refetchInterval:8e3}),it=o.useMemo(()=>{var ue,X;const T=new Map;for(const ge of xp)T.set(ge.id,{id:ge.id,name:ge.name,handle:ge.handle,domain:ge.domain,domainLabel:ge.domainLabel,role:ge.role,status:"idle",currentTask:null,isSystem:!1});if(ft!=null&&ft.agents)for(const ge of ft.agents){const Xe=T.get(ge.id);Xe?(Xe.status=ge.status==="running"?"running":(ue=ge.blockers)!=null&&ue.length?"blocked":"idle",Xe.currentTask=ge.currentTask??null):T.set(ge.id,{id:ge.id,name:ge.name,handle:ge.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:ge.status==="running"?"running":(X=ge.blockers)!=null&&X.length?"blocked":"idle",currentTask:ge.currentTask??null,isSystem:ho.has(ge.id)})}for(const ge of t){const Xe=(ge.agentId??"").trim(),Et=(ge.agentName??"").trim();!Xe||!Et||T.has(Xe)||T.set(Xe,{id:Xe,name:Et,handle:Xe,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:ho.has(Xe)})}return Array.from(T.values()).filter(ge=>!ge.isSystem).sort((ge,Xe)=>ge.name.localeCompare(Xe.name))},[ft,t]),at=o.useMemo(()=>s.map(T=>({id:T.id,name:T.name})).sort((T,ue)=>T.name.localeCompare(ue.name)),[s]),he=o.useMemo(()=>it.find(T=>T.id===re)??null,[it,re]),Ke=o.useMemo(()=>{const T=new Set(ne);return it.filter(ue=>T.has(ue.id))},[it,ne]),Ae=o.useMemo(()=>at.find(T=>T.id===J)??null,[at,J]);o.useEffect(()=>{re&&R(T=>T.filter(ue=>ue!==re))},[re]);const B=o.useMemo(()=>it.slice(0,8),[it]),Pe=o.useMemo(()=>{const T=ve.trim().toLowerCase();return T?it.filter(ue=>ue.name.toLowerCase().includes(T)||ue.handle.toLowerCase().includes(T)||ue.domain.toLowerCase().includes(T)||ue.role.toLowerCase().includes(T)):it},[it,ve]),z=o.useMemo(()=>{const T=pe.trim().toLowerCase();return T?at.filter(ue=>ue.name.toLowerCase().includes(T)):at},[at,pe]),Q=o.useMemo(()=>{const T=i.trim().toLowerCase(),ue=y.filter(X=>!wp(X,a)||!Ip(X,l,d)?!1:T.length===0?!0:bp(X).includes(T));return ue.sort((X,ge)=>{const Xe=Qt(ge.lastActivityAt)-Qt(X.lastActivityAt);return c==="newest"?Xe:-Xe}),ue},[d,i,c,a,y,l]),Ne=o.useMemo(()=>{if(!f||Q.some(ue=>ue.id===f))return Q;const T=y.find(ue=>ue.id===f);return T?[T,...Q]:Q},[f,Q,y]),Re=o.useMemo(()=>y.find(T=>T.id===f)??null,[f,y]),$e=o.useMemo(()=>fe.filter(T=>T.status!=="ready").length,[fe]),Se=V.trim().length>0&&!H,Ve=o.useMemo(()=>$e>0?`${$e} attachment(s) still processing.`:"Press Enter to send.",[$e]),lt=o.useMemo(()=>H?"Sending…":ce?"Launching…":"Send",[ce,H]),ze=o.useMemo(()=>new Ul({api:"/orgx/api/chat/usechat"}),[]),{messages:Tt,setMessages:et,sendMessage:kt,status:Jt,error:Gt,clearError:un}=Ol({id:`orgx-chat-guidance-${r??"global"}`,transport:ze,onError:T=>{K(lr((T==null?void 0:T.message)??null,"send"))}});o.useEffect(()=>{if(!x){et([]);return}et(jp(x.id,x.messages))},[x,et]);const An=o.useMemo(()=>{const T=[...Tt].reverse().find(X=>X.role==="assistant");if(!T)return null;const ue=kp(T);return ue.length>0?ue:null},[Tt]),gs=o.useRef(null);o.useEffect(()=>{if(Jt!=="ready"&&Jt!=="error"||!An)return;const T=[...Tt].reverse().find(ue=>ue.role==="assistant");!T||T.id===gs.current||(gs.current=T.id,W(ue=>[...ue,{id:`guidance_${T.id}`,role:"agent",body:An,timestamp:new Date().toISOString()}]))},[Jt,An,Tt]);const ht=o.useCallback(()=>{be(""),ee([]),de(!1),Ze(!1),K(null),Ee(null)},[]),Wt=o.useCallback(T=>{W(ue=>[...ue,{...T,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Sn=o.useCallback(()=>W([]),[]),Qn=o.useCallback(()=>De(T=>!T),[]),Ct=o.useMemo(()=>or.find(T=>T.id===qe)??or[0],[qe]),Ft=o.useCallback(()=>{Me(T=>{const ue=or.findIndex(X=>X.id===T);return or[(ue+1)%or.length].id})},[]),Ut=o.useCallback(async()=>{typeof g=="function"&&await g()},[g]),gt=o.useCallback(async T=>{var ge;b(!0),_(null);const ue=await cr(`/orgx/api/chat/threads/${encodeURIComponent(T)}`);if(!ue.ok||!((ge=ue.data)!=null&&ge.thread))return b(!1),_(lr(ue.error,"load")),null;const X=Np(ue.data.thread);return X?(j(X),b(!1),X):(b(!1),_("Thread detail payload was invalid."),null)},[]),Xt=o.useCallback(async(T,ue)=>{ue&&(Ge.current=ue),k(T),await gt(T),requestAnimationFrame(()=>{var X;return(X=Fe.current)==null?void 0:X.focus()})},[gt]),Jn=o.useCallback(()=>{var T;k(null),j(null),_(null),b(!1),(T=Ge.current)==null||T.focus()},[]),Yn=o.useCallback(T=>{window.setTimeout(()=>{ee(ue=>ue.map(X=>X.id===T?{...X,status:"indexing",updatedAt:new Date().toISOString()}:X))},80),window.setTimeout(()=>{ee(ue=>ue.map(X=>{var Et;if(X.id!==T)return X;const ge=((Et=X.mimeType)==null?void 0:Et.toLowerCase())==="application/x-msdownload"||X.name.toLowerCase().endsWith(".exe"),Xe=(X.sizeBytes??0)>25*1024*1024;return ge?{...X,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:Xe?{...X,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...X,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),xs=o.useCallback(T=>{if(!T||T.length===0)return;const ue=new Date().toISOString(),X=Array.from(T).map(ge=>({id:`draft_att_${crypto.randomUUID()}`,name:ge.name,mimeType:ge.type||null,sizeBytes:Number.isFinite(ge.size)?ge.size:null,status:"preparing",error:null,masked:!1,createdAt:ue,updatedAt:ue}));ee(ge=>ge.concat(X)),X.forEach(ge=>Yn(ge.id)),ls("chat_attachment_state_changed",{count:X.length,state:"preparing"})},[Yn]),_n=o.useCallback(T=>{ee(ue=>ue.map(X=>X.id===T?{...X,status:"preparing",error:null,updatedAt:new Date().toISOString()}:X)),Yn(T),ls("chat_attachment_state_changed",{state:"retry"})},[Yn]),Yt=o.useCallback(T=>{Le(ue=>ue===T?"":T),R(ue=>ue.filter(X=>X!==T)),oe(null),je("")},[]),mn=o.useCallback(T=>{R(ue=>ue.includes(T)?ue.filter(X=>X!==T):ue.concat(T))},[]),Ht=o.useCallback(()=>{Te(!1),C(""),oe(T=>T==="assignee"?null:"assignee"),je("")},[]),Pn=o.useCallback(()=>{Te(!1),C(""),oe(T=>T==="watcher"?null:"watcher"),je("")},[]),bn=o.useCallback(()=>{oe(null),je(""),Te(T=>!T),C("")},[]),Zn=o.useCallback(async(T,ue)=>{var Et;q(!0);const X=at.find(Qe=>Qe.id===ue)??null,ge=await cr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:T,project_id:r??void 0,initiativeId:(X==null?void 0:X.id)??null,initiativeTitle:(X==null?void 0:X.name)??null,relinked:!0})});if(q(!1),!ge.ok||!((Et=ge.data)!=null&&Et.thread)){_(ge.error??"Scope link failed.");return}const Xe=Xr(ge.data.thread);Xe&&v(Qe=>Ri(Qe,Xe)),await gt(T),await Ut(),ls("chat_thread_linked_initiative",{threadId:T,initiativeId:(X==null?void 0:X.id)??null})},[at,gt,Ut,r]),es=o.useCallback(async T=>{un(),await kt({text:T.prompt},{body:{threadId:T.thread.id,project_id:r??void 0,initiativeId:T.thread.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:T.thread.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,assigneeId:(he==null?void 0:he.id)??T.thread.assigneeId??void 0,assigneeName:(he==null?void 0:he.name)??T.thread.assigneeName??void 0,watcherIds:Ke.map(ue=>ue.id),watcherNames:Ke.map(ue=>ue.name)}}),await Ut(),await gt(T.thread.id)},[un,gt,Ut,he==null?void 0:he.id,he==null?void 0:he.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,Ke,kt,r]),Cn=o.useCallback(async()=>{var Xe,Et;const T=V.trim();if(!T)return K("Write a message before sending."),{thread:null,messageId:null};K(null),Ee(null),Z(!0);const ue=await cr("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:f??void 0,project_id:r??void 0,initiativeId:(Ae==null?void 0:Ae.id)??(x==null?void 0:x.initiativeId)??void 0,initiativeTitle:(Ae==null?void 0:Ae.name)??(x==null?void 0:x.initiativeTitle)??void 0,assigneeId:(he==null?void 0:he.id)??(x==null?void 0:x.assigneeId)??void 0,assigneeName:(he==null?void 0:he.name)??(x==null?void 0:x.assigneeName)??void 0,watcherIds:Ke.map(Qe=>Qe.id),watcherNames:Ke.map(Qe=>Qe.name),body:T,attachments:fe.map(Qe=>({id:Qe.id,name:Qe.name,mimeType:Qe.mimeType,sizeBytes:Qe.sizeBytes,status:Qe.status,error:Qe.error,masked:Qe.masked}))})});if(Z(!1),!ue.ok||!((Xe=ue.data)!=null&&Xe.thread))return K(lr(ue.error,"send")),ls("chat_message_send_failed",{reason:ue.error??"unknown"}),{thread:null,messageId:null};const X=Xr(ue.data.thread);if(!X)return K("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};v(Qe=>Ri(Qe,X)),Wt({role:"user",body:T}),qe!=="auto"&&he&&Wt({role:"system",body:`Routing to ${he.name} via ${Ct.label}`}),ls("chat_message_sent",{threadId:X.id,watcherCount:X.watcherIds.length}),await Ut();const ge=ue.data.message&&typeof ue.data.message.id=="string"?ue.data.message.id:((Et=X.latestMessage)==null?void 0:Et.id)??null;return k(X.id),await gt(X.id),es({thread:X,prompt:T}).catch(Qe=>{Wt({role:"error",body:lr(Qe instanceof Error?Qe.message:String(Qe??""),"send")})}),ht(),le("reviewing"),{thread:X,messageId:ge}},[x==null?void 0:x.assigneeId,x==null?void 0:x.assigneeName,x==null?void 0:x.initiativeId,x==null?void 0:x.initiativeTitle,f,V,fe,gt,Ut,ht,es,he==null?void 0:he.id,he==null?void 0:he.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,qe,Ct,Ke,r]),ts=o.useCallback(async(T,ue)=>{var jt,ut,On,ns,wt,Bn,vn;if(!ue){Wt({role:"error",body:"Send a message first to launch."});return}if(!he){Wt({role:"error",body:"Pick an agent with @ before launching."});return}if($e>0&&!Ce){de(!0),Wt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}xe(!0),K(null),Ee(null);const X=await cr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:he.id,message:V.trim().length>0?V.trim():T.lastSnippet??T.title,initiativeId:T.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:T.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,workstreamId:T.workstreamId??void 0,taskId:T.taskId??void 0,provider:qe!=="auto"?qe:void 0})}),ge=((jt=X.data)==null?void 0:jt.sessionId)??((ut=X.data)==null?void 0:ut.runId)??null,Xe=X.ok&&ge?"running":X.ok?"queued":"blocked",Et=X.ok?null:X.error??"Launch request failed before queueing.",Qe=await cr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:T.id,messageId:ue,assigneeId:he.id,assigneeName:he.name,watcherIds:Ke.map(At=>At.id),watcherNames:Ke.map(At=>At.name),executionMode:"local_queue",provider:((On=X.data)==null?void 0:On.provider)??(qe!=="auto"?qe:"openclaw"),runId:ge??void 0,status:Xe,blockedReason:Et??void 0,warnings:$e>0?[`${$e} attachment(s) were not ready at launch.`]:[]})});if(xe(!1),Ze(!1),de(!1),!Qe.ok||!((ns=Qe.data)!=null&&ns.thread)){K(Qe.error?lr(Qe.error,"launch"):Et??"Launch state could not be persisted. Message remained saved."),ls("chat_launch_failed",{threadId:T.id,reason:Qe.error??Et??"unknown"});return}const ys=Xr(Qe.data.thread);if(ys&&v(At=>Ri(At,ys)),await gt(T.id),await Ut(),!X.ok){K(`Launch blocked: ${Et??"Set assignee and retry."}`),ls("chat_launch_blocked",{threadId:T.id,reason:Et??"unknown"});return}const Ot=((wt=X.data)==null?void 0:wt.provider)==="anthropic"?"Claude Code":((Bn=X.data)==null?void 0:Bn.provider)==="openai"?"Codex":Ct.shortLabel,Kt=(vn=X.data)!=null&&vn.model?` (${X.data.model})`:"";Ee(ge?`Launch started via ${Ot}${Kt}. Thread timeline now tracks execution state.`:`Launch queued locally via ${Ot}. Run starts when a worker is available.`),ls(ge?"chat_launch_started":"chat_launch_queued",{threadId:T.id,runId:ge,assigneeId:he.id})},[V,Ce,gt,Ut,he,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,qe,Ct,Ke,$e]),It=o.useCallback(async()=>{var ue;const T=await Cn();(ue=T.thread)!=null&&ue.id&&await Xt(T.thread.id)},[Xt,Cn]),Mn=o.useCallback(async()=>{const T=await Cn();T.thread&&(await ts(T.thread,T.messageId),await Xt(T.thread.id))},[ts,Xt,Cn]),wn=o.useCallback(async()=>{if(Se){if(he){await Mn();return}await It()}},[Se,Mn,It,he]),Tn=o.useMemo(()=>({threads:y,activeThreadId:f,activeThread:x,activeThreadSummary:Re,displayedThreads:Ne,composerMode:U,draft:V,draftAttachments:fe,sending:H,launching:ce,composerError:we,composerNotice:Ie,selectedAssigneeId:re,selectedAssignee:he,selectedWatcherIds:ne,selectedWatchers:Ke,selectedInitiativeId:J,selectedInitiative:Ae,agentOptions:it,quickAssigneeOptions:B,initiativeOptions:at,agentPickerMode:Y,agentPickerQuery:ve,filteredAgentOptions:Pe,scopePickerOpen:te,scopePickerQuery:pe,filteredInitiativeOptions:z,panelLoading:w,panelError:h,scopeSaving:M,launchWarningOpen:ie,launchWarningAccepted:Ce,unresolvedAttachmentCount:$e,canSend:Se,composerGuidance:Ve,primaryActionLabel:lt,guidanceStatus:Jt,guidancePreview:An,guidanceError:Gt??null,inlineMessages:O,threadSidebarOpen:se,workspaceId:r,selectedProvider:qe,selectedProviderDef:Ct}),[y,f,x,Re,Ne,U,V,fe,H,ce,we,Ie,re,he,ne,Ke,J,Ae,it,B,at,Y,ve,Pe,te,pe,z,w,h,M,ie,Ce,$e,Se,Ve,lt,Jt,An,Gt,O,se,r,qe,Ct]),Zt=o.useMemo(()=>({setDraft:be,setComposerMode:le,setDraftAttachments:ee,selectAssignee:Yt,toggleWatcher:mn,setSelectedInitiativeId:P,toggleAssigneePicker:Ht,toggleWatcherPicker:Pn,toggleScopePicker:bn,setAgentPickerQuery:je,setScopePickerQuery:C,setAgentPickerMode:oe,setScopePickerOpen:Te,handlePrimaryAction:wn,handleFilesAdded:xs,handleRetryAttachment:_n,openThreadPanel:Xt,closeThreadPanel:Jn,loadThreadDetail:gt,applyScopeLink:Zn,resetComposer:ht,setComposerError:K,setComposerNotice:Ee,setLaunchWarningAccepted:Ze,pushInlineMessage:Wt,clearInlineMessages:Sn,toggleThreadSidebar:Qn,setSelectedProvider:Me,cycleProvider:Ft,fileInputRef:Je,panelHeadingRef:Fe,composerShellRef:He}),[Yt,mn,Ht,Pn,bn,wn,xs,_n,Xt,Jn,gt,Zn,ht,Wt,Sn,Qn,Ft]);return n.jsx(wl.Provider,{value:Tn,children:n.jsx(vl.Provider,{value:Zt,children:e})})}const _p={type:"spring",stiffness:500,damping:35,mass:.5};function Cp({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=Xn(),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:me("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(bt,{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:_p,className:me("flex",d.role==="user"?"justify-end":"justify-start",d.role==="system"&&"justify-center"),children:d.role==="system"?n.jsx("p",{className:"text-micro italic text-muted",children:d.body}):n.jsxs("div",{className:me("max-w-[85%] rounded-2xl px-3 py-2",d.role==="user"&&"bg-lime/[0.1]",d.role==="agent"&&"bg-white/[0.05]",d.role==="error"&&"bg-rose-400/[0.1]"),children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:me("text-micro font-medium",d.role==="user"&&"text-[#E1FFB2]/80",d.role==="agent"&&"text-secondary",d.role==="error"&&"text-rose-200"),children:d.role==="user"?"You":d.role==="error"?"Error":"Agent"}),n.jsx("time",{className:"text-[10px] text-muted/60",dateTime:d.timestamp,children:Mt(d.timestamp)})]}),n.jsxs("p",{className:me("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===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 yo({open:e,onClose:t}){const s=Xn(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:g}=xa(),{openThreadPanel:y,closeThreadPanel:v,loadThreadDetail:f,applyScopeLink:k,panelHeadingRef:x}=ya(),j=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,w=o.useCallback((h,_)=>{y(h,_)},[y]),b=o.useCallback(()=>{v(),t()},[v,t]);return n.jsx(bt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ye.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:b,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:sn.durationEntrance/1e3,ease:sn.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:b,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread drawer",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:me("grid min-h-0 flex-1 overflow-hidden",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(h=>n.jsxs("button",{type:"button",onClick:_=>w(h.id,_.currentTarget),className:me("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===h.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:h.lastSnippet?`"${h.lastSnippet.length>40?h.lastSnippet.slice(0,40)+"...":h.lastSnippet}"`:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:Mt(h.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",h.assigneeName]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(h.status)),children:si(h.status)})]})]},h.id))})}),n.jsx(bt,{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:sn.durationStandard/1e3,ease:sn.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:x,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:me("rounded-full border px-2 py-0.5 text-micro font-semibold",Vs((c==null?void 0:c.status)??"message_only")),children:si((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}),j&&n.jsx("button",{type:"button",onClick:()=>void f(j),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):a&&a.messages.length>0?n.jsx("div",{className:"space-y-2",children:a.messages.map(h=>n.jsx("article",{className:me("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:me("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:h.senderName??yl(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:Mt(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),a&&a.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[a.launches.length," launch",a.launches.length===1?"":"es"]}),a.launches.slice(0,2).map(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(bl(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:Mt(h.requestedAt)})]},h.id))]})]})})]})]})]})})}function bo(){const e=Xn(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=xa(),{openThreadPanel:g,closeThreadPanel:y,loadThreadDetail:v,applyScopeLink:f,setComposerMode:k,toggleThreadSidebar:x,panelHeadingRef:j}=ya(),w=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,b=o.useCallback(()=>{x()},[x]);return u?n.jsx(bt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ye.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:b,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:sn.durationEntrance/1e3,ease:sn.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:b,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:xo,transition:go,onClick:()=>{b(),k("focused"),requestAnimationFrame(()=>{const h=document.getElementById("chat-dock-input");h instanceof HTMLTextAreaElement&&h.focus()})},className:"mt-2 inline-flex min-h-[34px] items-center rounded-full border border-lime/30 bg-lime/[0.12] px-2.5 text-micro font-semibold text-[#E1FFB2] hover:bg-lime/[0.18]",children:"Start thread"})]}):n.jsx("div",{className:"space-y-1.5",children:t.map((h,_)=>n.jsxs(ye.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:go,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:xo,onClick:U=>void g(h.id,U.currentTarget),className:me("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===h.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:Mt(h.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:h.lastSnippet??h.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx($t,{name:h.assigneeName,hint:h.assigneeName,size:"xs"}),n.jsx("span",{children:h.assigneeName})]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(h.status)),children:si(h.status)})]})]},h.id))})}),n.jsx(bt,{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:sn.durationStandard/1e3,ease:sn.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:j,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:me("rounded-full border px-2 py-0.5 text-micro font-semibold",Vs((i==null?void 0:i.status)??"message_only")),children:si((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}),w&&n.jsx("button",{type:"button",onClick:()=>void v(w),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):r&&r.messages.length>0?n.jsx("div",{className:"space-y-2",children:r.messages.map(h=>n.jsx("article",{className:me("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:me("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:h.senderName??yl(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:Mt(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),r&&r.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[r.launches.length," launch",r.launches.length===1?"":"es"]}),r.launches.slice(0,2).map(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:me("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(bl(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:Mt(h.requestedAt)})]},h.id))]})]})})]},"sidebar-panel")]})}):null}const Mp={type:"spring",stiffness:500,damping:30,mass:.5};function Tp({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=Xn(),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 g=s.toLowerCase();return u.name.toLowerCase().includes(g)||u.handle.toLowerCase().includes(g)||u.domain.toLowerCase().includes(g)||u.role.toLowerCase().includes(g)}):t;if(!e||l.length===0)return null;const d=l.slice(0,6);return n.jsx(bt,{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:me("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref:c,className:"space-y-px",children:d.map((u,g)=>{const y=g===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:v=>v.preventDefault(),className:me("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($t,{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 Ep={type:"spring",stiffness:500,damping:30,mass:.5};function Lp({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=Xn(),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(bt,{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:Ep,className:me("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref: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:me("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,g)=>{const y=g+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:v=>v.preventDefault(),className:me("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",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 Dp({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:c,onQueryChange:l,onSelectAssignee:d,onToggleWatcher:u,onClose:g,onSwitchMode:y,anchorRef:v}){const f=Xn();return n.jsx(bt,{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:sn.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:me("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>y("watcher"),className:me("rounded-full px-2 py-0.5 text-micro",t==="watcher"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Watchers"})]}),n.jsx("button",{type:"button",onClick:g,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 x=a===k.id;return n.jsx("button",{type:"button",onClick:()=>d(k.id),title:k.name,className:me("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",x?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":x,"aria-label":`Select ${k.name} as assignee`,children:n.jsx($t,{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 x=a===k.id,j=c.includes(k.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(k.id);return}x||u(k.id)},className:me("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",x?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":j?"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($t,{name:k.name,hint:k.name,size:"xs"}),n.jsx("span",{children:k.name})]}),n.jsx("span",{className:"text-micro",children:x?"Assignee":j?"Watcher":"Select"})]},k.id)})})]})})}const wo=24,vo=200;function ko(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 Rp(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 jo({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 ra="orgx-chat-dock-collapsed";function $p(){try{return localStorage.getItem(ra)==="1"}catch{return!1}}function Fp(){const e=xa(),t=ya(),s=Xn(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState($p),l=o.useCallback(()=>{c(B=>{const Pe=!B;try{localStorage.setItem(ra,Pe?"1":"0")}catch{}return Pe})},[]),[d,u]=o.useState(!1),[g,y]=o.useState(!1),v=o.useRef(null),[f,k]=o.useState(!1),[x,j]=o.useState(""),[w,b]=o.useState(0),[h,_]=o.useState(-1),[U,le]=o.useState(!1),[V,be]=o.useState(""),[H,Z]=o.useState(0),[ce,xe]=o.useState(-1),{composerMode:we,draft:K,draftAttachments:Ie,sending:Ee,launching:fe,selectedAssigneeId:ee,selectedAssignee:re,selectedWatcherIds:Le,selectedInitiative:ne,agentOptions:R,quickAssigneeOptions:J,agentPickerMode:P,agentPickerQuery:Y,filteredAgentOptions:oe,initiativeOptions:ve,canSend:je,activeThreadId:te,guidanceStatus:Te,inlineMessages:pe,displayedThreads:C,launchWarningOpen:O,launchWarningAccepted:W,selectedProvider:se,selectedProviderDef:De}=e,qe=K.trim(),Me=pe.length>0;qe.length>0;const M=o.useCallback(()=>{const B=r.current;if(!B)return;B.style.height="0";const Pe=Math.min(Math.max(B.scrollHeight,wo),vo);B.style.height=`${Pe}px`},[]);o.useLayoutEffect(()=>{M()},[K,M]);const q=o.useMemo(()=>{if(!f)return R;const B=x.toLowerCase();return B?R.filter(Pe=>Pe.name.toLowerCase().includes(B)||Pe.handle.toLowerCase().includes(B)||Pe.domain.toLowerCase().includes(B)||Pe.role.toLowerCase().includes(B)):R},[R,f,x]),ie=o.useMemo(()=>{if(!U)return ve;const B=V.toLowerCase();return B?ve.filter(Pe=>Pe.name.toLowerCase().includes(B)):ve},[ve,U,V]);o.useEffect(()=>{if(v.current&&clearTimeout(v.current),pe.length<=2){y(!1);return}return y(!1),v.current=window.setTimeout(()=>{y(!0)},5e3),()=>{v.current&&clearTimeout(v.current)}},[pe.length]),o.useEffect(()=>{const B=Pe=>{if((Pe.metaKey||Pe.ctrlKey)&&Pe.key==="k"){if(Pe.preventDefault(),a){c(!1);try{localStorage.setItem(ra,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var z;return(z=r.current)==null?void 0:z.focus()})}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t,a]);const de=o.useCallback(()=>{we==="resting"&&t.setComposerMode("focused")},[we,t]),Ce=o.useCallback(()=>{window.setTimeout(()=>{qe.length===0&&!Me&&!f&&!U&&Ie.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),k(!1),le(!1))},100)},[qe,Me,f,U,Ie.length,t]),Ze=o.useCallback(B=>{const Pe=B.target.value,z=B.target.selectionStart??Pe.length;t.setDraft(Pe),(we==="resting"||we==="focused")&&t.setComposerMode("composing");const Q=Pe.slice(0,z),Ne=Q.match(/@(\w*)$/);if(Ne){k(!0),j(Ne[1]),b(0),_(z-Ne[0].length),le(!1);return}const Re=Q.match(/#(\w*)$/);if(Re){le(!0),be(Re[1]),Z(0),xe(z-Re[0].length),k(!1);return}f&&k(!1),U&&le(!1)},[we,t,f,U]),Je=o.useCallback(B=>{var Ne;const Pe=K.slice(0,h),z=K.slice(((Ne=r.current)==null?void 0:Ne.selectionStart)??K.length),Q=`${Pe}@${B.name} ${z}`;t.setDraft(Q),t.selectAssignee(B.id),k(!1),j(""),requestAnimationFrame(()=>{if(r.current){const Re=Pe.length+B.name.length+2;r.current.setSelectionRange(Re,Re),r.current.focus()}})},[K,h,t]),Fe=o.useCallback(B=>{var Q;const Pe=K.slice(0,ce),z=K.slice(((Q=r.current)==null?void 0:Q.selectionStart)??K.length);if(B){const Ne=`${Pe}#${B.name} ${z}`;t.setDraft(Ne),t.setSelectedInitiativeId(B.id),requestAnimationFrame(()=>{if(r.current){const Re=Pe.length+B.name.length+2;r.current.setSelectionRange(Re,Re),r.current.focus()}})}else{const Ne=`${Pe}${z}`;t.setDraft(Ne),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange(Pe.length,Pe.length),r.current.focus())})}le(!1),be("")},[K,ce,t]),Ge=o.useCallback(B=>{if(f&&q.length>0){if(B.key==="ArrowDown"){B.preventDefault(),b(Pe=>(Pe+1)%q.length);return}if(B.key==="ArrowUp"){B.preventDefault(),b(Pe=>(Pe-1+q.length)%q.length);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),Je(q[w]);return}if(B.key==="Escape"){B.preventDefault(),k(!1);return}}if(U){const Pe=ie.length+1;if(B.key==="ArrowDown"){B.preventDefault(),Z(z=>(z+1)%Pe);return}if(B.key==="ArrowUp"){B.preventDefault(),Z(z=>(z-1+Pe)%Pe);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),Fe(H===0?null:ie[H-1]);return}if(B.key==="Escape"){B.preventDefault(),le(!1);return}}if(B.key==="Enter"&&!B.shiftKey){B.preventDefault(),t.handlePrimaryAction();return}B.key==="Escape"&&(B.preventDefault(),P?t.setAgentPickerMode(null):Me?t.clearInlineMessages():(t.setComposerMode("resting"),B.target.blur()))},[t,P,Me,f,q,w,Je,U,ie,H,Fe]),He=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),ft=Ee||fe?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"})]}),it=(we==="reviewing"||Me)&&pe.length>0,at=Te==="submitted"||Te==="streaming",he=o.useRef(pe.length),[Ke,Ae]=o.useState(0);return o.useEffect(()=>{if(!a){he.current=pe.length,Ae(0);return}const B=pe.length-he.current;B>0&&Ae(B)},[a,pe.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(yo,{open:d,onClose:()=>u(!1)}),n.jsx(bo,{}),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 B;return(B=r.current)==null?void 0:B.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:me("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx(bt,{children:Ke>0&&n.jsx(ye.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:me("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:Ke>9?"9+":Ke},"unread")}),te&&Ke===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(yo,{open:d,onClose:()=>u(!1)}),n.jsx(bo,{}),n.jsxs("div",{ref:B=>{t.composerShellRef.current=B},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(bt,{children:O&&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:W,onChange:B=>t.setLaunchWarningAccepted(B.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(Dp,{open:P!==null,mode:P??"assignee",agents:oe,quickAgents:J,query:Y,selectedAssigneeId:ee,selectedWatcherIds:Le,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":we,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:sn.durationEntrance/1e3,ease:sn.easingEntrance},className:me("group/dock relative rounded-[22px] border border-white/[0.12] bg-[#0A0E16]/80 px-3 py-2.5 backdrop-blur-xl","shadow-[inset_0_1px_0_rgba(255,255,255,0.035),0_14px_34px_rgba(0,0,0,0.36)]","transition-[border-color] duration-200",we!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:l,className:me("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:B=>{t.fileInputRef.current=B},type:"file",multiple:!0,className:"hidden",onChange:B=>{t.handleFilesAdded(B.target.files),B.currentTarget.value=""}}),n.jsx(bt,{children:it&&n.jsx(Cp,{messages:pe,isStreaming:at,collapsed:g,onClick:He})}),n.jsxs("div",{className:"relative",children:[n.jsx(Tp,{open:f,agents:q,query:x,activeIndex:w,anchorRect:null,onSelect:Je,onClose:()=>k(!1)}),n.jsx(Lp,{open:U,initiatives:ie,query:V,activeIndex:H,onSelect:Fe,onClose:()=>le(!1)})]}),n.jsx(bt,{initial:!1,children:Ie.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:Ie.map(B=>n.jsxs("div",{className:me("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",B.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:`${ko(B.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:ko(B.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:B.name}),n.jsxs("p",{className:"text-micro text-muted",children:[Rp(B.mimeType,B.name),B.sizeBytes?` · ${yp(B.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Pe=>Pe.filter(z=>z.id!==B.id)),className:me("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${B.name}`,children:"×"}),B.status!=="ready"&&B.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]"})}),B.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(B.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"})]},B.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var B;return(B=t.fileInputRef.current)==null?void 0:B.click()},className:me("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(ye.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:me("mb-0.5 inline-flex h-7 flex-shrink-0 items-center gap-1.5 rounded-full px-2","border text-micro font-medium","transition-all duration-200",se==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":se==="openai"?"border-emerald-400/30 bg-emerald-400/[0.08] text-emerald-300":"border-white/[0.12] bg-white/[0.04] text-muted"),title:`Provider: ${De.label}. Click to switch.`,"aria-label":`Current provider: ${De.label}. Click to cycle.`,children:[n.jsx(jo,{icon:De.icon}),n.jsx("span",{children:De.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:K,onFocus:de,onBlur:Ce,onChange:Ze,onKeyDown:Ge,placeholder:"Ask anything",rows:1,className:me("w-full resize-none border-none bg-transparent py-1 text-[13px] leading-[22px] text-primary","placeholder:text-muted/60 focus:outline-none"),style:{minHeight:wo,maxHeight:vo,overflowY:"auto"},"aria-expanded":we!=="resting"})]}),C.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:me("mb-0.5 inline-flex h-7 min-w-[28px] flex-shrink-0 items-center justify-center gap-1 rounded-full px-1.5","text-micro text-muted transition-colors duration-150","hover:bg-white/[0.06] hover:text-secondary"),"aria-label":`${C.length} thread${C.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"})}),C.length]}),n.jsx(ye.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!je,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:me("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",je?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:re?`Send to ${re.name} via ${De.shortLabel}`:`Send via ${De.shortLabel}`,"aria-label":re?`Send to ${re.name} via ${De.shortLabel}`:`Send message via ${De.shortLabel}`,children:ft})]}),n.jsx(bt,{children:(re||ne)&&we!=="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:[re&&n.jsxs("button",{ref:B=>{i.current=B},type:"button",onClick:t.toggleWatcherPicker,className:me("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-micro","text-[#E1FFB2]/80 transition-colors duration-150 hover:bg-lime/[0.08]"),children:[n.jsx($t,{name:re.name,hint:re.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",re.name]}),re.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),ne&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",ne.name]}),se!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:De.accent},children:[n.jsx(jo,{icon:De.icon}),De.shortLabel]})]})})]})]})]})}const $i=50,Pp=50,dr=20,No=3600,Io=12e3,$r={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"};function Op(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 ms(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Pr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Fi(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function So(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Ts(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ba(e){if(!e)return;let t={...e},s=Ts(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=Ts(s.metadata),r+=1;return t}function Nt(e){const t=Ts(e==null?void 0:e.metadata);return ba(t)}function Bp(e){const t=ba(e);if(!t)return"";const s=[];for(const[r,i]of Object.entries(t))typeof i=="string"&&(r.toLowerCase().includes("type")||r.toLowerCase().includes("kind")||r.toLowerCase().includes("summary")||r.toLowerCase().includes("message")||r.toLowerCase().includes("artifact")||r.toLowerCase().includes("decision")||r.toLowerCase().includes("run")||r.toLowerCase().includes("title")||r.toLowerCase().includes("task")||r.toLowerCase().includes("workstream")||r.toLowerCase().includes("milestone"))&&s.push(i);return s.join(" ")}function ia(e){if(e.runId)return e.runId;const t=Nt(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 fr(e){const t=Nt(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 _o(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const qp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zp=/^[0-9a-f]{20,}$/i,kl=/^\d+$/,jl=/^(user|usr|clerk)_[a-z0-9]+$/i;function nn(e){if(!e)return null;const t=e.trim();return!t||qp.test(t)||zp.test(t)||kl.test(t)||jl.test(t)?null:t}const Wp=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Up(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Wp.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=nn(_o(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=nn(_o(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Hp(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 Mo(e){const t=Nt(e),s=fr(e),r=ai(e),i=nn(s.agentId),a=nn(s.agentName),c=nn(e.requesterAgentId??null),l=nn(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,g=nn(e.executorAgentId??null),y=nn(e.executorAgentName??null),f=(g||y?{id:g,name:y,label:y??g??"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?Hp(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:nn(e.agentName??null)??nn(e.agentId??null)??"OrgX",subtitle:nn(e.agentName??null)??nn(e.agentId??null)??"OrgX"}}function Pi(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function ur(e){const t=Nt(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 Oi(e){const t=Nt(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 To=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 Or(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Kp(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 Us(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 Vp(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 Gp(e){const t=Nt(e),s=Or(e.kind)??Or(t==null?void 0:t.activity_bucket)??Or(t==null?void 0:t.activityBucket)??Or(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=Vp(t),i=e.decisionRequired===!0||Kp(t,["decision_required","decisionRequired"])===!0,a=Us(t,["artifacts","artifact_count","artifactCount"])??0,c=Us(t,["decisions","decision_count","decisionCount"])??0,l=Us(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Us(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 g=Nn(ct(t,["stop_reason","stopReason"])??"");if(g==="blocked"||g==="error")return"decision"}return r&&To.has(r)?To.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 ri(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 Xp(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 Qp(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 Bi(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function qi(e){return e==="completed"?E.lime:e==="needs_input"?E.amber:e==="issue"?E.red:E.teal}function Jp(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 Eo(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function ps(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 Hn(e){const t=ps(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=ps(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function Yp(e){const t=ps(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 Zp(e,t){for(const s of t){const r=Yp(e[s]);if(r!==null)return r}return null}function Br(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 Nl(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Br(e,["blocking_decision_ids","blockingDecisionIds"]),s=Br(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=Br(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=Br(l,["id","decision_id","decisionId"]),u=l.blocking!==!1;for(const g of d)i.add(g),u?t.includes(g)||t.push(g):s.includes(g)||s.push(g)}return{decisionIds:Array.from(i),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function Il(e){if(!e)return null;const t=Nt(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=fr(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,g=Array.isArray(u)?u.filter(W=>typeof W=="string"&&W.trim().length>0):[],y=af(g),v=t.task_ids??t.taskIds,f=Array.isArray(v)?v.filter(W=>typeof W=="string"&&W.trim().length>0):[],k=t.milestone_ids??t.milestoneIds,x=Array.isArray(k)?k.filter(W=>typeof W=="string"&&W.trim().length>0):[],j=ct(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),w=ct(t,["initiative_title","initiativeTitle"]),b=ct(t,["initiative_status","initiativeStatus"]),h=ur(e),_=ct(t,["workstream_title","workstreamTitle"]),U=ct(t,["workstream_status","workstreamStatus"]),le=ct(t,["task_title","taskTitle"]),V=ct(t,["milestone_title","milestoneTitle"]),be=ct(t,["domain"]),H=ct(t,["phase","slice_phase","slicePhase"]),Z=ct(t,["next_step","nextStep"]),ce=Zp(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),xe=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,we=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,K=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,Ie=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,Ee=typeof t.error=="string"?t.error:null,fe=Hn(t.artifacts??t.artifact_count??t.artifactCount),ee=Hn(t.decisions??t.decision_count??t.decisionCount),re=Nl(t),Le=t.decisions_needed??t.decisionsNeeded;let ne=Hn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),R=Hn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((ne===null||R===null)&&Array.isArray(Le)){let W=0,se=0;for(const De of Le){if(!De||typeof De!="object"||Array.isArray(De))continue;De.blocking===!1?se+=1:W+=1}ne===null&&(ne=W),R===null&&(R=se)}ne===null&&ee!==null&&e.decisionRequired===!0&&(ne=ee>0?ee:1),R===null&&ee!==null&&ne!==null&&(R=Math.max(0,ee-ne)),ne===null&&ee!==null&&R!==null&&(ne=Math.max(0,ee-R));const J=Hn(t.status_updates_applied??t.statusUpdatesApplied),P=Hn(t.task_updates??t.taskUpdates),Y=Hn(t.milestone_updates??t.milestoneUpdates),oe=J??(P!==null||Y!==null?(P??0)+(Y??0):null),ve=Hn(t.status_updates_buffered??t.statusUpdatesBuffered),je=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,te=ps(t.token_budget??t.tokenBudget),Te=ps(t.tokens_used??t.tokensUsed),pe=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),C=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,O=y&&!a.agentName?null:pe;return{event:s,agentId:O,agentName:C,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:j,domain:be,phase:H,progressPct:ce,nextStep:Z,requiredSkills:g,initiativeStatus:b,initiativeTitle:w,workstreamId:h,workstreamStatus:U,workstreamTitle:_,taskTitle:le,milestoneTitle:V,taskIds:f,milestoneIds:x,parsedStatus:xe,hasOutput:we,artifacts:fe,decisions:ee,blockingDecisions:ne,nonBlockingDecisions:R,decisionIds:re.decisionIds,blockingDecisionIds:re.blockingDecisionIds,nonBlockingDecisionIds:re.nonBlockingDecisionIds,statusUpdatesApplied:oe,statusUpdatesBuffered:ve,stopReason:je,tokenBudget:te,tokensUsed:Te,logPath:K,outputPath:Ie,error:Ee}}function zi(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function ef(e){const t=ba(e);if(!t)return null;const s=t,r=s.orgx_provenance,i=r&&typeof r=="object"&&!Array.isArray(r)?r:null,a=i!=null&&i.skill_pack&&typeof i.skill_pack=="object"&&!Array.isArray(i.skill_pack)?i.skill_pack:null,c=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(i==null?void 0:i.plugin_version)=="string"?i.plugin_version:null),l=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),g=(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,v=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,x=typeof s.model=="string"?s.model:null,j=typeof s.domain=="string"?s.domain:null,w=s.required_skills??s.requiredSkills,b=Array.isArray(w)?w.filter(_=>typeof _=="string"&&_.trim().length>0):[];return!!c||!!(l||d||u)||!!y||!!(f||k||x||j)||b.length>0?{pluginVersion:c,skillPack:l||d||u||g?{name:l,version:d,checksum:u,source:g}:null,kickoffContextHash:y,kickoffContextSource:v,modelTier:f,provider:k,model:x,domain:j,requiredSkills:b}:null}function Al(e){if(!e)return null;const t=Nt(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 tf(e){const t=Nt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=Al(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 nf(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 Sl(e){const t=Nt(e);if(!t)return[];const s=[],r=new Set,i=(c,l)=>{if(typeof l!="string")return;const d=l.trim();if(!d||!nf(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,g]of Object.entries(c)){const y=l?`${l}.${u}`:u,v=u.toLowerCase();if(v.includes("path")||v==="url"||v==="uri"||v.endsWith("url")||v.endsWith("_file")||v.endsWith("file")||v.includes("artifact"))if(Array.isArray(g))for(const k of g)i(y,k);else i(y,g);g&&typeof g=="object"&&!Array.isArray(g)&&a(g,y,d+1)}};return a(t),s}function ct(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 sf(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 rf(e,t){if(!e)return null;const s=Nt(e);if(!s)return null;const r=ct(s,["event","event_name","eventName"]),i=Ts(s.spawn_guard),a=Ts(i==null?void 0:i.checks),c=Ts((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=ct(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=sf(l),u=ps(c==null?void 0:c.current)??d.domainCurrent,g=ps(c==null?void 0:c.max)??d.domainMax,y=d.totalCurrent,v=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:ct(s,["domain"])??ct(i,["domain","task_domain"]),modelTier:ct(s,["spawn_guard_model_tier","model_tier"])??ct(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:g,totalCurrent:y,totalMax:v,retryAt:ct(s,["next_retry_at","nextRetryAt"]),retryInMs:ps(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:k}}function af(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 of(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 Wi(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&&of(r)?a:r??a;if(c)return pr(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"?pr(i):mr.test(i)||lf.test(i)||kl.test(i)||jl.test(i)?"OrgX":pr(i)}const mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lf=/^[0-9a-f]{20,}$/i,cf=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function ii(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(cf)??[]){const l=c.trim().toLowerCase();mr.test(l)&&t.add(l)}typeof e.runId=="string"&&mr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=Nt(e);if(!s)return t;const r=["run_id","runId","last_run_id","lastRunId","active_run_id","activeRunId","slice_id","sliceId","worker_run_id","workerRunId","correlation_id","correlationId","initiative_id","initiativeId","workstream_id","workstreamId","task_id","taskId","milestone_id","milestoneId","decision_id","decisionId","outbox_event_id","outboxEventId"],i=["task_ids","taskIds","milestone_ids","milestoneIds","decision_ids","decisionIds","blocking_decision_ids","blockingDecisionIds","non_blocking_decision_ids","nonBlockingDecisionIds","allowed_workstream_ids","allowedWorkstreamIds"];for(const a of r){const c=s[a];if(typeof c=="string"){const l=c.trim().toLowerCase();mr.test(l)&&t.add(l)}}for(const a of i){const c=s[a];if(Array.isArray(c))for(const l of c){if(typeof l!="string")continue;const d=l.trim().toLowerCase();mr.test(d)&&t.add(d)}}return t}function df(e){if(!e)return[];const t=Nt(e);return Nl(t).decisionIds}function uf(e,t,s){if(!e)return[];const r=Nt(e),i=ct(r,["workstream_id","workstreamId"]),a=ct(r,["initiative_id","initiativeId"]),c=ii(e);if(!i&&!a&&c.size===0)return[];const l=ms(e.timestamp),d=[];for(const v of t){if(v.id===e.id)continue;const f=Nt(v);if(!f)continue;const k=ct(f,["workstream_id","workstreamId"]),x=ct(f,["initiative_id","initiativeId"]),j=ii(v),w=c.size>0&&Array.from(c).some(V=>j.has(V)),b=!!i&&!!k&&i===k;if(!w&&!b&&!(!!a&&!!x&&a===x))continue;const _=Sl(v).filter(V=>!s.has(V.path));if(_.length===0)continue;const U=Math.abs(ms(v.timestamp)-l);if(!w&&U>7200*1e3)continue;const le=w?0:b?1:2;!w&&U>1200*1e3||d.push({priority:le,delta:U,evidence:_})}if(d.length===0)return[];d.sort((v,f)=>v.priority!==f.priority?v.priority-f.priority:v.delta-f.delta);const u=[],g=new Set(s),y=d[0].priority;for(const v of d){if(v.priority!==y)break;for(const f of v.evidence)if(!g.has(f.path)&&(g.add(f.path),u.push({key:`related.${f.key}`,path:f.path}),u.length>=8))return u}return u}function mf(e,t){if(!e)return null;const s=Nt(e),r=ct(s,["workstream_id","workstreamId"]),i=ct(s,["initiative_id","initiativeId"]),a=ii(e);if(!r&&!i&&a.size===0)return null;const c=ms(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const g=Il(u);if(!g)continue;const y=Nt(u);if(!y)continue;const v=ct(y,["workstream_id","workstreamId"]),f=ct(y,["initiative_id","initiativeId"]),k=ii(u),x=a.size>0&&Array.from(a).some(U=>k.has(U)),j=!!r&&!!v&&r===v;if(!x&&!j&&!(!!i&&!!f&&i===f))continue;const b=Math.abs(ms(u.timestamp)-c);if(!x&&b>1200*1e3)continue;const h=x?"shared_id":j?"workstream":"initiative",_=h==="shared_id"?0:h==="workstream"?1:2;l.push({priority:_,delta:b,relation:h,detail:g})}if(l.length===0)return null;l.sort((u,g)=>u.priority!==g.priority?u.priority-g.priority:u.delta-g.delta);const d=l[0];return{detail:d.detail,relation:d.relation}}function Nn(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function di(e){const t=Nn(e);return["done","complete","completed","stopped","success"].includes(t)}function pf(e){const t=Nn(e.parsedStatus),s=Nn(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":di(t)||e.stopReason==="completed"?"positive":"neutral"}function ff(e){if(di(e.parsedStatus)||e.stopReason==="completed")return 100;const t=Nn(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 _l(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function hf(e,t){if(!e&&t===null)return null;const s=e?pf(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=_l(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=ff(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 gf(e,t,s,r=null){var w;const i=Nt(e),a=Nn(ct(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=Nn(e.state??e.phase??e.kind??e.type),l=Nn((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=Nn((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=ct(i,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,g=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,g):0)),v=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,g-y)),f=e.decisionRequired===!0||e.type==="decision_requested"||y>0||l==="needs_decision"&&v===0,k=e.type==="run_completed"||e.type==="milestone_completed"||di(l)||d==="completed",x=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),j=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:Rt(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:Rt(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:Rt(e.title)??"Autopilot stopped because the current dispatch scope is complete.",hint:null,tone:"positive"};if(d==="stopped")return{label:"Stopped",summary:Rt(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:Rt(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:Rt(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 b=String((i==null?void 0:i.old_state)??""),h=String((i==null?void 0:i.new_state)??""),_=String((i==null?void 0:i.reason)??"");return h==="running"?{label:"Autopilot activated",summary:`State changed from ${b} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:h==="blocked"||h==="error"?{label:h==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${b} to ${h}${_?`: ${_}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${b} → ${h}${_?` (${_})`:""}.`,hint:null,tone:"neutral"}}if(x)return{label:"Rate limited",summary:u?Rt(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(j)return{label:"Spawn guard blocked",summary:u?Rt(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:v>0?"Completed + follow-up":"Completed",summary:v>0?`Execution completed. ${v} non-blocking decision${v===1?"":"s"} were logged for optional follow-up.`:r.sentence,hint:r.nextAction,tone:"positive"};if(r.status==="failed")return{label:"Failed",summary:u?Rt(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const b=f||(((w=r.nextAction)==null?void 0:w.toLowerCase().includes("decision"))??!1);return{label:b?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(b?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:b?"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?Rt(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&&v>0?{label:"Completed + follow-up",summary:`Execution completed. ${v} non-blocking decision${v===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 Cl(e){if(typeof e=="string")return n.jsx(ti,{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:Cl(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 Rt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=gr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:ot(t)}const xf=[/^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 yf(e){return xf.some(t=>t.test(e))}function ai(e){const t=e.title??"";return yf(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(ri(e.type)),isSystem:!1}}const bf=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 hr(e){const t=Nt(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&&bf.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function Lo(e){var d;if(!e||!hr(e))return null;const t=Nt(e),s=Hn((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=ct(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 Ui(e){if(!hr(e))return null;const t=Nt(e);if(!t)return null;const s=ct(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=ct(t,["event","event_name","eventName"])??"",i=ct(t,["changeset_id","changesetId"])??"",a=ct(t,["entity_type","entityType"])??"",c=ct(t,["entity_id","entityId"])??"",l=ia(e)??"",d=ai(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function wf(e){if(!e)return null;const t=Nt(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 Do(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 Ro(e,t){const r=(Rt(t??e.summary)??Rt(e.description)??ot(e.title||ri(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=>Do(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let a=i[0]??Do(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const vf=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:g=null,timeFilterId:y="live",onTimeFilterChange:v,customTimeRange:f={startIso:null,endIso:null},onCustomTimeRangeChange:k,hasMore:x=!1,isLoadingMore:j=!1,onLoadMore:w,onClearSelection:b,onClearWorkstreamFilter:h,onClearAgentFilter:_,onFocusRunId:U,onOpenDecision:le,requestedActivityItemId:V=null,onActivityItemRequestHandled:be,onPlayNextUp:H,onStartAutopilot:Z,onPauseWorkstream:ce,onCreateInitiative:xe,onOpenMissionControl:we,onOpenSettings:K,workspaceId:Ie=null,chatSnapshot:Ee,onRefreshData:fe,isLoading:ee=!1,onOpenNextUp:re}){var va,ka;const Le=Xn(),{open:ne}=fl(),[R,J]=o.useState("all"),[P,Y]=o.useState(!1),[oe,ve]=o.useState(!1),[je,te]=o.useState(""),[Te,pe]=o.useState(new Set),[C,O]=o.useState({}),[W,se]=o.useState("newest"),[De,qe]=o.useState(!1),[Me,M]=o.useState(!1),[q,ie]=o.useState($i),[de,Ce]=o.useState(null),[Ze,Je]=o.useState(null),[Fe,Ge]=o.useState(!1),[He,ft]=o.useState(1),[it,at]=o.useState("structured"),[he,Ke]=o.useState(null),[Ae,B]=o.useState("feed"),[Pe,z]=o.useState(null),[Q,Ne]=o.useState(null),[Re,$e]=o.useState(!1),[Oe,Se]=o.useState(null),[Ve,lt]=o.useState(null),[ze,Tt]=o.useState(!1),[et,kt]=o.useState(null),[Jt,Gt]=o.useState(!1),un=o.useRef(Date.now()),An=o.useRef(null),gs=o.useRef(null),[ht,Wt]=o.useState(null),Sn=o.useRef(null),Qn=o.useRef(null),Ct=o.useRef(null),[Ft,Ut]=o.useState(()=>Fr(f.startIso)),[gt,Xt]=o.useState(()=>Fr(f.endIso)),[Jn,Yn]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),xs=o.useMemo(()=>Qo(y),[y]),_n=o.useMemo(()=>Fr(f.startIso),[f.startIso]),Yt=o.useMemo(()=>Fr(f.endIso),[f.endIso]),mn=o.useMemo(()=>!Ft||!gt?!1:gt.getTime()>=Ft.getTime(),[gt,Ft]),Ht=o.useMemo(()=>y!=="custom"?xs.label:_n&&Yt?`${Pr(_n)} - ${Pr(Yt)}`:"Custom range",[Yt,_n,y,xs.label]);o.useEffect(()=>{Ut(_n),Xt(Yt)},[Yt,_n]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>Yn(window.innerWidth<=640);return p(),window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]),o.useEffect(()=>{const I=()=>{un.current=Date.now()};window.addEventListener("pointerdown",I),window.addEventListener("keydown",I);const N=setInterval(()=>{Date.now()-un.current>3e5&&Gt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",I),window.removeEventListener("keydown",I),clearInterval(N)}},[]);const Pn=o.useMemo(()=>{const p=s.filter(F=>F.status==="completed").length,I=s.filter(F=>F.status==="blocked"||F.status==="failed").length,N=t.filter(F=>{var ke;return F.type==="decision_requested"&&((ke=F.metadata)==null?void 0:ke.status)==="pending"}).length;return{completed:p,blocked:I,decisions:N}},[s,t]),bn=o.useMemo(()=>{const p=new Map;for(const I of s)p.set(I.runId,I.title),p.set(I.id,I.title);return p},[s]),Zn=o.useMemo(()=>{const p=new Map;for(const I of s)I.status&&(p.set(I.runId,I.status),p.set(I.id,I.status));return p},[s]),es=o.useMemo(()=>{var I;const p=new Map;for(const N of s){const F={status:N.status??null,phase:N.phase??null,state:N.state??null,blockerCount:Array.isArray(N.blockers)?N.blockers.length:0,blockerReason:N.blockerReason??((I=N.blockerDiagnostics)==null?void 0:I.reason)??null};p.set(N.runId,F),p.set(N.id,F)}return p},[s]),Cn=o.useMemo(()=>{const p=new Map;for(const I of r){const N={status:I.status??null,blockingDecisions:Math.max(0,I.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(I.decisionCount??0)-(I.blockingDecisionCount??0)),updatedEpoch:ms(I.updatedAt??I.lastEventAt??I.startedAt??null)},F=[I.runId,I.sliceRunId].filter(ke=>typeof ke=="string"&&ke.trim().length>0).map(ke=>ke.trim());for(const ke of F){const Ye=p.get(ke);(!Ye||N.updatedEpoch>=Ye.updatedEpoch)&&p.set(ke,N)}}return p},[r]),ts=o.useMemo(()=>{const p=new Map;for(const I of s){const N=_l(I.progress);N!==null&&(p.set(I.runId,N),p.set(I.id,N))}return p},[s]),It=o.useMemo(()=>{const p=new Map;for(const I of s)!I.agentId||!I.agentName||p.set(I.agentId,I.agentName);return p},[s]),Mn=o.useMemo(()=>{const p=new Map;for(const I of s){const N=I.workstreamId??null;p.set(I.runId,N),p.set(I.id,N)}return p},[s]),wn=o.useMemo(()=>{const p=new Map;for(const I of i)p.set(I.id,I.name);return p},[i]),Tn=o.useMemo(()=>{const p=new Map;for(const I of i)for(const N of I.workstreams??[])p.set(N.id,N.name);return p},[i]);o.useMemo(()=>{const p=[...s];return p.sort((I,N)=>{const F=ms(I.updatedAt??I.lastEventAt??I.startedAt??null);return ms(N.updatedAt??N.lastEventAt??N.startedAt??null)-F}),p},[s]);const Zt=el({}),T=o.useMemo(()=>s.filter(p=>p.status==="running"),[s]),ue=o.useCallback(p=>`${p.initiativeId}:${p.workstreamId}`,[]),X=o.useMemo(()=>Zt.items.find(I=>I.queueState==="running")??null,[Zt.items]),ge=o.useMemo(()=>Zt.items.find(I=>I.queueState==="queued")??null,[Zt.items]),Xe=o.useMemo(()=>X?null:T[0]??null,[X,T]),Et=o.useCallback(async p=>{const I=ue(p);Wt(I);try{const N=await Zt.playWorkstream({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId}),F=N&&typeof N=="object"&&"sessionId"in N?N.sessionId??null:null;F&&(U==null||U(F)),re==null||re()}catch(N){Je(N instanceof Error?N.message:"Dispatch failed")}finally{Wt(null)}},[Zt,U,re,ue]),Qe=o.useMemo(()=>t.map(p=>{const I=ia(p),N=Gp(p),F=Nt(p),ke=I?es.get(I)??null:null,Ye=I?Cn.get(I)??null:null,tt=Qm({sessionStatus:(ke==null?void 0:ke.status)??(I?Zn.get(I)??null:null),sessionPhase:(ke==null?void 0:ke.phase)??null,sessionState:(ke==null?void 0:ke.state)??null,sliceStatus:(Ye==null?void 0:Ye.status)??null,activityType:p.type,activityStatus:ct(F,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:ct(F,["stop_reason","stopReason"]),decisionRequired:p.decisionRequired??!1,blockingDecisionCount:Us(F,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ye==null?void 0:Ye.blockingDecisions)??0,nonBlockingDecisionCount:Us(F,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ye==null?void 0:Ye.nonBlockingDecisions)??0,blockerCount:(ke==null?void 0:ke.blockerCount)??0,blockerReason:(ke==null?void 0:ke.blockerReason)??null}),vt=Jp(N,tt),fn=[p.title,p.description,p.summary,p.agentName,Bp(F)].filter(Vt=>typeof Vt=="string"&&Vt.length>0).join(" ").toLowerCase(),yt=F==null?void 0:F.scope,mt=yt==="milestone"||yt==="workstream"?yt:void 0;return{item:p,bucket:N,userState:vt.state,userStateWhy:vt.why,canonicalProjection:tt,runId:I,timestampEpoch:ms(p.timestamp),searchText:fn,scopeGroupId:mt?I??null:null,scope:mt}}),[t,es,Zn,Cn]),ys=o.useMemo(()=>{let p=0;for(const I of Qe)p=Math.max(p,I.timestampEpoch);return p<=0?!1:Date.now()-p<6e4},[Qe]),Ot=o.useMemo(()=>new Set(c.filter(p=>p&&p.trim().length>0)),[c]),Kt=Ot.size>0,jt=o.useMemo(()=>xr.filter(p=>["live","24h","7d","all"].includes(p.id)),[]),ut=o.useMemo(()=>{if(!Kt)return null;for(const p of Ot){const I=s.find(N=>N.runId===p||N.id===p);if(I)return I}return null},[Kt,Ot,s]),On=o.useMemo(()=>Kt?ut!=null&&ut.runtimeProvider?{id:Op(ut.runtimeProvider)}:us(ut==null?void 0:ut.agentId,ut==null?void 0:ut.agentName,ut==null?void 0:ut.title,ut==null?void 0:ut.lastEventSummary,ut==null?void 0:ut.runtimeClient,l):us(),[ut,Kt,l]),ns=o.useMemo(()=>g?us(g):us(),[g]),{filtered:wt,filteredTotal:Bn,hiddenCount:vn,hiddenSyncCount:At}=o.useMemo(()=>{const p=[];let I=0,N=0;const F=new Set,ke=je.trim().toLowerCase();for(const yt of Qe){const mt=yt.runId;if(Kt&&(!mt||!Ot.has(mt)))continue;if(d){const hn=ur(yt.item),Fs=mt?Mn.get(mt)??null:null;if((hn??Fs)!==d)continue}const Vt=fr(yt.item);if(g&&Vt.agentName!==g)continue;const ks=Ui(yt.item);if(ks){if(F.has(ks)){N+=1;continue}if(F.add(ks),!P){N+=1;continue}}else if(!P&&hr(yt.item)){N+=1;continue}if(!(R==="completed"&&yt.userState!=="completed")&&!(R==="needs_attention"&&yt.userState!=="needs_input"&&yt.userState!=="issue")&&!(R==="in_progress"&&yt.userState!=="in_progress")){if(ke.length>0){const hn=mt?bn.get(mt)??mt:"";if(!`${yt.searchText} ${hn.toLowerCase()}`.includes(ke))continue}p.length<Io?p.push(yt):I+=1}}const Ye=[...p].sort((yt,mt)=>{const Vt=mt.timestampEpoch-yt.timestampEpoch;return W==="newest"?Vt:-Vt}),tt=Math.min(Math.max(1,Math.min(No,q)),Ye.length),vt=Ye.slice(0,tt),fn=Ye.length+I;return{filtered:vt,filteredTotal:fn,hiddenCount:Math.max(0,fn-vt.length),hiddenSyncCount:N}},[R,g,Qe,Kt,je,bn,q,d,Ot,Mn,P,W]),En=o.useMemo(()=>{const p=new Map;for(const N of wt){const F=Xp(N.item.timestamp),ke=p.get(F);ke?ke.push(N):p.set(F,[N])}return Array.from(p.keys()).sort((N,F)=>{const ke=Number(F)-Number(N);return W==="newest"?ke:-ke}).map(N=>({key:N,label:Qp(N),items:p.get(N)??[]}))},[wt,W]),ss=o.useMemo(()=>En.map(p=>{const I=new Map;for(const N of p.items){const F=ai(N.item).title.trim().toLowerCase(),ke=Ui(N.item),Ye=ke?`${N.item.type}::sync::${ke}`:`${N.item.type}::${F}`,tt=I.get(Ye);tt?(tt.count+=1,tt.firstTimestamp=Math.min(tt.firstTimestamp,N.timestampEpoch),tt.allItems.push(N),N.timestampEpoch>tt.representative.timestampEpoch&&(tt.representative=N)):I.set(Ye,{key:Ye,representative:N,count:1,firstTimestamp:N.timestampEpoch,allItems:[N]})}return{...p,clusters:Array.from(I.values())}}),[En]),bs=o.useCallback(p=>{pe(I=>{const N=new Set(I);return N.has(p)?N.delete(p):N.add(p),N}),O(I=>{if(Object.prototype.hasOwnProperty.call(I,p)){const N={...I};return delete N[p],N}return{...I,[p]:dr}})},[]),Ln=o.useCallback((p,I)=>{O(N=>{const F=N[p]??dr,ke=Math.min(I,F+dr);return ke===F?N:{...N,[p]:ke}})},[]),rs=o.useCallback(()=>{!k||!v||!Ft||!gt||gt.getTime()<Ft.getTime()||(k({startIso:Ft.toISOString(),endIso:gt.toISOString()}),v("custom"),M(!1))},[gt,Ft,k,v]),ws=o.useCallback(()=>{Ut(null),Xt(null),k==null||k({startIso:null,endIso:null}),y==="custom"&&(v==null||v("live"))},[k,v,y]),Ls=o.useMemo(()=>Math.min(No,Math.min(Io,Bn)),[Bn]);o.useEffect(()=>{ie($i),pe(new Set),O({})},[R,g,Kt,je,d,P,W,y]),o.useEffect(()=>{if(!De)return;const p=N=>{var ke;const F=N.target;F instanceof Node&&((ke=An.current)!=null&&ke.contains(F)||qe(!1))},I=N=>{N.key==="Escape"&&qe(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",I),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",I)}},[De]),o.useEffect(()=>{if(!Me)return;const p=N=>{var ke;const F=N.target;F instanceof Node&&((ke=gs.current)!=null&&ke.contains(F)||M(!1))},I=N=>{N.key==="Escape"&&M(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",I),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",I)}},[Me]);const Ds=o.useRef(w);Ds.current=w;const br=o.useRef(x);br.current=x;const wr=o.useRef(j);wr.current=j,o.useEffect(()=>{const p=Sn.current,I=Qn.current;if(!p||!I)return;const N=new IntersectionObserver(F=>{var Ye;if(F.some(tt=>tt.isIntersecting)){if(wt.length<Ls){ie(tt=>Math.min(Ls,Math.max(tt,$i)+Pp));return}br.current&&!wr.current&&((Ye=Ds.current)==null||Ye.call(Ds))}},{root:p,rootMargin:"0px 0px 600px 0px"});return N.observe(I),()=>N.disconnect()},[wt.length,Ls]);const Lt=o.useMemo(()=>de?wt.findIndex(p=>p.item.id===de):-1,[de,wt]),D=Lt>=0?wt[Lt]:null,vr=o.useMemo(()=>{var I;const p=new Map;for(const N of a){const F=(I=N==null?void 0:N.sliceRunId)==null?void 0:I.trim();!F||p.has(F)||p.set(F,N)}return p},[a]),qn=o.useMemo(()=>{if(!D)return null;const p=D.runId??ia(D.item);return p?vr.get(p)??null:null},[D,vr]),zn=o.useMemo(()=>Al((D==null?void 0:D.item)??null),[D]),pn=o.useMemo(()=>Oi((D==null?void 0:D.item)??null),[D]),Dn=o.useMemo(()=>Il((D==null?void 0:D.item)??null),[D]),is=o.useMemo(()=>Dn?null:mf((D==null?void 0:D.item)??null,t),[Dn,D,t]),We=o.useMemo(()=>D?Mo(D.item):null,[D]),Rn=o.useMemo(()=>We?We.executor??We.requester:null,[We]),ae=Dn??(is==null?void 0:is.detail)??null,Xs=o.useMemo(()=>{var p,I;return Wi((ae==null?void 0:ae.requesterAgentName)??((p=We==null?void 0:We.requester)==null?void 0:p.name)??null,(ae==null?void 0:ae.requesterAgentId)??((I=We==null?void 0:We.requester)==null?void 0:I.id)??null,It)},[ae,We,It]),as=o.useMemo(()=>Up(Xs),[Xs]),Qs=o.useMemo(()=>{var I,N;const p=Wi((ae==null?void 0:ae.agentName)??((I=We==null?void 0:We.executor)==null?void 0:I.name)??null,(ae==null?void 0:ae.agentId)??((N=We==null?void 0:We.executor)==null?void 0:N.id)??null,It);return p==="—"?(We==null?void 0:We.primaryLabel)??"Codex":p},[ae,We,It]),en=o.useMemo(()=>D!=null&&D.runId?ts.get(D.runId)??null:null,[D,ts]),tn=o.useMemo(()=>hf(ae,en),[ae,en]),$=o.useMemo(()=>{const p=ae;if(!p)return null;const I=p.initiativeId??(D==null?void 0:D.item.initiativeId)??null,N=I?i.find(hn=>hn.id===I)??null:null,F=p.initiativeTitle??(N==null?void 0:N.name)??null,ke=p.initiativeStatus??(N==null?void 0:N.status)??null,Ye=(N==null?void 0:N.workstreams)??[],tt=Ye.length>0?Ye.length:null,vt=tt!==null?Ye.filter(hn=>di(hn.status)).length:null,fn=tt&&vt!==null?Math.round(vt/tt*100):null,yt=p.workstreamId??null,mt=yt&&Ye.length>0?Ye.find(hn=>hn.id===yt)??null:null,Vt=p.workstreamTitle??(mt==null?void 0:mt.name)??(yt?Tn.get(yt)??null:null),ks=p.workstreamStatus??(mt==null?void 0:mt.status)??null;return{initiativeId:I,initiativeTitle:F,initiativeStatus:ke,totalInitiativeWorkstreams:tt,doneInitiativeWorkstreams:vt,initiativeWorkstreamPct:fn,workstreamId:yt,workstreamTitle:Vt,workstreamStatus:ks,taskTitle:p.taskTitle,milestoneTitle:p.milestoneTitle,scopedTaskCount:p.taskIds.length,scopedMilestoneCount:p.milestoneIds.length,statusUpdatesApplied:p.statusUpdatesApplied,statusUpdatesBuffered:p.statusUpdatesBuffered,artifacts:p.artifacts,decisions:p.decisions,blockingDecisions:p.blockingDecisions,nonBlockingDecisions:p.nonBlockingDecisions,tokensUsed:p.tokensUsed,tokenBudget:p.tokenBudget,nextStep:p.nextStep,phase:p.phase,stopReason:p.stopReason,parsedStatus:p.parsedStatus}},[ae,D,i,Tn]),Dt=o.useMemo(()=>D?gf(D.item,ae,$?{decisions:$.decisions,blockingDecisions:$.blockingDecisions,nonBlockingDecisions:$.nonBlockingDecisions,stopReason:$.stopReason,parsedStatus:$.parsedStatus}:null,D.canonicalProjection??null):null,[ae,D,$]),kr=o.useMemo(()=>{if(!$)return[];const p=[];Dt&&p.push({label:"Status",value:Dt.label}),$.scopedTaskCount>0&&p.push({label:"Tasks",value:$.scopedTaskCount}),$.scopedMilestoneCount>0&&p.push({label:"Milestones",value:$.scopedMilestoneCount});const I=$.artifacts??0;I>0&&p.push({label:"Artifacts",value:I});const N=$.decisions??0;N>0&&p.push({label:"Decisions",value:N}),$.blockingDecisions&&$.blockingDecisions>0&&p.push({label:"Blocking",value:$.blockingDecisions,tone:"critical"}),$.stopReason&&p.push({label:"Stop reason",value:tr($.stopReason)??ot($.stopReason)});const F=Ql($.tokensUsed,$.tokenBudget);return F&&p.push({label:"Token usage",value:F}),p},[$,Dt]),Rs=o.useMemo(()=>{const p=new Set;for(const I of df((D==null?void 0:D.item)??null))p.add(I);for(const I of(ae==null?void 0:ae.decisionIds)??[])p.add(I);for(const I of(ae==null?void 0:ae.blockingDecisionIds)??[])p.add(I);for(const I of(ae==null?void 0:ae.nonBlockingDecisionIds)??[])p.add(I);return Array.from(p)},[ae,D]),ui=o.useMemo(()=>le?Rs.length>0||(D==null?void 0:D.item.decisionRequired)===!0||(($==null?void 0:$.blockingDecisions)??0)>0?!0:(Dt==null?void 0:Dt.label)==="Needs decision":!1,[Rs,D,$,Dt,le]),Js=o.useMemo(()=>tn?tn.tone==="positive"?E.lime:tn.tone==="warning"?E.amber:tn.tone==="critical"?E.red:E.teal:E.teal,[tn]),vs=(tn==null?void 0:tn.terminalStop)===!0,nt=o.useMemo(()=>ef(Nt((D==null?void 0:D.item)??null)),[D]),Ys=o.useMemo(()=>Nt((D==null?void 0:D.item)??null),[D]),xt=o.useMemo(()=>rf((D==null?void 0:D.item)??null,ae),[ae,D]),Wn=o.useMemo(()=>{if(!(xt!=null&&xt.retryAt))return null;const p=new Date(xt.retryAt);if(!Number.isFinite(p.getTime()))return null;const I=p.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),N=Mt(xt.retryAt);return N?`${I} (${N})`:I},[xt]),Zs=o.useMemo(()=>D?fr(D.item):{agentId:null,agentName:null},[D]),m=o.useMemo(()=>Eo(Ts(D==null?void 0:D.item.metadata)??void 0),[D]);o.useMemo(()=>Eo(Ys),[Ys]);const A=o.useMemo(()=>{const p=Sl((D==null?void 0:D.item)??null);return p.length>0?p:uf((D==null?void 0:D.item)??null,t,new Set)},[D,t]),L=o.useMemo(()=>A.filter((p,I,N)=>N.findIndex(F=>F.path===p.path)===I),[A]),S=o.useMemo(()=>L.slice(0,4),[L]),G=o.useMemo(()=>L.slice(4),[L]),_e=o.useMemo(()=>{if(L.length===0)return null;const p=L[0];return p?zi(p.path):null},[L]),st=o.useMemo(()=>{const p=Rt(he);if(p)return p;const I=Lo((D==null?void 0:D.item)??null);return I||(Rt(D==null?void 0:D.item.summary)??Rt(D==null?void 0:D.item.description))},[he,D]),Ue=o.useMemo(()=>D?hr(D.item):!1,[D]),Be=o.useMemo(()=>{if(!ae||!D)return null;const p=ae.initiativeId??D.item.initiativeId??null,I=ae.workstreamId??ur(D.item);if(!p||!I)return null;const N=Nn(($==null?void 0:$.parsedStatus)??ae.parsedStatus),F=Nn(($==null?void 0:$.stopReason)??ae.stopReason),ke=Math.max(0,($==null?void 0:$.blockingDecisions)??ae.blockingDecisions??(D.item.decisionRequired?1:0)),Ye=Math.max(0,($==null?void 0:$.nonBlockingDecisions)??ae.nonBlockingDecisions??0),tt=N==="blocked"||N==="error"||N==="failed"||F==="blocked"||F==="error"||D.item.type==="blocker_created",vt=!tt&&ke===0&&Ye>0&&(N==="needs_decision"||N==="completed"||F==="completed");return!tt&&!vt?null:{initiativeId:p,workstreamId:I,runId:D.runId??null,event:ae.event,requestedByAgentId:ae.requesterAgentId??D.item.requesterAgentId??null,requestedByAgentName:ae.requesterAgentName??D.item.requesterAgentName??null,actionLabel:tt?"Auto-fix in 10s":"Auto-continue in 10s",helperText:tt?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:tt}},[ae,D,$]),dt=o.useCallback(()=>{Ce(null)},[]),St=o.useCallback(async(p,I)=>{if(I){lt(null),Se(p);try{await I()}catch(N){lt(N instanceof Error?N.message:"Action failed")}finally{Se(N=>N===p?null:N)}}},[]),jr=o.useCallback(async()=>{var p;if(!(!Be||ze)){Tt(!0),kt(null);try{const I=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:Be.initiativeId,workstreamId:Be.workstreamId,runId:Be.runId,event:Be.event,requestedByAgentId:Be.requestedByAgentId,requestedByAgentName:Be.requestedByAgentName,graceMs:1e4})}),N=await I.json().catch(()=>null);if(!I.ok||(N==null?void 0:N.ok)!==!0)throw new Error((N==null?void 0:N.error)||`Request failed (${I.status})`);const F=(p=N==null?void 0:N.scheduled)!=null&&p.dueAt?new Date(N.scheduled.dueAt):null,ke=F&&Number.isFinite(F.getTime())?F.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;kt(ke?`Scheduled. Auto action starts by ${ke} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(I){const N=I instanceof Error?I.message:"Failed to schedule auto-fix";kt(In(N)||N)}finally{Tt(!1)}}},[Be,ze]);o.useEffect(()=>{if(!Ze)return;const p=window.setTimeout(()=>Je(null),2e3);return()=>window.clearTimeout(p)},[Ze]),o.useEffect(()=>{lt(null)},[R,je,y]),o.useEffect(()=>{if(!V){Ct.current=null;return}const p=V.trim();!p||Ct.current===p||!t.some(N=>N.id===p)||(Ct.current=p,ve(!1),J("all"),te(""),ft(1),Ce(p),be==null||be(p))},[t,be,V]);const rn=o.useCallback(async(p,I)=>{if(I)try{await navigator.clipboard.writeText(I),Je(`${p} copied`)}catch{Je("Copy failed")}},[]);o.useEffect(()=>{at("structured"),Ge(!1),Tt(!1),kt(null)},[de]),o.useEffect(()=>{Ke(null),B("feed");const p=wf((D==null?void 0:D.item)??null);if(!p||Pt())return;const I=new URLSearchParams({turnId:p.turnId});p.sessionKey&&I.set("sessionKey",p.sessionKey),p.runId&&I.set("run",p.runId);const N=new AbortController;return fetch(`/orgx/api/live/activity/detail?${I.toString()}`,{method:"GET",signal:N.signal}).then(async F=>{var Ye;return F.ok?((Ye=(await F.json()).detail)==null?void 0:Ye.summary)??null:(F.status===404&&B("missing"),null)}).then(F=>{typeof F=="string"&&F.trim().length>0?(Ke(F),B("local")):B("missing")}).catch(F=>{F instanceof DOMException&&F.name==="AbortError"||B("missing")}),()=>N.abort()},[D]),o.useEffect(()=>{z(null),Ne(null);const p=D==null?void 0:D.item;if(!p||Re)return;const I=(he??p.summary??p.description??p.title??"").trim();if(!I||Pt())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:I,title:p.title??null,type:p.type})}).then(async F=>F.ok?await F.json():((F.status===404||F.status===405)&&$e(!0),null)).then(F=>{const ke=F==null?void 0:F.headline;typeof ke=="string"&&ke.trim().length>0&&($e(!1),z(ke.trim()),Ne((F==null?void 0:F.source)??null))}).catch(F=>{F instanceof DOMException&&F.name}),()=>N.abort()},[D,he,Re]);const $n=o.useCallback(p=>{var F;if(wt.length===0)return;const N=((Lt>=0?Lt:0)+p+wt.length)%wt.length;ft(p),Ce(((F=wt[N])==null?void 0:F.item.id)??null)},[Lt,wt]);o.useEffect(()=>{de&&(Lt>=0||Ce(null))},[Lt,de]),o.useEffect(()=>{if(!de)return;const p=I=>{I.key==="ArrowRight"||I.key.toLowerCase()==="l"?(I.preventDefault(),$n(1)):(I.key==="ArrowLeft"||I.key.toLowerCase()==="h")&&(I.preventDefault(),$n(-1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[de,$n]);const os=Ot.size===1,mi=os?[...Ot][0]:null,Ml=mi?s.find(p=>p.runId===mi||p.id===mi)??null:null,pi=o.useMemo(()=>{if(!os)return[];const p=[],I=new Set;for(const N of Qe){if(!N.runId||!Ot.has(N.runId))continue;const F=Ui(N.item);if(F){if(I.has(F)||(I.add(F),!P))continue}else if(!P&&hr(N.item))continue;p.push(N.item)}return p},[os,Qe,Ot,P]),wa=!Le&&wt.length<=160,$s=(p,I,N)=>{const F=p.item,ke=N??F.id,Ye=fr(F),tt=Mo(F),vt=tt.executor??tt.requester,fn=Wi(nn((vt==null?void 0:vt.name)??tt.primaryLabel??F.agentName??Ye.agentName??null),nn((vt==null?void 0:vt.id)??F.agentId??Ye.agentId??null),It)||"OrgX",yt=qi(p.userState),mt=W==="newest"&&I<2,Vt=p.runId,ks=Lo(F),{title:hn}=ai(F),Fs=ks??Rt(F.summary),Nr=Rt(F.description),ja=Ro(F,Fs??Nr??null),Na=F.initiativeId?wn.get(F.initiativeId)??ot(F.initiativeId):null,fi=ur(F)??(Vt?Mn.get(Vt)??null:null),Ia=fi?Tn.get(fi)??ot(fi):null,Tl=[Na,Ia].filter(Boolean).join(" > ")||Na||Ia||ot(F.type),El=Bi(p.userState),Ll=new Date(F.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Dl=Mt(F.timestamp),Rl=p.bucket==="artifact"?tf(F):null;return n.jsx(mp,{renderKey:ke,displayTitle:hn,headline:ja,contextLabel:Tl,detailText:(Fs??Nr)!==ja?Fs??Nr:null,displayAgentName:fn,railColor:yt,userStateLabel:El,userStateWhy:p.userStateWhy,relativeTime:Dl,timeLabel:Ll,isRecent:mt,enableMotion:wa,onOpen:()=>{ft(1),Ce(F.id)},ariaLabel:`Open activity details for ${hn||ri(F.type)}`,artifactSnippet:Rl},ke)};return n.jsx(Sp,{sessions:s,initiatives:i??[],workspaceId:Ie??null,query:je,statusFilter:R,sortOrder:W,timeFilterId:y,customTimeRange:f,snapshot:Ee,onRequestRefresh:fe,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[os&&pi.length>0?n.jsx(cp,{items:pi,session:Ml,agentName:((va=pi[0])==null?void 0:va.agentName)??null,onBack:b,onOpenItem:p=>{ft(1),Ce(p.id)}}):n.jsxs(n.Fragment,{children:[(X||ge||Xe)&&n.jsx("div",{className:"border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"grid gap-2.5 lg:grid-cols-2",children:[n.jsxs("div",{className:"relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[n.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, rgba(255,255,255,0.10), rgba(191,255,0,0.10), transparent 70%)"}}),n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx($t,{name:(X==null?void 0:X.runnerAgentName)??(Xe==null?void 0:Xe.agentName)??"OrgX",hint:X?`${X.runnerAgentId} ${X.runnerSource}`:(Xe==null?void 0:Xe.agentId)??null,size:"xs"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/72",children:"Now"}),n.jsx("span",{className:"rounded-full border border-white/[0.10] bg-white/[0.03] px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.07em] text-secondary",children:"Running"})]}),n.jsx("p",{className:"mt-1 truncate text-body font-semibold leading-snug text-bright",children:(X==null?void 0:X.workstreamTitle)??(Xe==null?void 0:Xe.title)??"Nothing running"}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",children:X?`${X.initiativeTitle}${X.nextTaskTitle?` · ${X.nextTaskTitle}`:""}`:Xe?"Session is running. Focus it to watch progress.":"Queue a workstream to start execution."})]})]}),n.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var I;const p=((I=X==null?void 0:X.autoContinue)==null?void 0:I.activeRunId)??(Xe==null?void 0:Xe.runId)??null;p&&(U==null||U(p))},disabled:!(((ka=X==null?void 0:X.autoContinue)==null?void 0:ka.activeRunId)??(Xe==null?void 0:Xe.runId)),className:"control-pill h-8 px-3 text-caption font-semibold disabled:opacity-45",children:"Focus"}),n.jsx("button",{type:"button",onClick:re,className:"control-pill h-8 px-3 text-caption font-semibold",title:"Open Next Up queue",children:"Queue"})]})]}),n.jsxs("div",{className:"relative overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[n.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, rgba(255,255,255,0.10), rgba(10,212,196,0.12), transparent 70%)"}}),n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx($t,{name:(ge==null?void 0:ge.runnerAgentName)??"OrgX",hint:ge?`${ge.runnerAgentId} ${ge.runnerSource}`:null,size:"xs"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/72",children:"Up Next"}),n.jsx("span",{className:"rounded-full border border-white/[0.10] bg-white/[0.03] px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.07em] text-secondary",children:"Queued"})]}),n.jsx("p",{className:"mt-1 truncate text-body font-semibold leading-snug text-bright",children:(ge==null?void 0:ge.workstreamTitle)??"Queue the next workstream"}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",children:ge?`${ge.initiativeTitle}${ge.nextTaskTitle?` · ${ge.nextTaskTitle}`:""}`:"Open the queue to choose what should run next."})]})]}),n.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{ge&&Et(ge)},disabled:!ge||Zt.isPlaying||ht===(ge?ue(ge):null),className:"control-pill h-8 px-3 text-caption font-semibold disabled:opacity-45","data-state":"active",title:ge?"Dispatch queued workstream":"No queued workstream",children:ht&&ge&&ht===ue(ge)?"Dispatching...":"Play"}),n.jsx("button",{type:"button",onClick:re,className:"control-pill h-8 px-3 text-caption font-semibold",title:"Open Next Up queue",children:"Queue"})]})]})]})}),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:Bn}),vn>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:["+",vn," hidden"]}),At>0&&!P&&n.jsxs("button",{type:"button",onClick:()=>Y(!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:[At," sync hidden"]}),P&&n.jsx("button",{type:"button",onClick:()=>Y(!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:gs,children:[n.jsxs("button",{type:"button",onClick:()=>{M(p=>!p),qe(!1)},"aria-haspopup":"menu","aria-expanded":Me,className:me("inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors",Me?"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:Ht}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:me("transition-transform duration-200",Me&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:Me&&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:xr.filter(p=>p.id!=="custom").map(p=>{const I=y===p.id;return n.jsx("button",{type:"button",onClick:()=>{v==null||v(p.id),M(!1)},className:me("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",I?"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:p.label},p.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"}),Jn?n.jsx("input",{type:"datetime-local",step:300,value:Fi(Ft),onChange:p=>Ut(So(p.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(Aa,{selected:Ft,onChange:p=>Ut(p instanceof Date?p:null),selectsStart:!0,startDate:Ft,endDate:gt,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"}),Jn?n.jsx("input",{type:"datetime-local",step:300,min:Fi(Ft),value:Fi(gt),onChange:p=>Xt(So(p.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(Aa,{selected:gt,onChange:p=>Xt(p instanceof Date?p:null),selectsEnd:!0,minDate:Ft??void 0,startDate:Ft,endDate:gt,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:mn?`${Pr(Ft)} - ${Pr(gt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:ws,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:rs,disabled:!mn,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:me("h-1.5 w-1.5 flex-shrink-0 rounded-full",ys&&"pulse-soft"),style:{backgroundColor:E.lime},"aria-label":"Live",title:ys?"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:je,onChange:p=>te(p.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:[(Kt||d||g)&&n.jsxs(n.Fragment,{children:[Kt&&n.jsxs("button",{onClick:b,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Ao(On.id)?n.jsx(Ks,{provider:On.id,size:"xs"}):n.jsx($t,{name:(ut==null?void 0:ut.agentName)??"OrgX",hint:l??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",l?`: ${l}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:h,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),g&&n.jsxs("button",{onClick:_,className:"chip chip-avatar inline-flex min-w-0 items-center",style:{borderColor:"rgba(10,212,196,0.3)",color:"#0AD4C4"},"aria-label":"Clear agent filter",children:[Ao(ns.id)?n.jsx(Ks,{provider:ns.id,size:"xs"}):n.jsx($t,{name:g,hint:g,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Agent: ",g]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]})]}),n.jsx("div",{className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-white/[0.08] bg-white/[0.02] p-0.5",role:"group","aria-label":"Activity status filters",children:Object.keys($r).map(p=>{const I=R===p;return n.jsx("button",{type:"button",onClick:()=>J(p),"aria-pressed":I,className:me("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",I?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:$r[p]},p)})}),n.jsx("button",{type:"button",onClick:()=>ve(p=>!p),className:me("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",oe?"border-lime/30 text-lime":"border-white/[0.1]"),"aria-pressed":oe,"aria-label":oe?"Expand activity density":"Compact activity density",title:oe?"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:oe?"M4 12h16":"M4 12h10"}),n.jsx("path",{d:"M4 17h16"})]})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:An,children:[n.jsxs("button",{type:"button",onClick:()=>{qe(p=>!p),M(!1)},"aria-haspopup":"menu","aria-expanded":De,"aria-label":"Activity filters",title:"Activity filters",className:me("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",De?"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:me("transition-transform duration-200",De&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(bt,{children:De&&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(p=>n.jsx("button",{type:"button",onClick:()=>{se(p.id),qe(!1)},className:me("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",W===p.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:p.label},p.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys($r).map(p=>{const I=R===p;return n.jsx("button",{type:"button",onClick:()=>{J(p),qe(!1)},className:me("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",I?"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:$r[p]},p)})})]}),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:()=>{Y(p=>!p)},className:me("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",P?"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:P?"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:Sn,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[wt.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:ee?"Syncing activity feed...":Kt?"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:ee?"Live updates usually appear within a few seconds after dispatch.":`Try widening the time window (${Ht}), changing filters, or launch the next workstream.`})]})]}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:jt.map(p=>{const I=y===p.id;return n.jsx("button",{type:"button",onClick:()=>v==null?void 0:v(p.id),className:me("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",I?"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:p.label},`empty-time-${p.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(Kt||d||g)&&n.jsx("button",{type:"button",onClick:()=>{Kt&&b(),d&&(h==null||h()),g&&(_==null||_())},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"}),H&&n.jsx("button",{type:"button",onClick:()=>void St("play",H),disabled:Oe!==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:Oe==="play"?"Starting...":"Start next session"}),!H&&we&&n.jsx("button",{type:"button",onClick:we,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),Ve&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Ve})]})}),n.jsx(dp,{completedCount:Pn.completed,decisionsCount:Pn.decisions,blockerCount:Pn.blocked,visible:Jt,onDismiss:()=>{Gt(!1),un.current=Date.now()}}),wt.length>0&&n.jsxs("div",{className:"space-y-4",children:[ss.map(p=>{const I=oe?p.clusters.slice(0,4):p.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:p.label}),wa?n.jsx(bt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:I.map((N,F)=>{const ke=Te.has(N.key),Ye=N.allItems.slice(1),tt=Ye.length,vt=Math.min(tt,C[N.key]??dr),fn=Ye.slice(0,vt);if(N.count===1)return $s(N.representative,F);const yt=`cluster:${N.key}`;return n.jsxs("div",{children:[$s(N.representative,F,yt),n.jsxs("button",{type:"button",onClick:mt=>{mt.stopPropagation(),bs(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:ke?"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:me("transition-transform",ke?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ke&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[fn.map((mt,Vt)=>$s(mt,F+Vt+1)),vt<tt&&n.jsxs("button",{type:"button",onClick:mt=>{mt.stopPropagation(),Ln(N.key,tt)},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 (",tt-vt," remaining)"]})]})]},N.key)})})}):n.jsx("div",{className:"space-y-2",children:I.map((N,F)=>{const ke=Te.has(N.key),Ye=N.allItems.slice(1),tt=Ye.length,vt=Math.min(tt,C[N.key]??dr),fn=Ye.slice(0,vt);if(N.count===1)return $s(N.representative,F);const yt=`cluster:${N.key}`;return n.jsxs("div",{children:[$s(N.representative,F,yt),n.jsxs("button",{type:"button",onClick:mt=>{mt.stopPropagation(),bs(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:ke?"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:me("transition-transform",ke?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ke&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[fn.map((mt,Vt)=>$s(mt,F+Vt+1)),vt<tt&&n.jsxs("button",{type:"button",onClick:mt=>{mt.stopPropagation(),Ln(N.key,tt)},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 (",tt-vt," remaining)"]})]})]},N.key)})}),oe&&p.clusters.length>I.length&&n.jsxs("p",{className:"mt-1.5 text-caption text-muted",children:["+",p.clusters.length-I.length," more"]})]},p.key)}),n.jsx("div",{ref:Qn,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:me("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",j?"opacity-100":x?"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]"})]})})}),!x&&!j&&wt.length>0&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:vn>0?`${wt.length} of ${Bn} events`:"You’ve reached the beginning"})]})]})]}),n.jsx(Fp,{}),n.jsx(pp,{open:D!==null,onClose:dt,children:D&&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:qi(D.userState),boxShadow:`0 0 12px ${qi(D.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Bi(D.userState)," · ",Lt+1,"/",wt.length]}),Ze&&n.jsx(kn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:Ze})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[D.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(D.runId),dt()},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:()=>$n(-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:()=>$n(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:()=>Ge(p=>!p),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),Fe&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Ge(!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:[D.runId&&n.jsx("button",{type:"button",onClick:()=>{rn("Run id",D.runId??""),Ge(!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"}),Zs.agentId&&n.jsx("button",{type:"button",onClick:()=>{rn("Agent id",Zs.agentId??""),Ge(!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:()=>{rn("Event id",D.item.id),Ge(!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:dt,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"Close activity detail",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]})]}),n.jsx("div",{className:"relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-5 pb-5 pt-4 sm:px-6",children:n.jsx(bt,{mode:"wait",custom:He,children:n.jsx(ye.section,{custom:He,initial:{opacity:0,x:He*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:He*-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:Pe||Ro(D.item,he)||ot(D.item.title||ri(D.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(D.item.timestamp).toLocaleString()," · ",Mt(D.item.timestamp),Q==="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 p=(ae==null?void 0:ae.workstreamId)??ur(D.item)??(D.runId?Mn.get(D.runId)??null:null),I=p?Tn.get(p)??ot(p):null,F=[(ae==null?void 0:ae.initiativeTitle)??(D.item.initiativeId?wn.get(D.item.initiativeId)??null:null),I].filter(Boolean).join(" > ");return F?n.jsx(kn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:F})}):null})(),n.jsx(kn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Bi(D.userState)}),n.jsxs(kn,{tone:"muted",children:[n.jsx($t,{name:(Rn==null?void 0:Rn.label)??(We==null?void 0:We.primaryLabel)??"OrgX",hint:Rn?Pi(Rn):(We==null?void 0:We.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Rn==null?void 0:Rn.label)??(We==null?void 0:We.primaryLabel)??"OrgX"})]}),Ue&&n.jsx(kn,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(gp,{item:D.item}),zn&&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:zn.source==="metadata"?"Artifact":ot(zn.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":it==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${it==="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":it==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${it==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),pn&&n.jsx("button",{type:"button",onClick:()=>ne(pn),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:it==="structured"?Cl(zn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(zn.value,null,2)})})})]}),Dt&&n.jsxs("div",{className:me("rounded-xl border px-3.5 py-3",Dt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Dt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Dt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Dt.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:Dt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Dt.summary}),Dt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Dt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[D.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(D.runId),dt()},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"}),ui&&n.jsx("button",{type:"button",onClick:()=>{le==null||le(Rs[0]??null),dt()},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:Rs.length>0?"Resolve decision":"Resolve decisions"}),pn&&!zn&&n.jsx("button",{type:"button",onClick:()=>ne(pn),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"}),_e&&n.jsx("a",{href:_e,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"}),Be&&n.jsx("button",{type:"button",onClick:()=>void jr(),disabled:ze,className:me("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",Be.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:ze?"Scheduling...":Be.actionLabel})]}),Be&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:et??Be.helperText})]}),xt&&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(kn,{tone:xt.isRateLimited?"muted":"red",children:xt.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:xt.domainCurrent!==null&&xt.domainMax!==null?`${xt.domainCurrent}/${xt.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:xt.totalCurrent!==null&&xt.totalMax!==null?`${xt.totalCurrent}/${xt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[xt.domain&&n.jsxs(kn,{tone:"muted",children:["Domain: ",ot(xt.domain)]}),xt.modelTier&&n.jsxs(kn,{tone:"muted",children:["Tier: ",ot(xt.modelTier)]}),Wn&&n.jsxs(kn,{tone:"muted",children:["Retry: ",Wn]}),!Wn&&xt.retryInMs!==null&&n.jsxs(kn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(xt.retryInMs/1e3)),"s"]})]}),xt.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:Rt(xt.blockedReason)??xt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[K&&n.jsx("button",{type:"button",onClick:K,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"}),Be&&n.jsx("button",{type:"button",onClick:()=>void jr(),disabled:ze,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:ze?"Scheduling...":"Retry now"})]})]}),kr.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:kr.map(p=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:p.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${p.tone==="critical"?"text-red-300":"text-primary"}`,children:p.value})]},p.label))})]}),We&&!ae&&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:We.requester?n.jsxs(n.Fragment,{children:[n.jsx($t,{name:We.requester.label,hint:Pi(We.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:We.requester.label})]}):n.jsx("span",{children:pr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:We.mode==="handoff"?"Delegated handoff":We.mode==="requested"?"Dispatch requested":We.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:We.executor?n.jsxs(n.Fragment,{children:[n.jsx($t,{name:We.executor.label,hint:Pi(We.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:We.executor.label})]}):n.jsx("span",{children:pr("Not assigned")})})]}),We.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:We.subtitle})]}),ae&&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:tr(ae.event)??ot(ae.event)})]}),is&&n.jsxs("p",{className:"mt-1 px-1 text-caption text-muted",children:["Based on related activity (",ot(is.relation),")."]})]}),tn&&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:vs?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:Js},children:vs?(Dt==null?void 0:Dt.label)??"Stopped":`${tn.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,tn.pct)}%`,backgroundColor:Js}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:tn.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($t,{name:as.primary,hint:as.secondary??as.primary,size:"xs"}),n.jsx("span",{children:as.primary})]}),as.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",as.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($t,{name:Qs,hint:Qs,size:"xs"}),n.jsx("span",{children:Qs})]})]}),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:ae.dispatcherClient?ot(ae.dispatcherClient):"OrgX"})]}),(ae.domain||ae.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:[ae.domain??"",ae.requiredSkills.length>0?`${ae.domain?" · ":""}${ae.requiredSkills.join(", ")}`:""]})]})]})]}),$&&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:$.initiativeTitle??($.initiativeId?ds($.initiativeId):"—")})]}),$.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:ot($.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:$.workstreamTitle??($.workstreamId?ds($.workstreamId):"—")})]}),$.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:ot($.workstreamStatus)})]})]}),$.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:[$.doneInitiativeWorkstreams??0,"/",$.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,$.initiativeWorkstreamPct)}%`}})})]})]}),(($==null?void 0:$.taskTitle)||($==null?void 0:$.milestoneTitle)||($==null?void 0:$.phase)||($==null?void 0:$.nextStep)||($==null?void 0:$.parsedStatus)||($==null?void 0:$.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:[($==null?void 0:$.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:$.taskTitle})]}),($==null?void 0:$.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:$.milestoneTitle})]}),($==null?void 0:$.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:tr($.phase)??ot($.phase)})]}),($==null?void 0:$.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:$.nextStep})]}),($==null?void 0:$.parsedStatus)&&$.parsedStatus!==($==null?void 0:$.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:tr($.parsedStatus)??ot($.parsedStatus)})]}),($==null?void 0:$.stopReason)&&$.stopReason!==($==null?void 0:$.phase)&&$.stopReason!==($==null?void 0:$.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:tr($.stopReason)??ot($.stopReason)})]})]})]}),ae.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:ae.error})]}),st&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Ae==="missing"&&!Ue&&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(ti,{mode:"block",text:st,className:"text-body leading-relaxed text-primary"})]}),Rt(D.item.description)&&Rt(D.item.description)!==st&&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(ti,{mode:"block",text:Rt(D.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),qn&&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:qn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:qn.dispatch})]}),qn.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:qn.highlights.slice(0,3).map((p,I)=>n.jsx("li",{children:p},`${qn.sliceRunId}:highlight:${I}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:qn.outcome.summary})]})]})]}),L.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.jsxs("p",{className:"mb-2 px-1 text-caption text-secondary",children:[L.length," ",L.length===1?"file":"files"," captured for this run."]}),n.jsxs("div",{className:"space-y-2",children:[S.map((p,I)=>{const N=zi(p.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(p.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:_s(p.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 rn(`${ot(p.key)} path`,p.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"})]})]},`${p.key}:${p.path}:${I}`)}),G.length>0&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary",children:["View ",G.length," additional evidence file",G.length===1?"":"s"]}),n.jsx("div",{className:"mt-2 space-y-2",children:G.map((p,I)=>{const N=zi(p.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(p.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:_s(p.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 rn(`${ot(p.key)} path`,p.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"})]})]},`${p.key}:${p.path}:overflow:${I}`)})})]})]})]}),D&&Oi(D.item)&&!zn&&n.jsxs("button",{type:"button",onClick:()=>{const p=Oi(D.item);p&&ne(p)},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:E.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:E.cyan},children:"View registered artifact"})]}),(nt||(ae==null?void 0:ae.logPath)||m)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(nt||(ae==null?void 0:ae.logPath)||(ae==null?void 0:ae.outputPath)||($==null?void 0:$.initiativeId)||($==null?void 0:$.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:[nt&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[nt.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(nt.domain)})]}),(nt.provider||nt.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:[nt.provider?`${ot(nt.provider)} · `:"",nt.model?gr(nt.model):"—"]})]}),nt.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(nt.modelTier)})]}),nt.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",nt.pluginVersion]})]})]}),(nt==null?void 0:nt.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:[nt.skillPack.name??"—",nt.skillPack.version?`@${nt.skillPack.version}`:"",nt.skillPack.source?` · ${nt.skillPack.source}`:""]}),nt.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var p;return void rn("Skill pack checksum",((p=nt.skillPack)==null?void 0:p.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 ",nt.skillPack.checksum.slice(0,12)]})]}),nt&&nt.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"}),nt.requiredSkills.map(p=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:p},p))]}),(nt==null?void 0:nt.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:[nt.kickoffContextSource?`${nt.kickoffContextSource} · `:"",nt.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void rn("Kickoff context hash",nt.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"})]}),((ae==null?void 0:ae.logPath)||(ae==null?void 0:ae.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(ae==null?void 0:ae.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: ",_s(ae.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void rn("Log path",(ae==null?void 0:ae.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"})]}),(ae==null?void 0:ae.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: ",_s(ae.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void rn("Output path",(ae==null?void 0:ae.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"})]})]}),(($==null?void 0:$.initiativeId)||($==null?void 0:$.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[($==null?void 0:$.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",ds($.initiativeId)]}),($==null?void 0:$.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",ds($.workstreamId)]})]})]})]}),m&&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:m})]})]})},D.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"})]})})]})})}),kf=o.lazy(async()=>({default:(await zt(()=>import("./BDMstdfu.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))).MissionControlView})),jf=o.lazy(async()=>({default:(await zt(()=>import("./Dlz0Cm_E.js"),__vite__mapDeps([9,1,2,3,4,10,7]))).SessionInspector})),Nf=o.lazy(async()=>({default:(await zt(()=>import("./BdusVDcP.js"),__vite__mapDeps([11,1,2,3,4,8,7,10]))).DecisionQueue})),If=o.lazy(()=>zt(()=>import("./CL_wXqR7.js"),__vite__mapDeps([12,1,2,3,4,7])).then(e=>({default:e.TriageQueue}))),Af=o.lazy(()=>zt(()=>import("./BTAEErUY.js"),__vite__mapDeps([13,1,2,3,4,7])).then(e=>({default:e.TriageDetailModal}))),Sf=o.lazy(async()=>({default:(await zt(()=>import("./bxgRC96y.js").then(t=>t.a),__vite__mapDeps([5,1,2,3,4,6,7]))).NextUpPanel})),_f=o.lazy(async()=>({default:(await zt(()=>import("./DHtZPEKd.js"),__vite__mapDeps([14,1,2,3,4,7]))).SettingsModal})),Cf=o.lazy(async()=>({default:(await zt(()=>import("./BwkNYH6r.js"),__vite__mapDeps([15,1,2,3,4,7]))).BulkSessionsModal})),Mf=o.lazy(async()=>({default:(await zt(()=>import("./DUaqjbT7.js"),__vite__mapDeps([16,1,2,3,4,11,8,7,10]))).BulkDecisionsModal})),Tf=o.lazy(async()=>({default:(await zt(()=>import("./B1mDqDdy.js"),__vite__mapDeps([17,1,2,3,4,7]))).BulkOutboxModal})),Ef=o.lazy(async()=>({default:(await zt(()=>import("./BXapfumA.js"),__vite__mapDeps([18,1,2,3,4,7]))).BulkHandoffsModal})),Lf=o.lazy(async()=>({default:(await zt(()=>import("./CRhvoVeH.js"),__vite__mapDeps([19,1,2,3,4,6,7]))).ArtifactViewerModal})),Df=o.lazy(async()=>({default:(await zt(()=>import("./VH0fzk6I.js"),__vite__mapDeps([20,1,2,3,4,8,7]))).SliceDetailModal})),Rf=o.lazy(async()=>({default:(await zt(()=>import("./E8q3xNGK.js"),__vite__mapDeps([21,1,2,3,4,7]))).RealtimeOrchestratorModal})),$o={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},$f={connected:E.lime,reconnecting:E.amber,disconnected:E.red},Hi="orgx.demo_mode",Ki="orgx.dev_mode",Vi="orgx.show_synthetic_entities",aa="orgx.selected_workspace_id",Fo={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Po=new Set(["running","active","queued","pending","in_progress","working","planning"]),Ff=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function dn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Pf(e){const t=dn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Of(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 Bf(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:Of(e),action:"settings"}}function Gi(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 qf(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 Oo(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Bo(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 Xi(e,t){const s=Fo[e.status]??99,r=Fo[t.status]??99;return s!==r?s-r:dn(e.updatedAt??e.lastEventAt??e.startedAt)-dn(t.updatedAt??t.lastEventAt??t.startedAt)}function qo(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 zf(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 Wf(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Uf(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Hf(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Kf(e){return Ff.test(e)}function qr(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 Vf(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Gf(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Xf(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 Qf(e,t){hs(e,t)}function Jf(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 Yf(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Xf(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(aa);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function Zf(){const e=ad();return e.showGate?n.jsx(Yd,{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(em,{children:n.jsx(rh,{onboarding:e})})}function eh(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 th(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 zo(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 Wo(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function nh(){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:li,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function sh(){const{state:e}=fl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Lf,{})}):null}function rh({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(Hi)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Vi)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ki)==="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,g]=o.useState(()=>Yf()),y=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:v=[]}=fs({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const m=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!m.ok)return[];const A=await m.json().catch(()=>null),L=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const G of L){if(!G||typeof G!="object"||Array.isArray(G))continue;const _e=qr(G,["id"]);if(!_e)continue;const st=qr(G,["status","priority"]);if(!Vf(st))continue;const Ue=qr(G,["title","name"])??(_e.length>10?`${_e.slice(0,8)}…`:_e),Be=G.is_default===!0,dt=Gf({title:Ue,isDefault:Be}),St=qr(G,["created_at"]);S.push({id:_e,title:dt,status:st,isDefault:Be,createdAt:St})}return S.sort((G,_e)=>{if(G.isDefault!==_e.isDefault)return G.isDefault?-1:1;const st=dn(G.createdAt)-dn(_e.createdAt);return st!==0?st:G.title.localeCompare(_e.title)}),S},staleTime:6e4}),f=o.useMemo(()=>{var m;return u?((m=v.find(A=>A.id===u))==null?void 0:m.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,v]),k=o.useMemo(()=>!u||v.some(m=>m.id===u)?v:[{id:u,title:f,status:null,isDefault:!1,createdAt:null},...v],[u,f,v]);o.useEffect(()=>{u&&v.length!==0&&(v.some(m=>m.id===u)||g(null))},[u,v]),t||e.state.hasApiKey&&e.state.connectionVerified;const x=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:j,isLoading:w,error:b,refetch:h,approveDecision:_,rejectDecision:U,approveAllDecisions:le,bulkDecisionAction:V,decisionMutation:be}=Lc({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...x}),H=t||r,Z=o.useMemo(()=>H?j.sessions.nodes:j.sessions.nodes.filter(m=>!Wf(m)),[j.sessions.nodes,H]),ce=o.useMemo(()=>j.activity.filter(m=>!(!H&&Uf(m)||!a&&Hf(m))),[j.activity,H,a]),xe=j.connection==="connected"||j.decisions.length>0,[we,K]=o.useState(null),[Ie,Ee]=o.useState(!1),[fe,ee]=o.useState(null),[re,Le]=o.useState(null),[ne,R]=o.useState(null),[J,P]=o.useState(null),[Y,oe]=o.useState("live"),[ve,je]=o.useState({startIso:null,endIso:null}),te=o.useRef(new Set),[Te,pe]=o.useState(null),[C,O]=o.useState(null),[W,se]=o.useState(null),[De,qe]=o.useState(null),Me=o.useRef(null),M=o.useCallback(m=>{Me.current&&clearTimeout(Me.current),qe(m),Me.current=setTimeout(()=>qe(null),4e3)},[]),[q,ie]=o.useState(!1),[de,Ce]=o.useState(!1),[Ze,Je]=o.useState([]),Fe=o.useRef(null),Ge=o.useRef(null),[He,ft]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[it,at]=o.useState(!1),[he,Ke]=o.useState(null),[Ae,B]=o.useState("agents"),[Pe,z]=o.useState("initiatives"),[Q,Ne]=o.useState("next_up"),Re=o.useCallback(m=>{if(B(m),m==="initiatives"){z("initiatives"),Ne("next_up");return}m==="decisions"&&(z("initiatives"),Ne("in_progress"),Oe("needs_attention"))},[]),[$e,Oe]=o.useState("all"),Se=o.useMemo(()=>Array.isArray(j.sliceRuns)?j.sliceRuns:[],[j.sliceRuns]),lt=o.useMemo(()=>dl({sessions:Z,sliceRuns:Se}),[Se,Z]).length,ze=o.useMemo(()=>ul(Se),[Se]),Tt=ze.length+(xe?j.decisions.length:0),[et,kt]=o.useState(null),Jt=o.useCallback(m=>{const A=Se.find(L=>L.initiativeId===m.initiativeId&&L.workstreamId===m.workstreamId)??null;kt({source:"queue",item:m,linkedSliceRun:A})},[Se]),Gt=o.useCallback((m,A)=>{kt({source:"in_progress",row:m,sliceRun:A})},[]),un=o.useCallback(m=>{kt({source:"needs_input",sliceRun:m})},[]),An=o.useCallback(async(m,A)=>{M("Slice accepted and marked complete."),h()},[h,M]),gs=o.useCallback(async(m,A)=>{M("Changes requested — feedback posted.")},[M]),ht=el({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:j.snapshotVersion}),Wt=jd({authToken:null,embedMode:!1}),{model:Sn,actions:Qn}=Ad({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Ct=o.useMemo(()=>Sn.items.filter(m=>m.kind==="failure_diagnostic"),[Sn.items]),Ft=o.useMemo(()=>({...Sn,items:Ct,total:Ct.length}),[Ct,Sn]),[Ut,gt]=o.useState(null),[Xt,Jn]=o.useState(0),Yn=o.useCallback(m=>{gt(m);const A=Ct.findIndex(L=>L.id===m.id);Jn(A>=0?A:0)},[Ct]),xs=o.useCallback(m=>{if(Ct.length===0)return;const A=(Xt+m+Ct.length)%Ct.length;Jn(A),gt(Ct[A]??null)},[Xt,Ct]),_n=ht,Yt=o.useMemo(()=>ht.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[ht.items]),mn=!!Yt;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(Hi,"1"):window.localStorage.removeItem(Hi)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(Vi,"1"):window.localStorage.removeItem(Vi)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(Ki,"1"):window.localStorage.removeItem(Ki)}catch{}},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(aa,u):window.localStorage.removeItem(aa)}catch{}try{const m=new URL(window.location.href);u?Qf(m.searchParams,u):Jf(m.searchParams),m.searchParams.delete("initiative"),m.searchParams.delete("initiative_id"),m.searchParams.delete("project"),window.history.replaceState(null,"",`${m.pathname}${m.search}${m.hash}`)}catch{}}},[u]);const Ht=o.useCallback((m,A)=>{ft(L=>({open:!0,tab:m??L.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),Pn=o.useCallback(m=>{if(s(m),!(typeof window>"u"))try{const A=new URL(window.location.href);m?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),bn=o.useCallback(()=>{Ht("orgx")},[Ht]),Zn=o.useCallback(()=>{zt(()=>import("./BDMstdfu.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))},[]),{data:es}=ml(l==="mission-control",u),{data:Cn}=Zu(l==="mission-control",u),{data:ts=[]}=fs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[It,Mn]=o.useState(null),[wn,Tn]=o.useState(""),[Zt,T]=o.useState(!1),ue=o.useCallback((m,A)=>{Mn({type:m,initiativeId:A}),Tn(""),T(!1)},[]),X=o.useCallback(()=>{Mn(null),Tn(""),T(!1)},[]),ge=o.useCallback(()=>{Le(null)},[]),Xe=o.useCallback(()=>{R(null),P(null)},[]),Et=o.useCallback(()=>{se(null)},[]);o.useEffect(()=>{var L;const m=((L=Z[0])==null?void 0:L.id)??null;if(!m){we!==null&&K(null);return}if(we===null){K(m);return}Z.some(S=>S.id===we)||K(m)},[Z,we]),o.useEffect(()=>{if(!re)return;Z.some(A=>A.id===re)||Le(null)},[re,Z]);const Qe=o.useCallback(m=>{zt(()=>import("./Dlz0Cm_E.js"),__vite__mapDeps([9,1,2,3,4,10,7])),K(m),Ee(!0),ee(null),Le(m),R(null),P(null)},[]),ys=o.useCallback(m=>{zt(()=>import("./Dlz0Cm_E.js"),__vite__mapDeps([9,1,2,3,4,10,7])),K(m.id),Ee(!0),Le(m.id),R(m.workstreamId??null),P(m.title),ee({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),M(`Opened intervention composer for ${m.title}.`)},[]),Ot=o.useCallback(m=>{const A=m.trim();if(!A)return;const L=Z.find(S=>S.runId===A||S.id===A)??null;L&&(Qe(L.id),M(`Focused session: ${L.title}`))},[Z,Qe]),Kt=o.useCallback(m=>{var S;const A=(S=m.id)==null?void 0:S.trim();if(!A)return;const L=Gi(m);if(L){const G=Z.find(_e=>_e.runId===L||_e.id===L)??null;G&&(K(G.id),Le(G.id))}y("activity"),B("activity"),Ee(!1),pe(A),M("Opened activity detail from session timeline.")},[Z,y]),jt=o.useMemo(()=>Z.find(m=>m.id===re)??null,[re,Z]),ut=o.useMemo(()=>{var L,S;const m=((L=jt==null?void 0:jt.runId)==null?void 0:L.trim())??"",A=((S=jt==null?void 0:jt.id)==null?void 0:S.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[jt==null?void 0:jt.id,jt==null?void 0:jt.runId]),On=o.useMemo(()=>{const m=new Set;for(const A of ut){const L=A.trim();L.length>0&&m.add(L)}return m},[ut]),ns=o.useMemo(()=>{const m=new Map;for(const A of Z){const L=A.workstreamId??null;A.runId&&m.set(A.runId,L),A.id&&m.set(A.id,L)}return m},[Z]),wt=o.useMemo(()=>{const m=ut.length>0?ut.join("|"):"*",A=(ne==null?void 0:ne.trim())||"*",L=(W==null?void 0:W.trim())||"*";return`${m}::${A}::${L}`},[ne,W,ut]),Bn=o.useCallback(m=>{te.current.add(wt),oe(m)},[wt]);o.useEffect(()=>{if(te.current.has(wt)||w)return;const m=Date.now(),A=ce.filter(G=>{const _e=Gi(G);if(On.size>0&&(!_e||!On.has(_e)))return!1;if(ne){const st=Oo(G);if((Bo(st,["workstreamId","workstream_id"])??(_e?ns.get(_e)??null:null))!==ne)return!1}if(W){const st=Oo(G);if((Bo(st,["agentName","agent_name"])??G.agentName)!==W)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(G=>{const _e=yr(G,m);return A.some(st=>{const Ue=dn(st.timestamp);return Ue?_e===null||Ue>=_e:!1})})??"all";te.current.add(wt),S!==Y&&oe(S)},[ne,ce,wt,Y,ns,W,w,On]);const vn=Uc({seed:ce,timeFilterId:Y,customSinceIso:Y==="custom"?ve.startIso:null,customUntilIso:Y==="custom"?ve.endIso:null,runId:(jt==null?void 0:jt.runId)??null,projectId:u,pageSize:50,demoMode:t}),At=o.useMemo(()=>Z.find(m=>m.id===we)??null,[Z,we]),En=o.useMemo(()=>Z.filter(m=>Po.has(m.status)).length,[Z]),ss=o.useMemo(()=>Se.length>0?ze.length:Z.filter(m=>{const A=qt(m.status),L=qt(m.phase??""),S=qt(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||L==="blocked"||S==="error"?!0:Po.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[Se.length,ze.length,Z]);o.useMemo(()=>Z.filter(m=>m.status==="failed").length,[Z]);const bs=o.useMemo(()=>Z.filter(m=>m.status==="completed").length,[Z]);o.useMemo(()=>{const m=(xe?j.decisions.length:0)+ss;return[{id:"active",label:"Running",value:En,color:En>0?E.lime:E.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?E.amber:E.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:bs,color:E.teal,icon:"session"}]},[En,ss,bs,j.decisions.length,Z,xe]),o.useMemo(()=>j.decisions.length>0?Math.max(0,...j.decisions.map(m=>m.waitingMinutes)):0,[j.decisions]);const Ln=o.useMemo(()=>b?Bf(b):null,[b]),rs=o.useMemo(()=>{const m=[];if(Ln){const A=Ln.action==="refresh"&&typeof h=="function";m.push({id:`stream-error:${b}`,kind:"error",icon:"notification",title:Ln.title,message:Ln.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void h():()=>Ht("orgx")})}return j.connection!=="connected"&&m.push({id:`connection:${j.connection}`,kind:j.connection==="disconnected"?"error":"info",icon:"notification",title:j.connection==="disconnected"?"Connection lost":"Reconnecting",message:j.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:bn}),De&&m.push({id:`ops:${De}`,kind:"info",icon:/decision/i.test(De)?"decision":"workstream",title:"Update",message:De}),m},[j.connection,j.outbox.lastReplayError,j.outbox.pendingTotal,j.outbox.replayStatus,b,Ln,bn,h,Ht,De]);o.useEffect(()=>{const m=new Set(rs.map(A=>A.id));Je(A=>A.filter(L=>m.has(L)))},[rs]);const ws=o.useMemo(()=>rs.filter(m=>!Ze.includes(m.id)),[Ze,rs]),Ls=xe?j.decisions.length:0,Ds=En+ss+Ls,br=o.useCallback(m=>{Je(A=>A.includes(m)?A:A.concat(m))},[]),wr=o.useCallback(()=>{Je(rs.map(m=>m.id))},[rs]);o.useEffect(()=>{if(!de)return;const m=L=>{var G,_e;const S=L.target;S&&((G=Ge.current)!=null&&G.contains(S)||(_e=Fe.current)!=null&&_e.contains(S)||Ce(!1))},A=L=>{L.key==="Escape"&&Ce(!1)};return document.addEventListener("mousedown",m),document.addEventListener("touchstart",m),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("touchstart",m),document.removeEventListener("keydown",A)}},[de]);const Lt=o.useMemo(()=>{var L;const m=new Map;for(const S of Z){const G=S.initiativeId??S.groupId??"unscoped",_e=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",st=eh(_e),Ue=m.get(G)??{id:G,name:_e,category:st,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(S.progress!==null&&(Ue.progressTotal+=S.progress,Ue.progressCount+=1),Ue.statusCounts[S.status]=(Ue.statusCounts[S.status]??0)+1,S.agentName&&(Ue.allAgents.add(S.agentName),["running","queued","pending","blocked"].includes(S.status)&&Ue.activeAgents.add(S.agentName)),S.workstreamId){const Be=j.sessions.groups.find(St=>St.id===S.workstreamId),dt=((L=Be==null?void 0:Be.label)==null?void 0:L.trim())||S.workstreamId;Ue.workstreams.set(S.workstreamId,dt)}Ue.latestEpoch=Math.max(Ue.latestEpoch,dn(S.updatedAt??S.lastEventAt??S.startedAt)),m.set(G,Ue)}const A=[];for(const S of m.values()){const G=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,_e=S.category,st=th(_e),Ue=Math.round(Math.max(0,Math.min(100,G))/100*(st.length-1)),Be=(S.statusCounts.blocked??0)>0,dt=(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,St=!dt&&!Be&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,jr=st.map((rn,$n)=>{let os="upcoming";return(dt||$n<Ue)&&(os="completed"),$n===Ue&&!dt&&(os=Be?"warning":"current"),{name:rn,status:os}});A.push({id:S.id,name:S.name,status:dt?"completed":Be?"blocked":St?"paused":"active",rawStatus:dt?"completed":Be?"blocked":St?"paused":"active",category:_e,health:Math.max(0,Math.min(100,G)),phases:jr,currentPhase:dt?st.length-1:Ue,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(([rn,$n])=>({id:rn,name:$n,status:"active"}))})}return A.sort((S,G)=>{const _e=S.status==="blocked"?0:S.status==="active"?1:2,st=G.status==="blocked"?0:G.status==="active"?1:2;return _e!==st?_e-st:G.health-S.health})},[Z,j.sessions.groups]),D=o.useMemo(()=>{const m=(S,G)=>{var _e,st;return{...S,...G,health:G.health>0?G.health:S.health,activeAgents:Math.max(S.activeAgents,G.activeAgents),totalAgents:Math.max(S.totalAgents,G.totalAgents),avatars:(_e=S.avatars)!=null&&_e.length?S.avatars:G.avatars,workstreams:(st=S.workstreams)!=null&&st.length?S.workstreams:G.workstreams,description:S.description??G.description,rawStatus:G.rawStatus??S.rawStatus??null,targetDate:G.targetDate??S.targetDate??null,createdAt:G.createdAt??S.createdAt??null,updatedAt:G.updatedAt??S.updatedAt??null}},A=new Map;for(const S of Lt)A.set(S.id,S);for(const S of[...Cn??[],...es??[]]){if(!H&&Es(S.id)){A.delete(S.id);continue}const G=S.rawStatus??S.status;if(!Wo(G)){A.delete(S.id);continue}const _e=A.get(S.id);A.set(S.id,_e?m(_e,S):S)}const L=new Set(ts);return Array.from(A.values()).filter(S=>!L.has(S.id)).filter(S=>Wo(S.rawStatus??S.status)).sort((S,G)=>{const _e=St=>St==="blocked"?0:St==="active"?1:St==="paused"?2:3,st=_e(S.status)-_e(G.status);if(st!==0)return st;const Ue=zo(S.priority)-zo(G.priority);if(Ue!==0)return Ue;const Be=dn(G.updatedAt)-dn(S.updatedAt);if(Be!==0)return Be;const dt=G.health-S.health;return dt!==0?dt:S.name.localeCompare(G.name)})},[Lt,es,H,Cn,ts]),vr=o.useMemo(()=>{if(!jt)return null;const m=jt.agentName,A=jt.title;if(m){const L=ce.find(S=>{var G;return S.runId===jt.runId&&((G=S.summary)==null?void 0:G.trim())});if(L!=null&&L.summary){const S=L.summary.trim().length>40?L.summary.trim().slice(0,40)+"…":L.summary.trim();return`${m}: ${S}`}return m}if(A){const L=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(L.length>0)return L}return A??null},[ce,jt]),qn=o.useMemo(()=>{const m=new Map;for(const A of Z){const L=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const G=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),_e=dn(G),st=_e?Math.max(0,Math.floor((Date.now()-_e)/6e4)):0,Ue=m.get(L),Be={id:L,name:S,role:"Agent",status:zf(A.status),task:A.title??null,progress:A.progress??null,lastActive:G,lastActiveMinutes:st};(!Ue||dn(Be.lastActive)>dn(Ue.lastActive))&&m.set(L,Be)}return Array.from(m.values())},[Z]),zn=o.useCallback(async()=>{if(Z.length===0){M("No sessions available to continue.");return}const m=[...Z].sort(Xi)[0];if(K(m.id),Le(m.id),R(null),P(null),["blocked","pending","queued"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}M(`Focused highest priority session: ${m.title}`),await h()},[Z,h]),pn=o.useCallback(async(m,A)=>{const L=await m.json().catch(()=>null),S=typeof(L==null?void 0:L.error)=="string"&&L.error.trim()||typeof(L==null?void 0:L.message)=="string"&&L.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:In(S)},[]),Dn=o.useCallback((m,A)=>!m||m.trim().length===0?A:In(m.trim())||A,[]),is=o.useCallback(async()=>{const m=qo(ht.items);if(!m){M("No startable Next Up workstream is available."),y("mission-control");return}await ht.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),Le(null),R(m.workstreamId),P(m.workstreamTitle),se(null),M(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([ht.refetch(),h()])},[h,ht,y]),We=o.useCallback(async()=>{const m=qo(ht.items);if(!m){M("No startable initiative is ready for Autopilot yet."),y("mission-control");return}await Wt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await ht.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),Le(null),R(m.workstreamId),P(m.workstreamTitle),se(null),M(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([ht.refetch(),h()])},[h,Wt,ht,y]),Rn=o.useCallback(async()=>{ie(!0);try{if(!Yt){await We();return}await ht.stopInitiativeAutoContinue({initiativeId:Yt.initiativeId}),M(`Autopilot stopped for ${Yt.initiativeTitle}.`),await Promise.all([ht.refetch(),h()])}finally{ie(!1)}},[Yt,h,ht,We]),ae=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),L=(m.workstreamId??"").trim();if(!A||!L)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:L,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await pn(S,"Failed to dispatch workstream from In Progress"));Le(null),R(L),P(m.title),M(`Dispatched ${m.title}.`),await Promise.all([ht.refetch(),h()])},[pn,h,ht]),Xs=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),L=(m.workstreamId??"").trim();if(!A||!L)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:L,placement:"bottom",resetToTodo:!1})});if(!S.ok){const G=await pn(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(G))throw new Error(G);const _e=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!_e.ok)throw new Error(await pn(_e,"Failed to pause workstream using legacy fallback"))}M(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([ht.refetch(),h()])},[pn,h,ht]),as=o.useCallback(async m=>{const A=(m.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const L=m.text.trim();if(Kf(L)){Ht("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:L,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!S.ok)throw new Error(await pn(S,"Failed to submit intervention"));M(`Intervention sent for ${m.session.title}.`),await h()},[Ht,pn,h]),Qs=o.useCallback(async m=>{if(K(m.id),Le(m.id),R(null),P(null),!["running","completed","archived"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}M(`Dispatch requested: ${m.title}`),await h()},[h]),en=o.useCallback(async(m,A,L={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!S.ok){const G=await S.json().catch(()=>null);throw new Error((G==null?void 0:G.error)??`${A} failed (${S.status})`)}},[]),tn=o.useCallback(async m=>{var G;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const _e=await A.json().catch(()=>null);throw new Error((_e==null?void 0:_e.error)??`Checkpoint creation failed (${A.status})`)}const L=await A.json().catch(()=>null),S=L&&"data"in L&&((G=L.data)==null?void 0:G.id)||L&&"id"in L&&L.id||null;M(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await h()},[h]),$=o.useCallback(async m=>{await en(m,"pause",{reason:"pause_from_dashboard"}),M(`Pause requested: ${m.title}`),await h()},[h,en]),Dt=o.useCallback(async m=>{await en(m,"resume",{reason:"resume_from_dashboard"}),M(`Resume requested: ${m.title}`),await h()},[h,en]),kr=o.useCallback(async m=>{await en(m,"cancel",{reason:"restart_from_in_progress"}),await ae(m),M(`Restarted ${m.title}.`),await h()},[ae,h,en]),Rs=o.useCallback(async m=>{await en(m,"cancel",{reason:"cancel_from_dashboard"}),M(`Cancel requested: ${m.title}`),await h()},[h,en]),ui=o.useCallback(async m=>{var st;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Ue=await A.json().catch(()=>null);throw new Error((Ue==null?void 0:Ue.error)??`Checkpoint list failed (${A.status})`)}const L=await A.json().catch(()=>null),_e=(st=(Array.isArray(L)?L:Array.isArray(L==null?void 0:L.data)?L.data:[]).map(Ue=>({id:typeof Ue.id=="string"?Ue.id:"",createdAt:typeof Ue.createdAt=="string"?Ue.createdAt:typeof Ue.created_at=="string"?Ue.created_at:""})).filter(Ue=>Ue.id.length>0).sort((Ue,Be)=>Date.parse(Be.createdAt)-Date.parse(Ue.createdAt))[0])==null?void 0:st.id;if(!_e)throw new Error("No checkpoint available for rollback.");await en(m,"rollback",{checkpointId:_e,reason:"rollback_from_dashboard"}),M(`Rollback requested for ${m.title}.`),await h()},[h,en]),Js=o.useCallback(async()=>{var L;if(!It||wn.trim().length===0||Zt)return;T(!0);const m=It.type,A=wn.trim();try{const S={type:m,title:A,status:"active"};if(m==="workstream"){const _e=It.initiativeId??(At==null?void 0:At.initiativeId)??((L=Lt[0])==null?void 0:L.id)??null;if(!_e){M("Select an initiative first to start a workstream."),T(!1);return}S.initiative_id=_e,S.parentId=_e}const G=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!G.ok){const _e=await G.json().catch(()=>null);throw new Error((_e==null?void 0:_e.error)??`Failed to create ${m}.`)}M(`Created ${m}: ${A}`),X(),await h()}catch(S){M(Dn(S instanceof Error?S.message:"",`Failed to create ${m}.`)),T(!1)}},[X,Zt,It,wn,Lt,h,At==null?void 0:At.initiativeId]),vs=o.useCallback(()=>{ue("initiative")},[ue]),nt=o.useCallback(m=>{ue("workstream",m)},[ue]);o.useCallback(()=>{var m;return nt((At==null?void 0:At.initiativeId)??((m=Lt[0])==null?void 0:m.id)??null)},[Lt,At==null?void 0:At.initiativeId,nt]);const Ys=o.useCallback(m=>{const A=[...Z].filter(L=>(L.initiativeId??L.groupId)===m.id).sort(Xi)[0];A&&(K(A.id),Le(A.id),R(null),P(null),M(`Focused initiative: ${m.name}`))},[Z]),xt=o.useCallback(m=>{const A=Lt.find(L=>L.id===m)??D.find(L=>L.id===m)??null;A&&Ys(A)},[Ys,Lt,D]),Wn=o.useCallback(m=>{const A=(m??"").trim();y("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention"),O(A.length>0?A:null),M(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[y]),Zs=o.useCallback(m=>{const A=new Set,L=(m.runId??"").trim();L.length>0&&A.add(L),A.add(m.sliceRunId);const S=new Map;for(const Be of ce){const dt=Gi(Be),St=qf(Be);(dt&&A.has(dt)||St&&St===m.sliceRunId)&&S.set(Be.id,Be)}const G=Array.from(S.values()),_e=Be=>{const dt=Be.type.trim().toLowerCase();let St=0;return(dt==="decision_requested"||dt==="blocker_created")&&(St+=80),(dt==="run_failed"||dt==="autopilot_stopped")&&(St+=70),(dt.includes("slice_completed")||dt.includes("completed"))&&(St+=60),dt.includes("artifact")&&(St+=55),(dt.includes("progress")||dt.includes("update"))&&(St+=35),St+=Math.floor(dn(Be.timestamp)/1e3),St};G.sort((Be,dt)=>_e(dt)-_e(Be));const st=G[0]??null;y("activity"),B("activity"),z("initiatives");const Ue=(L?Z.find(Be=>Be.runId===L||Be.id===L)??null:null)??(m.initiativeId&&m.workstreamId?Z.find(Be=>Be.initiativeId===m.initiativeId&&Be.workstreamId===m.workstreamId)??null:null);if(Ue?(K(Ue.id),Le(Ue.id),R(null),P(null)):m.workstreamId&&(Le(null),R(m.workstreamId),P(m.workstreamTitle??"Work slice")),st!=null&&st.id){pe(st.id),M(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){Wn();return}if(L.length>0){Ot(L),M("Opened the related work session. Timeline details were unavailable.");return}M("No activity details were found for this slice yet.")},[ce,Ot,Wn,Z,y]);return o.useCallback(m=>{const A=new Set(m),L=[...Z].filter(S=>A.has(S.status)).sort(Xi)[0];if(!L){M("No matching sessions for that metric right now.");return}Qe(L.id),B("activity")},[Z,Qe]),o.useCallback(m=>{l==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&Ke(m)},[l]),w?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:E.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((m,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor:E.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(nh,{}),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(Zd,{color:$f[j.connection],pulse:j.connection==="connected",title:[`Status: ${$o[j.connection]??j.connection}`,j.connection==="connected"?"Meaning: receiving live updates.":j.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${Pf(j.lastSnapshotAt)}`,Ln?`Details: ${Ln.message}`:null].filter(Boolean).join(`
212
+ `),children:$o[j.connection]??"Unknown"}),(En>0||ss>0)&&n.jsx(uo,{className:"hidden md:flex",running:En,blocked:ss,decisionsCount:xe?j.decisions.length:0,completedToday:bs,onDecisionsClick:()=>{y("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention")},onBlockedClick:()=>{Se.length>0?(y("mission-control"),Ne("in_progress"),Oe("needs_attention")):Ke("blocked")},onNewInitiative:vs})]}),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:Zn,onFocus:Zn,"aria-pressed":l==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:m=>{const A=m.target.value;g(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(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),j.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",j.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Pn(!1),bn()},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:Fe,onClick:()=>Ce(m=>!m),title:"Notifications","aria-haspopup":"dialog","aria-expanded":de,"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"})]}),ws.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:ws.length})]}),n.jsx("button",{type:"button",onClick:()=>at(!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:()=>Ht("orgx"),title:"Settings",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"}),n.jsx("path",{d:"M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.2 2.2 0 0 1-1.56 3.76 2.2 2.2 0 0 1-1.56-.64l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.1 1.63V22a2.2 2.2 0 0 1-4.4 0v-.07a1.8 1.8 0 0 0-1.1-1.63 1.8 1.8 0 0 0-2 .36l-.05.05a2.2 2.2 0 1 1-3.12-3.12l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.63-1.1H2a2.2 2.2 0 0 1 0-4.4h.07a1.8 1.8 0 0 0 1.63-1.1 1.8 1.8 0 0 0-.36-2l-.05-.05a2.2 2.2 0 1 1 3.12-3.12l.05.05a1.8 1.8 0 0 0 2 .36 1.8 1.8 0 0 0 1.1-1.63V2a2.2 2.2 0 0 1 4.4 0v.07a1.8 1.8 0 0 0 1.1 1.63 1.8 1.8 0 0 0 2-.36l.05-.05a2.2 2.2 0 0 1 3.12 3.12l-.05.05a1.8 1.8 0 0 0-.36 2 1.8 1.8 0 0 0 1.63 1.1H22a2.2 2.2 0 0 1 0 4.4h-.07a1.8 1.8 0 0 0-1.63 1.1z"})]})}),n.jsxs("button",{type:"button",onClick:h,className:"group inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-body text-primary transition-colors hover:bg-white/[0.08] sm:w-auto sm:gap-1.5 sm:px-3",title:"Refresh data",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"transition-transform group-hover:rotate-45",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),de&&n.jsxs("div",{id:"header-notifications-panel",ref:Ge,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:[ws.length>0&&n.jsx("button",{type:"button",onClick:wr,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Ce(!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(uo,{className:"max-w-full overflow-hidden",running:En,blocked:ss,decisionsCount:Ls,completedToday:bs,onDecisionsClick:()=>{y("activity"),B("initiatives"),z("initiatives"),Ne("in_progress"),Oe("needs_attention"),Ce(!1)},onBlockedClick:()=>{Se.length>0?(y("mission-control"),Ne("in_progress"),Oe("needs_attention")):Ke("blocked"),Ce(!1)}})}),ws.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:ws.map(m=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:m.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:m.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:m.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(yn,{type:m.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:m.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:m.message}),m.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=m.onAction)==null||A.call(m),Ce(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:m.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>br(m.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},m.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:m=>{const A=m.target.value;g(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(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>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(kf,{initiatives:D,activities:ce,agents:qn,runtimeInstances:j.runtimeInstances??[],workspaceInitiativeId:u,isLoading:w,authToken:null,embedMode:!1,connection:j.connection,lastSnapshotAt:j.lastSnapshotAt,error:b,hasApiKey:e.state.hasApiKey,onOpenSettings:()=>Ht("orgx"),onRefresh:h,onCreateInitiative:vs,onPlayNextUp:is,onStartAutopilot:We,nextUpQueueModel:ht,nextUpActionsModel:Wt,snapshotVersion:j.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 ${Ae!=="agents"?"hidden lg:flex":""}`,children:n.jsx(Om,{sessions:j.sessions,activity:ce,runtimeInstances:j.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:we,onSelectSession:Qe,onAgentFilter:se,agentFilter:W,timeFilterId:Y,onReconnect:bn,onLaunched:h,connectionStatus:j.connection})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${Ae!=="activity"?"hidden lg:flex":""}`,children:n.jsx(vf,{activity:vn.items,sessions:Z,sliceRuns:Se,initiatives:Lt,timelineNarrative:j.timelineNarrative??[],workspaceId:u,chatSnapshot:j.chat,selectedRunIds:ut,selectedSessionLabel:vr,selectedWorkstreamId:ne,selectedWorkstreamLabel:J,agentFilter:W,timeFilterId:Y,onTimeFilterChange:Bn,customTimeRange:ve,onCustomTimeRangeChange:je,hasMore:vn.hasMore,isLoadingMore:vn.isLoadingMore,onLoadMore:vn.loadMore,onClearSelection:ge,onClearWorkstreamFilter:Xe,onClearAgentFilter:Et,onFocusRunId:Ot,onOpenDecision:Wn,requestedActivityItemId:Te,onActivityItemRequestHandled:()=>pe(null),onPlayNextUp:is,onStartAutopilot:We,onPauseWorkstream:Xs,onCreateInitiative:vs,onOpenMissionControl:()=>y("mission-control"),onOpenNextUp:()=>y("mission-control"),onOpenSettings:()=>Ht("orgx"),onRefreshData:h,isLoading:w})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${Ae!=="decisions"&&Ae!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${Pe==="initiatives"?"flex-1":"flex-shrink-0"} `,children:Pe==="initiatives"?n.jsxs(Hs,{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":Q==="in_progress",onClick:m=>{m.stopPropagation(),Ne("in_progress")},className:me("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Q==="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:lt}),n.jsx("span",{className:me("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Q==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":Q==="next_up",onClick:m=>{m.stopPropagation(),Ne("next_up")},className:me("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Q==="next_up"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"Next Up"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:_n.total}),n.jsx("span",{className:me("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Q==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{Rn().catch(m=>{M(Dn(m instanceof Error?m.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":mn?"active":"idle",title:mn?"Stop autopilot":"Start autopilot","aria-label":mn?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:me("h-3.5 w-3.5",mn?"animate-pulse":""),"aria-hidden":!0,children:n.jsx("path",{d:"M6.1 13.25C4.25 13.25 2.8 11.8 2.8 10s1.45-3.25 3.3-3.25c3.15 0 4.35 6.5 8.05 6.5 1.85 0 3.3-1.45 3.3-3.25s-1.45-3.25-3.3-3.25c-3.7 0-4.9 6.5-8.05 6.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n.jsx("span",{className:"text-micro uppercase tracking-[0.12em]",children:"Auto"}),n.jsx("span",{className:me("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",mn?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:mn?"On":"Off"})]})]}),Q==="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:me("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",$e==="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:lt})]}),n.jsxs("button",{type:"button",onClick:()=>Oe("needs_attention"),className:me("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",$e==="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:Tt})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Q==="in_progress"?$e==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Ft.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(If,{model:Ft,actions:Qn,onOpenDetail:Yn})})}),xe?n.jsxs("section",{className:me("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",ze.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:j.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(Nf,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:j.decisions,focusDecisionId:C,onFocusDecisionHandled:()=>O(null),onApproveDecision:_,onRejectDecision:U,onApproveAll:le,onBulkDecisionAction:V,mutationState:be})})})]}):n.jsx(Hs,{className:"border border-subtle bg-white/[0.02] px-4 py-3 text-body text-secondary",children:"OrgX is not connected. Decision actions are hidden until connectivity returns."}),n.jsxs("section",{className:me("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:xe?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:ze.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(zu,{className:me("h-full min-h-0"),title:xe?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Se,initiatives:Lt,onOpenDecisions:()=>Wn(),onFocusRunId:Ot,onReviewActivity:Zs,onOpenSliceDetail:un})})]})]}):n.jsx(Eu,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:Z,sliceRuns:Se,initiatives:Lt,needsAttentionCount:Tt,onSwitchToNeedsAttention:()=>Oe("needs_attention"),onOpenSession:Qe,onFocusRunId:Ot,onPlayWorkstream:ae,onPauseWorkstream:Xs,onResumeWorkstream:ae,onRestartSession:kr,onIntervene:ys,onOpenSliceDetail:Gt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Sf,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:ht,queueActions:Wt,snapshotVersion:j.snapshotVersion,onOpenInitiative:xt,onOpenSliceDetail:Jt})})},`${Q}:${$e}`)]}):n.jsx(Hs,{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(bt,{children:Ie&&At&&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:()=>Ee(!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:E.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:()=>Ee(!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(jf,{session:At,activity:ce,initiatives:Lt,sliceRuns:Se,initialInterventionDraft:fe,onSubmitIntervention:as,onOpenActivityItem:Kt,onContinueHighestPriority:zn,onDispatchSession:Qs,onPauseSession:$,onResumeSession:Dt,onCancelSession:Rs,onCreateCheckpoint:tn,onRollbackSession:ui,onStartInitiative:vs,onStartWorkstream:nt})})})]},"session-drawer-panel")]})}),l==="activity"?n.jsx(tu,{activeTab:Ae,onTabChange:Re,pendingDecisionCount:xe?j.decisions.length:0}):null,n.jsx(ci,{open:It!==null,onClose:X,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:wn,onChange:m=>Tn(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Js()},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:X,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:Js,disabled:wn.trim().length===0||Zt,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:Zt?"Creating…":"Create"})]})]})}),He.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(_f,{open:He.open,onClose:()=>ft(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:He.tab,onChangeTab:m=>ft(A=>({...A,tab:m})),agentBehaviorInitialDomain:He.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{Pn(m),m||bn()},devMode:a,onToggleDevMode:c,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:k,selectedWorkspaceId:u,onSelectWorkspace:g,onboarding:e,authToken:null,embedMode:!1})}),it&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Rf,{open:it,selectedWorkspaceId:u,onClose:()=>at(!1)})}),(he==="sessions"||he==="active"||he==="blocked"||he==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cf,{open:he==="sessions"||he==="active"||he==="blocked"||he==="failed",onClose:()=>Ke(null),mode:he==="active"||he==="blocked"||he==="failed"?he:"sessions",sessions:Z,onOpenSession:m=>{Qe(m.id),Ke(null)},onRunAction:async(m,A)=>{await en(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>h(),onSetNotice:m=>M(m)})}),he==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Mf,{open:he==="decisions",onClose:()=>Ke(null),decisions:xe?j.decisions:[],onApproveDecision:_,onRejectDecision:U,onApproveAll:le,onBulkDecisionAction:V})}),he==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Tf,{open:he==="outbox",onClose:()=>Ke(null),outbox:j.outbox,onOpenSettings:()=>{Ke(null),Ht("orgx")},onRefresh:()=>{h()}})}),he==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ef,{open:he==="handoffs",onClose:()=>Ke(null),handoffs:j.handoffs})}),n.jsx(sh,{}),Ut&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:n.jsx("div",{className:"relative w-full max-w-lg max-h-[80vh] overflow-hidden rounded-xl border border-subtle bg-[#0E0F11] shadow-2xl",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-8 text-center text-secondary",children:"Loading…"}),children:n.jsx(Af,{item:Ut,actions:Qn,onClose:()=>gt(null),onNavigate:xs,currentIndex:Xt,totalCount:Ct.length,decisions:xe?j.decisions:void 0,onApproveDecision:_,onRejectDecision:U})})})}),et&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Df,{target:et,onClose:()=>kt(null),onPlayWorkstream:async(m,A,L)=>{const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,agentId:L??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const G=await S.json().catch(()=>null);M(Dn((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Failed to dispatch workstream (${S.status})`));return}M("Dispatched workstream."),h()},onStartAutoContinue:async(m,A,L)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:"top"})});const S=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,agentId:L??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const G=await S.json().catch(()=>null);M(Dn((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Failed to start auto-continue (${S.status})`));return}M("Auto-continue started."),h()},onMoveWorkstream:async(m,A,L)=>{const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:L})});if(!S.ok){const G=await S.json().catch(()=>null);M(Dn((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Move failed (${S.status})`));return}M(`Moved workstream to ${L}.`),h()},onRemoveFromQueue:async(m,A)=>{const L=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!L.ok){const S=await L.json().catch(()=>null);M(Dn((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${L.status})`));return}M("Removed workstream from queue."),h()},onOpenSession:Qe,onFocusRunId:Ot,onOpenInitiative:xt,onReviewActivity:Zs,onOpenDecisions:()=>Wn(),onAcceptSlice:An,onRejectSlice:gs})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Zc();const ih=new zl({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Bl.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(ql,{client:ih,children:n.jsx(Zf,{})})}));export{lu as $,$t as A,el as B,hh as C,ls as D,yn as E,us as F,Qm as G,ph as H,bh as I,_s as J,Mt as K,Ks as L,ti as M,ld as N,Od as O,Hs as P,Bd as Q,sn as R,Hd as S,Gd as T,od as U,xh as V,ec as W,fh as X,bu as Y,yh as Z,kn as _,Hu as a,mh as a0,tr as a1,Qr as a2,_t as b,Oc as c,E as d,pm as e,Nh as f,As as g,In as h,Pt as i,wh as j,fl as k,kh as l,jh as m,qt as n,vh as o,gh as p,Vn as q,ci as r,Ih as s,Ku as t,jd as u,hs as v,me as w,Bt as x,Gn as y,ds as z};